clang-tools 20.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,
79 isRefReturningMethodCallWithConstOverloads,
80 std::vector<StringRef>, ExcludedContainerTypes) {
81 // Match method call expressions where the `this` argument is only used as
82 // const, this will be checked in `check()` part. This returned reference is
83 // highly likely to outlive the local const reference of the variable being
84 // declared. The assumption is that the reference being returned either points
85 // to a global static variable or to a member of the called object.
86 const auto MethodDecl =
87 cxxMethodDecl(returns(hasCanonicalType(referenceType())))
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 isRefReturningMethodCallWithConstOverloads(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(
263 LocalVarCopiedFrom(anyOf(
264 isConstRefReturningFunctionCall(),
265 isRefReturningMethodCallWithConstOverloads(ExcludedContainerTypes))),
266 this);
267
268 Finder->addMatcher(LocalVarCopiedFrom(declRefExpr(
269 to(varDecl(hasLocalStorage()).bind(OldVarDeclId)))),
270 this);
271}
272
274 const MatchFinder::MatchResult &Result) {
275 const auto &NewVar = *Result.Nodes.getNodeAs<VarDecl>("newVarDecl");
276 const auto &BlockStmt = *Result.Nodes.getNodeAs<Stmt>("blockStmt");
277 const auto &VarDeclStmt = *Result.Nodes.getNodeAs<DeclStmt>("declStmt");
278 // Do not propose fixes if the DeclStmt has multiple VarDecls or in
279 // macros since we cannot place them correctly.
280 const bool IssueFix =
281 VarDeclStmt.isSingleDecl() && !NewVar.getLocation().isMacroID();
282 const bool IsVarUnused = isVariableUnused(NewVar, BlockStmt, *Result.Context);
283 const bool IsVarOnlyUsedAsConst =
284 isOnlyUsedAsConst(NewVar, BlockStmt, *Result.Context,
285 // `NewVar` is always of non-pointer type.
286 0);
287 const CheckContext Context{
288 NewVar, BlockStmt, VarDeclStmt, *Result.Context,
289 IssueFix, IsVarUnused, IsVarOnlyUsedAsConst};
290 const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>(OldVarDeclId);
291 const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>(ObjectArgId);
292 const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctorCall");
293
294 TraversalKindScope RAII(*Result.Context, TK_AsIs);
295
296 // A constructor that looks like T(const T& t, bool arg = false) counts as a
297 // copy only when it is called with default arguments for the arguments after
298 // the first.
299 for (unsigned int I = 1; I < CtorCall->getNumArgs(); ++I)
300 if (!CtorCall->getArg(I)->isDefaultArgument())
301 return;
302
303 // Don't apply the check if the variable and its initializer have different
304 // replaced template parameter types. In this case the check triggers for a
305 // template instantiation where the substituted types are the same, but
306 // instantiations where the types differ and rely on implicit conversion would
307 // no longer compile if we switched to a reference.
308 if (differentReplacedTemplateParams(
309 Context.Var.getType(), constructorArgumentType(OldVar, Result.Nodes),
310 *Result.Context))
311 return;
312
313 if (OldVar == nullptr) {
314 // `auto NewVar = functionCall();`
315 handleCopyFromMethodReturn(Context, ObjectArg);
316 } else {
317 // `auto NewVar = OldVar;`
318 handleCopyFromLocalVar(Context, *OldVar);
319 }
320}
321
322void UnnecessaryCopyInitialization::handleCopyFromMethodReturn(
323 const CheckContext &Ctx, const VarDecl *ObjectArg) {
324 bool IsConstQualified = Ctx.Var.getType().isConstQualified();
325 if (!IsConstQualified && !Ctx.IsVarOnlyUsedAsConst)
326 return;
327 if (ObjectArg != nullptr &&
328 !isInitializingVariableImmutable(*ObjectArg, Ctx.BlockStmt, Ctx.ASTCtx,
329 ExcludedContainerTypes))
330 return;
332}
333
334void UnnecessaryCopyInitialization::handleCopyFromLocalVar(
335 const CheckContext &Ctx, const VarDecl &OldVar) {
336 if (!Ctx.IsVarOnlyUsedAsConst ||
337 !isInitializingVariableImmutable(OldVar, Ctx.BlockStmt, Ctx.ASTCtx,
338 ExcludedContainerTypes))
339 return;
340 diagnoseCopyFromLocalVar(Ctx, OldVar);
341}
342
344 const CheckContext &Ctx) {
345 auto Diagnostic =
346 diag(Ctx.Var.getLocation(),
347 "the %select{|const qualified }0variable %1 is "
348 "copy-constructed "
349 "from a const reference%select{%select{ but is only used as const "
350 "reference|}0| but is never used}2; consider "
351 "%select{making it a const reference|removing the statement}2")
352 << Ctx.Var.getType().isConstQualified() << &Ctx.Var << Ctx.IsVarUnused;
353 maybeIssueFixes(Ctx, Diagnostic);
354}
355
357 const CheckContext &Ctx, const VarDecl &OldVar) {
358 auto Diagnostic =
359 diag(Ctx.Var.getLocation(),
360 "local copy %1 of the variable %0 is never modified%select{"
361 "| and never used}2; consider %select{avoiding the copy|removing "
362 "the statement}2")
363 << &OldVar << &Ctx.Var << Ctx.IsVarUnused;
364 maybeIssueFixes(Ctx, Diagnostic);
365}
366
367void UnnecessaryCopyInitialization::maybeIssueFixes(
368 const CheckContext &Ctx, DiagnosticBuilder &Diagnostic) {
369 if (Ctx.IssueFix) {
370 if (Ctx.IsVarUnused)
371 recordRemoval(Ctx.VarDeclStmt, Ctx.ASTCtx, Diagnostic);
372 else
373 recordFixes(Ctx.Var, Ctx.ASTCtx, Diagnostic);
374 }
375}
376
379 Options.store(Opts, "AllowedTypes",
381 Options.store(Opts, "ExcludedContainerTypes",
382 utils::options::serializeStringList(ExcludedContainerTypes));
383}
384
385} // 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
static constexpr const char FuncDecl[]