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