clang-tools 23.0.0git
UnnecessaryCopyInitializationCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12#include "../utils/LexerUtils.h"
13#include "../utils/Matchers.h"
15#include "clang/AST/Decl.h"
16#include "clang/Basic/Diagnostic.h"
17#include <optional>
18
19using namespace clang::ast_matchers;
20
24
25static constexpr StringRef ObjectArgId = "objectArg";
26static constexpr StringRef InitFunctionCallId = "initFunctionCall";
27static constexpr StringRef MethodDeclId = "methodDecl";
28static constexpr StringRef FunctionDeclId = "functionDecl";
29static constexpr StringRef OldVarDeclId = "oldVarDecl";
30
31static void recordFixes(const VarDecl &Var, ASTContext &Context,
32 DiagnosticBuilder &Diagnostic) {
33 Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
34 if (!Var.getType().isLocalConstQualified()) {
35 if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
36 Var, Context, Qualifiers::Const))
37 Diagnostic << *Fix;
38 }
39}
40
41static std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
42 SourceManager &SM) {
43 bool Invalid = false;
44 const char *TextAfter = SM.getCharacterData(Loc, &Invalid);
45 if (Invalid)
46 return std::nullopt;
47 const size_t Offset = std::strcspn(TextAfter, "\n");
48 return Loc.getLocWithOffset(TextAfter[Offset] == '\0' ? Offset : Offset + 1);
49}
50
51static void recordRemoval(const DeclStmt &Stmt, ASTContext &Context,
52 DiagnosticBuilder &Diagnostic) {
53 auto &SM = Context.getSourceManager();
54 // Attempt to remove trailing comments as well.
55 auto Tok = utils::lexer::findNextTokenSkippingComments(Stmt.getEndLoc(), SM,
56 Context.getLangOpts());
57 std::optional<SourceLocation> PastNewLine =
58 firstLocAfterNewLine(Stmt.getEndLoc(), SM);
59 if (Tok && PastNewLine) {
60 auto BeforeFirstTokenAfterComment = Tok->getLocation().getLocWithOffset(-1);
61 // Remove until the end of the line or the end of a trailing comment which
62 // ever comes first.
63 auto End =
64 SM.isBeforeInTranslationUnit(*PastNewLine, BeforeFirstTokenAfterComment)
65 ? *PastNewLine
66 : BeforeFirstTokenAfterComment;
67 Diagnostic << FixItHint::CreateRemoval(
68 SourceRange(Stmt.getBeginLoc(), End));
69 } else {
70 Diagnostic << FixItHint::CreateRemoval(Stmt.getSourceRange());
71 }
72}
73
74namespace {
75
76AST_MATCHER_FUNCTION_P(StatementMatcher,
77 isRefReturningMethodCallWithConstOverloads,
78 std::vector<StringRef>, ExcludedContainerTypes) {
79 // Match method call expressions where the `this` argument is only used as
80 // const, this will be checked in `check()` part. This returned reference is
81 // highly likely to outlive the local const reference of the variable being
82 // declared. The assumption is that the reference being returned either points
83 // to a global static variable or to a member of the called object.
84 const auto MethodDecl =
85 cxxMethodDecl(returns(hasCanonicalType(referenceType())))
86 .bind(MethodDeclId);
87 const auto ReceiverExpr =
88 ignoringParenImpCasts(declRefExpr(to(varDecl().bind(ObjectArgId))));
89 const auto OnExpr = anyOf(
90 // Direct reference to `*this`: `a.f()` or `a->f()`.
91 ReceiverExpr,
92 // Access through dereference, typically used for `operator[]`: `(*a)[3]`.
93 unaryOperator(hasOperatorName("*"), hasUnaryOperand(ReceiverExpr)));
94 const auto ReceiverType =
95 hasCanonicalType(recordType(hasDeclaration(namedDecl(unless(
96 matchers::matchesAnyListedRegexName(ExcludedContainerTypes))))));
97
98 return expr(
99 anyOf(cxxMemberCallExpr(callee(MethodDecl), on(OnExpr),
100 thisPointerType(ReceiverType)),
101 cxxOperatorCallExpr(callee(MethodDecl), hasArgument(0, OnExpr),
102 hasArgument(0, hasType(ReceiverType)))));
103}
104
105AST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); }
106
107AST_MATCHER_FUNCTION(StatementMatcher, isConstRefReturningFunctionCall) {
108 // Only allow initialization of a const reference from a free function or
109 // static member function if it has no arguments. Otherwise it could return
110 // an alias to one of its arguments and the arguments need to be checked
111 // for const use as well.
112 return callExpr(argumentCountIs(0),
113 callee(functionDecl(returns(hasCanonicalType(
114 matchers::isReferenceToConst())),
115 unless(cxxMethodDecl(unless(isStatic()))))
116 .bind(FunctionDeclId)))
117 .bind(InitFunctionCallId);
118}
119
120AST_MATCHER_FUNCTION_P(StatementMatcher, initializerReturnsReferenceToConst,
121 std::vector<StringRef>, ExcludedContainerTypes) {
122 auto OldVarDeclRef =
123 declRefExpr(to(varDecl(hasLocalStorage()).bind(OldVarDeclId)));
124 return expr(
125 anyOf(isConstRefReturningFunctionCall(),
126 isRefReturningMethodCallWithConstOverloads(ExcludedContainerTypes),
127 ignoringImpCasts(OldVarDeclRef),
128 ignoringImpCasts(unaryOperator(hasOperatorName("&"),
129 hasUnaryOperand(OldVarDeclRef)))));
130}
131
132} // namespace
133
134// This checks that the variable itself is only used as const, and also makes
135// sure that it does not reference another variable that could be modified in
136// the BlockStmt. It does this by checking the following:
137// 1. If the variable is neither a reference nor a pointer then the
138// isOnlyUsedAsConst() check is sufficient.
139// 2. If the (reference or pointer) variable is not initialized in a DeclStmt in
140// the BlockStmt. In this case its pointee is likely not modified (unless it
141// is passed as an alias into the method as well).
142// 3. If the reference is initialized from a reference to const. This is
143// the same set of criteria we apply when identifying the unnecessary copied
144// variable in this check to begin with. In this case we check whether the
145// object arg or variable that is referenced is immutable as well.
147 const VarDecl &InitializingVar, const Stmt &BlockStmt, ASTContext &Context,
148 const std::vector<StringRef> &ExcludedContainerTypes) {
149 const QualType T = InitializingVar.getType().getCanonicalType();
150 if (!isOnlyUsedAsConst(InitializingVar, BlockStmt, Context,
151 T->isPointerType() ? 1 : 0))
152 return false;
153
154 // The variable is a value type and we know it is only used as const. Safe
155 // to reference it and avoid the copy.
156 if (!isa<ReferenceType, PointerType>(T))
157 return true;
158
159 // The reference or pointer is not declared and hence not initialized anywhere
160 // in the function. We assume its pointee is not modified then.
161 if (!InitializingVar.isLocalVarDecl() || !InitializingVar.hasInit())
162 return true;
163
164 auto Matches =
165 match(initializerReturnsReferenceToConst(ExcludedContainerTypes),
166 *InitializingVar.getInit(), Context);
167 // The reference is initialized from a free function without arguments
168 // returning a const reference. This is a global immutable object.
169 if (selectFirst<CallExpr>(InitFunctionCallId, Matches) != nullptr)
170 return true;
171 // Check that the object argument is immutable as well.
172 if (const auto *OrigVar = selectFirst<VarDecl>(ObjectArgId, Matches))
173 return isInitializingVariableImmutable(*OrigVar, BlockStmt, Context,
174 ExcludedContainerTypes);
175 // Check that the old variable we reference is immutable as well.
176 if (const auto *OrigVar = selectFirst<VarDecl>(OldVarDeclId, Matches))
177 return isInitializingVariableImmutable(*OrigVar, BlockStmt, Context,
178 ExcludedContainerTypes);
179
180 return false;
181}
182
183static bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt,
184 ASTContext &Context) {
185 return allDeclRefExprs(Var, BlockStmt, Context).empty();
186}
187
188static const SubstTemplateTypeParmType *
189getSubstitutedType(const QualType &Type, ASTContext &Context) {
190 auto Matches = match(
191 qualType(anyOf(substTemplateTypeParmType().bind("subst"),
192 hasDescendant(substTemplateTypeParmType().bind("subst")))),
193 Type, Context);
194 return selectFirst<SubstTemplateTypeParmType>("subst", Matches);
195}
196
197static bool differentReplacedTemplateParams(const QualType &VarType,
198 const QualType &InitializerType,
199 ASTContext &Context) {
200 if (const SubstTemplateTypeParmType *VarTmplType =
201 getSubstitutedType(VarType, Context)) {
202 if (const SubstTemplateTypeParmType *InitializerTmplType =
203 getSubstitutedType(InitializerType, Context)) {
204 const TemplateTypeParmDecl *VarTTP = VarTmplType->getReplacedParameter();
205 const TemplateTypeParmDecl *InitTTP =
206 InitializerTmplType->getReplacedParameter();
207 return (VarTTP->getDepth() != InitTTP->getDepth() ||
208 VarTTP->getIndex() != InitTTP->getIndex() ||
209 VarTTP->isParameterPack() != InitTTP->isParameterPack());
210 }
211 }
212 return false;
213}
214
215static QualType constructorArgumentType(const VarDecl *OldVar,
216 const BoundNodes &Nodes) {
217 if (OldVar)
218 return OldVar->getType();
219 if (const auto *FuncDecl = Nodes.getNodeAs<FunctionDecl>(FunctionDeclId))
220 return FuncDecl->getReturnType();
221 const auto *MethodDecl = Nodes.getNodeAs<CXXMethodDecl>(MethodDeclId);
222 return MethodDecl->getReturnType();
223}
224
226 StringRef Name, ClangTidyContext *Context)
227 : ClangTidyCheck(Name, Context),
228 AllowedTypes(
229 utils::options::parseStringList(Options.get("AllowedTypes", ""))),
230 ExcludedContainerTypes(utils::options::parseStringList(
231 Options.get("ExcludedContainerTypes", ""))) {}
232
234 auto LocalVarCopiedFrom =
235 [this](const ast_matchers::internal::Matcher<Expr> &CopyCtorArg) {
236 return compoundStmt(
237 forEachDescendant(
238 declStmt(
239 unless(has(decompositionDecl())),
240 has(varDecl(
241 hasLocalStorage(),
242 hasType(qualType(
243 hasCanonicalType(allOf(
244 matchers::isExpensiveToCopy(),
245 unless(hasDeclaration(namedDecl(
246 hasName("::std::function")))))),
247 unless(hasDeclaration(namedDecl(
249 AllowedTypes)))))),
250 unless(isImplicit()),
251 hasInitializer(traverse(
252 TK_AsIs,
253 cxxConstructExpr(
254 hasDeclaration(cxxConstructorDecl(
255 isCopyConstructor())),
256 hasArgument(0, CopyCtorArg))
257 .bind("ctorCall"))))
258 .bind("newVarDecl")))
259 .bind("declStmt")))
260 .bind("blockStmt");
261 };
262
263 Finder->addMatcher(
264 LocalVarCopiedFrom(anyOf(
265 isConstRefReturningFunctionCall(),
266 isRefReturningMethodCallWithConstOverloads(ExcludedContainerTypes))),
267 this);
268
269 Finder->addMatcher(LocalVarCopiedFrom(declRefExpr(
270 to(varDecl(hasLocalStorage()).bind(OldVarDeclId)))),
271 this);
272}
273
275 const MatchFinder::MatchResult &Result) {
276 const auto &NewVar = *Result.Nodes.getNodeAs<VarDecl>("newVarDecl");
277 const auto &BlockStmt = *Result.Nodes.getNodeAs<Stmt>("blockStmt");
278 const auto &VarDeclStmt = *Result.Nodes.getNodeAs<DeclStmt>("declStmt");
279 // Do not propose fixes if the DeclStmt has multiple VarDecls or in
280 // macros since we cannot place them correctly.
281 const bool IssueFix =
282 VarDeclStmt.isSingleDecl() && !NewVar.getLocation().isMacroID();
283 const bool IsVarUnused = isVariableUnused(NewVar, BlockStmt, *Result.Context);
284 const bool IsVarOnlyUsedAsConst =
285 isOnlyUsedAsConst(NewVar, BlockStmt, *Result.Context,
286 // `NewVar` is always of non-pointer type.
287 0);
288 const CheckContext Context{
289 NewVar, BlockStmt, VarDeclStmt, *Result.Context,
290 IssueFix, IsVarUnused, IsVarOnlyUsedAsConst};
291 const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>(OldVarDeclId);
292 const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>(ObjectArgId);
293 const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctorCall");
294
295 const TraversalKindScope RAII(*Result.Context, TK_AsIs);
296
297 // A constructor that looks like T(const T& t, bool arg = false) counts as a
298 // copy only when it is called with default arguments for the arguments after
299 // the first.
300 for (unsigned int I = 1; I < CtorCall->getNumArgs(); ++I)
301 if (!CtorCall->getArg(I)->isDefaultArgument())
302 return;
303
304 // Don't apply the check if the variable and its initializer have different
305 // replaced template parameter types. In this case the check triggers for a
306 // template instantiation where the substituted types are the same, but
307 // instantiations where the types differ and rely on implicit conversion would
308 // no longer compile if we switched to a reference.
310 Context.Var.getType(), constructorArgumentType(OldVar, Result.Nodes),
311 *Result.Context))
312 return;
313
314 if (OldVar == nullptr) {
315 // `auto NewVar = functionCall();`
316 handleCopyFromMethodReturn(Context, ObjectArg);
317 } else {
318 // `auto NewVar = OldVar;`
319 handleCopyFromLocalVar(Context, *OldVar);
320 }
321}
322
323void UnnecessaryCopyInitializationCheck::handleCopyFromMethodReturn(
324 const CheckContext &Ctx, const VarDecl *ObjectArg) {
325 const bool IsConstQualified = Ctx.Var.getType().isConstQualified();
326 if (!IsConstQualified && !Ctx.IsVarOnlyUsedAsConst)
327 return;
328 if (ObjectArg != nullptr &&
329 !isInitializingVariableImmutable(*ObjectArg, Ctx.BlockStmt, Ctx.ASTCtx,
330 ExcludedContainerTypes))
331 return;
333}
334
335void UnnecessaryCopyInitializationCheck::handleCopyFromLocalVar(
336 const CheckContext &Ctx, const VarDecl &OldVar) {
337 if (!Ctx.IsVarOnlyUsedAsConst ||
338 !isInitializingVariableImmutable(OldVar, Ctx.BlockStmt, Ctx.ASTCtx,
339 ExcludedContainerTypes))
340 return;
341 diagnoseCopyFromLocalVar(Ctx, OldVar);
342}
343
345 const CheckContext &Ctx) {
346 auto Diagnostic =
347 diag(Ctx.Var.getLocation(),
348 "the %select{|const qualified }0variable %1 of type %2 is "
349 "copy-constructed "
350 "from a const reference%select{%select{ but is only used as const "
351 "reference|}0| but is never used}3; consider "
352 "%select{making it a const reference|removing the statement}3")
353 << Ctx.Var.getType().isConstQualified() << &Ctx.Var << Ctx.Var.getType()
354 << Ctx.IsVarUnused;
355 maybeIssueFixes(Ctx, Diagnostic);
356}
357
359 const CheckContext &Ctx, const VarDecl &OldVar) {
360 auto Diagnostic =
361 diag(Ctx.Var.getLocation(),
362 "local copy %0 of the variable %1 of type %2 is never "
363 "modified%select{"
364 "| and never used}3; consider %select{avoiding the copy|removing "
365 "the statement}3")
366 << &Ctx.Var << &OldVar << Ctx.Var.getType() << Ctx.IsVarUnused;
367 maybeIssueFixes(Ctx, Diagnostic);
368}
369
370void UnnecessaryCopyInitializationCheck::maybeIssueFixes(
371 const CheckContext &Ctx, DiagnosticBuilder &Diagnostic) {
372 if (Ctx.IssueFix) {
373 if (Ctx.IsVarUnused)
374 recordRemoval(Ctx.VarDeclStmt, Ctx.ASTCtx, Diagnostic);
375 else
376 recordFixes(Ctx.Var, Ctx.ASTCtx, Diagnostic);
377 }
378}
379
382 Options.store(Opts, "AllowedTypes",
384 Options.store(Opts, "ExcludedContainerTypes",
385 utils::options::serializeStringList(ExcludedContainerTypes));
386}
387
388} // namespace clang::tidy::performance
static cl::opt< bool > Fix("fix", desc(R"( Apply suggested fixes. Without -fix-errors clang-tidy will bail out if any compilation errors were found. )"), cl::init(false), cl::cat(ClangTidyCategory))
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
virtual void diagnoseCopyFromLocalVar(const CheckContext &Ctx, const VarDecl &OldVar)
AST_MATCHER_FUNCTION_P(ast_matchers::internal::Matcher< Stmt >, comparisonOperatorWithCallee, ast_matchers::internal::Matcher< Decl >, FuncDecl)
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedRegexName(llvm::ArrayRef< StringRef > NameList)
SmallPtrSet< const DeclRefExpr *, 16 > allDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt.
static void recordRemoval(const DeclStmt &Stmt, ASTContext &Context, DiagnosticBuilder &Diagnostic)
static bool isInitializingVariableImmutable(const VarDecl &InitializingVar, const Stmt &BlockStmt, ASTContext &Context, const std::vector< StringRef > &ExcludedContainerTypes)
static bool differentReplacedTemplateParams(const QualType &VarType, const QualType &InitializerType, ASTContext &Context)
static const SubstTemplateTypeParmType * getSubstitutedType(const QualType &Type, ASTContext &Context)
static bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt, ASTContext &Context)
static QualType constructorArgumentType(const VarDecl *OldVar, const BoundNodes &Nodes)
bool isOnlyUsedAsConst(const VarDecl &Var, const Stmt &Stmt, ASTContext &Context, int Indirections)
Returns true if all DeclRefExpr to the variable within Stmt do not modify it. See constReferenceDeclR...
static std::optional< SourceLocation > firstLocAfterNewLine(SourceLocation Loc, SourceManager &SM)
static void recordFixes(const VarDecl &Var, ASTContext &Context, DiagnosticBuilder &Diagnostic)
SmallPtrSet< const DeclRefExpr *, 16 > allDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt.
bool isOnlyUsedAsConst(const VarDecl &Var, const Stmt &Stmt, ASTContext &Context, int Indirections)
Returns true if all DeclRefExpr to the variable within Stmt do not modify it. See constReferenceDeclR...
FixItHint changeVarDeclToReference(const VarDecl &Var, ASTContext &Context)
Creates fix to make VarDecl a reference by adding &.
std::optional< FixItHint > addQualifierToVarDecl(const VarDecl &Var, const ASTContext &Context, Qualifiers::TQ Qualifier, QualifierTarget QualTarget, QualifierPolicy QualPolicy)
Creates fix to qualify VarDecl with the specified Qualifier. Requires that Var is isolated in written...
std::optional< Token > findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
Definition LexerUtils.h:106
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap
static constexpr const char FuncDecl[]