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
9 #include "UnnecessaryCopyInitialization.h"
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
18 namespace clang {
19 namespace tidy {
20 namespace performance {
21 namespace {
22
23 using namespace ::clang::ast_matchers;
24 using llvm::StringRef;
25 using utils::decl_ref_expr::allDeclRefExprs;
26 using utils::decl_ref_expr::isOnlyUsedAsConst;
27
28 static constexpr StringRef ObjectArgId = "objectArg";
29 static constexpr StringRef InitFunctionCallId = "initFunctionCall";
30 static constexpr StringRef MethodDeclId = "methodDecl";
31 static constexpr StringRef FunctionDeclId = "functionDecl";
32 static constexpr StringRef OldVarDeclId = "oldVarDecl";
33
recordFixes(const VarDecl & Var,ASTContext & Context,DiagnosticBuilder & Diagnostic)34 void recordFixes(const VarDecl &Var, ASTContext &Context,
35 DiagnosticBuilder &Diagnostic) {
36 Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
37 if (!Var.getType().isLocalConstQualified()) {
38 if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
39 Var, Context, DeclSpec::TQ::TQ_const))
40 Diagnostic << *Fix;
41 }
42 }
43
firstLocAfterNewLine(SourceLocation Loc,SourceManager & SM)44 llvm::Optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
45 SourceManager &SM) {
46 bool Invalid;
47 const char *TextAfter = SM.getCharacterData(Loc, &Invalid);
48 if (Invalid) {
49 return llvm::None;
50 }
51 size_t Offset = std::strcspn(TextAfter, "\n");
52 return Loc.getLocWithOffset(TextAfter[Offset] == '\0' ? Offset : Offset + 1);
53 }
54
recordRemoval(const DeclStmt & Stmt,ASTContext & Context,DiagnosticBuilder & Diagnostic)55 void 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 llvm::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
AST_MATCHER_FUNCTION_P(StatementMatcher,isConstRefReturningMethodCall,std::vector<std::string>,ExcludedContainerTypes)78 AST_MATCHER_FUNCTION_P(StatementMatcher, isConstRefReturningMethodCall,
79 std::vector<std::string>, 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 return cxxMemberCallExpr(
87 callee(cxxMethodDecl(returns(matchers::isReferenceToConst()))
88 .bind(MethodDeclId)),
89 on(declRefExpr(to(
90 varDecl(
91 unless(hasType(qualType(hasCanonicalType(hasDeclaration(namedDecl(
92 matchers::matchesAnyListedName(ExcludedContainerTypes))))))))
93 .bind(ObjectArgId)))));
94 }
95
AST_MATCHER_FUNCTION(StatementMatcher,isConstRefReturningFunctionCall)96 AST_MATCHER_FUNCTION(StatementMatcher, isConstRefReturningFunctionCall) {
97 // Only allow initialization of a const reference from a free function if it
98 // has no arguments. Otherwise it could return an alias to one of its
99 // arguments and the arguments need to be checked for const use as well.
100 return callExpr(callee(functionDecl(returns(matchers::isReferenceToConst()))
101 .bind(FunctionDeclId)),
102 argumentCountIs(0), unless(callee(cxxMethodDecl())))
103 .bind(InitFunctionCallId);
104 }
105
AST_MATCHER_FUNCTION_P(StatementMatcher,initializerReturnsReferenceToConst,std::vector<std::string>,ExcludedContainerTypes)106 AST_MATCHER_FUNCTION_P(StatementMatcher, initializerReturnsReferenceToConst,
107 std::vector<std::string>, ExcludedContainerTypes) {
108 auto OldVarDeclRef =
109 declRefExpr(to(varDecl(hasLocalStorage()).bind(OldVarDeclId)));
110 return expr(
111 anyOf(isConstRefReturningFunctionCall(),
112 isConstRefReturningMethodCall(ExcludedContainerTypes),
113 ignoringImpCasts(OldVarDeclRef),
114 ignoringImpCasts(unaryOperator(hasOperatorName("&"),
115 hasUnaryOperand(OldVarDeclRef)))));
116 }
117
118 // This checks that the variable itself is only used as const, and also makes
119 // sure that it does not reference another variable that could be modified in
120 // the BlockStmt. It does this by checking the following:
121 // 1. If the variable is neither a reference nor a pointer then the
122 // isOnlyUsedAsConst() check is sufficient.
123 // 2. If the (reference or pointer) variable is not initialized in a DeclStmt in
124 // the BlockStmt. In this case its pointee is likely not modified (unless it
125 // is passed as an alias into the method as well).
126 // 3. If the reference is initialized from a reference to const. This is
127 // the same set of criteria we apply when identifying the unnecessary copied
128 // variable in this check to begin with. In this case we check whether the
129 // object arg or variable that is referenced is immutable as well.
isInitializingVariableImmutable(const VarDecl & InitializingVar,const Stmt & BlockStmt,ASTContext & Context,const std::vector<std::string> & ExcludedContainerTypes)130 static bool isInitializingVariableImmutable(
131 const VarDecl &InitializingVar, const Stmt &BlockStmt, ASTContext &Context,
132 const std::vector<std::string> &ExcludedContainerTypes) {
133 if (!isOnlyUsedAsConst(InitializingVar, BlockStmt, Context))
134 return false;
135
136 QualType T = InitializingVar.getType().getCanonicalType();
137 // The variable is a value type and we know it is only used as const. Safe
138 // to reference it and avoid the copy.
139 if (!isa<ReferenceType, PointerType>(T))
140 return true;
141
142 // The reference or pointer is not declared and hence not initialized anywhere
143 // in the function. We assume its pointee is not modified then.
144 if (!InitializingVar.isLocalVarDecl() || !InitializingVar.hasInit()) {
145 return true;
146 }
147
148 auto Matches =
149 match(initializerReturnsReferenceToConst(ExcludedContainerTypes),
150 *InitializingVar.getInit(), Context);
151 // The reference is initialized from a free function without arguments
152 // returning a const reference. This is a global immutable object.
153 if (selectFirst<CallExpr>(InitFunctionCallId, Matches) != nullptr)
154 return true;
155 // Check that the object argument is immutable as well.
156 if (const auto *OrigVar = selectFirst<VarDecl>(ObjectArgId, Matches))
157 return isInitializingVariableImmutable(*OrigVar, BlockStmt, Context,
158 ExcludedContainerTypes);
159 // Check that the old variable we reference is immutable as well.
160 if (const auto *OrigVar = selectFirst<VarDecl>(OldVarDeclId, Matches))
161 return isInitializingVariableImmutable(*OrigVar, BlockStmt, Context,
162 ExcludedContainerTypes);
163
164 return false;
165 }
166
isVariableUnused(const VarDecl & Var,const Stmt & BlockStmt,ASTContext & Context)167 bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt,
168 ASTContext &Context) {
169 return allDeclRefExprs(Var, BlockStmt, Context).empty();
170 }
171
getSubstitutedType(const QualType & Type,ASTContext & Context)172 const SubstTemplateTypeParmType *getSubstitutedType(const QualType &Type,
173 ASTContext &Context) {
174 auto Matches = match(
175 qualType(anyOf(substTemplateTypeParmType().bind("subst"),
176 hasDescendant(substTemplateTypeParmType().bind("subst")))),
177 Type, Context);
178 return selectFirst<SubstTemplateTypeParmType>("subst", Matches);
179 }
180
differentReplacedTemplateParams(const QualType & VarType,const QualType & InitializerType,ASTContext & Context)181 bool differentReplacedTemplateParams(const QualType &VarType,
182 const QualType &InitializerType,
183 ASTContext &Context) {
184 if (const SubstTemplateTypeParmType *VarTmplType =
185 getSubstitutedType(VarType, Context)) {
186 if (const SubstTemplateTypeParmType *InitializerTmplType =
187 getSubstitutedType(InitializerType, Context)) {
188 return VarTmplType->getReplacedParameter()
189 ->desugar()
190 .getCanonicalType() !=
191 InitializerTmplType->getReplacedParameter()
192 ->desugar()
193 .getCanonicalType();
194 }
195 }
196 return false;
197 }
198
constructorArgumentType(const VarDecl * OldVar,const BoundNodes & Nodes)199 QualType constructorArgumentType(const VarDecl *OldVar,
200 const BoundNodes &Nodes) {
201 if (OldVar) {
202 return OldVar->getType();
203 }
204 if (const auto *FuncDecl = Nodes.getNodeAs<FunctionDecl>(FunctionDeclId)) {
205 return FuncDecl->getReturnType();
206 }
207 const auto *MethodDecl = Nodes.getNodeAs<CXXMethodDecl>(MethodDeclId);
208 return MethodDecl->getReturnType();
209 }
210
211 } // namespace
212
UnnecessaryCopyInitialization(StringRef Name,ClangTidyContext * Context)213 UnnecessaryCopyInitialization::UnnecessaryCopyInitialization(
214 StringRef Name, ClangTidyContext *Context)
215 : ClangTidyCheck(Name, Context),
216 AllowedTypes(
217 utils::options::parseStringList(Options.get("AllowedTypes", ""))),
218 ExcludedContainerTypes(utils::options::parseStringList(
219 Options.get("ExcludedContainerTypes", ""))) {}
220
registerMatchers(MatchFinder * Finder)221 void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) {
222 auto LocalVarCopiedFrom = [this](const internal::Matcher<Expr> &CopyCtorArg) {
223 return compoundStmt(
224 forEachDescendant(
225 declStmt(
226 unless(has(decompositionDecl())),
227 has(varDecl(hasLocalStorage(),
228 hasType(qualType(
229 hasCanonicalType(allOf(
230 matchers::isExpensiveToCopy(),
231 unless(hasDeclaration(namedDecl(
232 hasName("::std::function")))))),
233 unless(hasDeclaration(namedDecl(
234 matchers::matchesAnyListedName(
235 AllowedTypes)))))),
236 unless(isImplicit()),
237 hasInitializer(traverse(
238 TK_AsIs,
239 cxxConstructExpr(
240 hasDeclaration(cxxConstructorDecl(
241 isCopyConstructor())),
242 hasArgument(0, CopyCtorArg))
243 .bind("ctorCall"))))
244 .bind("newVarDecl")))
245 .bind("declStmt")))
246 .bind("blockStmt");
247 };
248
249 Finder->addMatcher(LocalVarCopiedFrom(anyOf(isConstRefReturningFunctionCall(),
250 isConstRefReturningMethodCall(
251 ExcludedContainerTypes))),
252 this);
253
254 Finder->addMatcher(LocalVarCopiedFrom(declRefExpr(
255 to(varDecl(hasLocalStorage()).bind(OldVarDeclId)))),
256 this);
257 }
258
check(const MatchFinder::MatchResult & Result)259 void UnnecessaryCopyInitialization::check(
260 const MatchFinder::MatchResult &Result) {
261 const auto *NewVar = Result.Nodes.getNodeAs<VarDecl>("newVarDecl");
262 const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>(OldVarDeclId);
263 const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>(ObjectArgId);
264 const auto *BlockStmt = Result.Nodes.getNodeAs<Stmt>("blockStmt");
265 const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctorCall");
266 const auto *Stmt = Result.Nodes.getNodeAs<DeclStmt>("declStmt");
267
268 TraversalKindScope RAII(*Result.Context, TK_AsIs);
269
270 // Do not propose fixes if the DeclStmt has multiple VarDecls or in macros
271 // since we cannot place them correctly.
272 bool IssueFix = Stmt->isSingleDecl() && !NewVar->getLocation().isMacroID();
273
274 // A constructor that looks like T(const T& t, bool arg = false) counts as a
275 // copy only when it is called with default arguments for the arguments after
276 // the first.
277 for (unsigned int I = 1; I < CtorCall->getNumArgs(); ++I)
278 if (!CtorCall->getArg(I)->isDefaultArgument())
279 return;
280
281 // Don't apply the check if the variable and its initializer have different
282 // replaced template parameter types. In this case the check triggers for a
283 // template instantiation where the substituted types are the same, but
284 // instantiations where the types differ and rely on implicit conversion would
285 // no longer compile if we switched to a reference.
286 if (differentReplacedTemplateParams(
287 NewVar->getType(), constructorArgumentType(OldVar, Result.Nodes),
288 *Result.Context))
289 return;
290
291 if (OldVar == nullptr) {
292 handleCopyFromMethodReturn(*NewVar, *BlockStmt, *Stmt, IssueFix, ObjectArg,
293 *Result.Context);
294 } else {
295 handleCopyFromLocalVar(*NewVar, *OldVar, *BlockStmt, *Stmt, IssueFix,
296 *Result.Context);
297 }
298 }
299
handleCopyFromMethodReturn(const VarDecl & Var,const Stmt & BlockStmt,const DeclStmt & Stmt,bool IssueFix,const VarDecl * ObjectArg,ASTContext & Context)300 void UnnecessaryCopyInitialization::handleCopyFromMethodReturn(
301 const VarDecl &Var, const Stmt &BlockStmt, const DeclStmt &Stmt,
302 bool IssueFix, const VarDecl *ObjectArg, ASTContext &Context) {
303 bool IsConstQualified = Var.getType().isConstQualified();
304 if (!IsConstQualified && !isOnlyUsedAsConst(Var, BlockStmt, Context))
305 return;
306 if (ObjectArg != nullptr &&
307 !isInitializingVariableImmutable(*ObjectArg, BlockStmt, Context,
308 ExcludedContainerTypes))
309 return;
310 if (isVariableUnused(Var, BlockStmt, Context)) {
311 auto Diagnostic =
312 diag(Var.getLocation(),
313 "the %select{|const qualified }0variable %1 is copy-constructed "
314 "from a const reference but is never used; consider "
315 "removing the statement")
316 << IsConstQualified << &Var;
317 if (IssueFix)
318 recordRemoval(Stmt, Context, Diagnostic);
319 } else {
320 auto Diagnostic =
321 diag(Var.getLocation(),
322 "the %select{|const qualified }0variable %1 is copy-constructed "
323 "from a const reference%select{ but is only used as const "
324 "reference|}0; consider making it a const reference")
325 << IsConstQualified << &Var;
326 if (IssueFix)
327 recordFixes(Var, Context, Diagnostic);
328 }
329 }
330
handleCopyFromLocalVar(const VarDecl & NewVar,const VarDecl & OldVar,const Stmt & BlockStmt,const DeclStmt & Stmt,bool IssueFix,ASTContext & Context)331 void UnnecessaryCopyInitialization::handleCopyFromLocalVar(
332 const VarDecl &NewVar, const VarDecl &OldVar, const Stmt &BlockStmt,
333 const DeclStmt &Stmt, bool IssueFix, ASTContext &Context) {
334 if (!isOnlyUsedAsConst(NewVar, BlockStmt, Context) ||
335 !isInitializingVariableImmutable(OldVar, BlockStmt, Context,
336 ExcludedContainerTypes))
337 return;
338
339 if (isVariableUnused(NewVar, BlockStmt, Context)) {
340 auto Diagnostic = diag(NewVar.getLocation(),
341 "local copy %0 of the variable %1 is never modified "
342 "and never used; "
343 "consider removing the statement")
344 << &NewVar << &OldVar;
345 if (IssueFix)
346 recordRemoval(Stmt, Context, Diagnostic);
347 } else {
348 auto Diagnostic =
349 diag(NewVar.getLocation(),
350 "local copy %0 of the variable %1 is never modified; "
351 "consider avoiding the copy")
352 << &NewVar << &OldVar;
353 if (IssueFix)
354 recordFixes(NewVar, Context, Diagnostic);
355 }
356 }
357
storeOptions(ClangTidyOptions::OptionMap & Opts)358 void UnnecessaryCopyInitialization::storeOptions(
359 ClangTidyOptions::OptionMap &Opts) {
360 Options.store(Opts, "AllowedTypes",
361 utils::options::serializeStringList(AllowedTypes));
362 Options.store(Opts, "ExcludedContainerTypes",
363 utils::options::serializeStringList(ExcludedContainerTypes));
364 }
365
366 } // namespace performance
367 } // namespace tidy
368 } // namespace clang
369