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