1 //===--- ForRangeCopyCheck.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 "ForRangeCopyCheck.h"
10 #include "../utils/DeclRefExprUtils.h"
11 #include "../utils/FixItHintUtils.h"
12 #include "../utils/Matchers.h"
13 #include "../utils/OptionsUtils.h"
14 #include "../utils/TypeTraits.h"
15 #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
16 #include "clang/Basic/Diagnostic.h"
17 
18 using namespace clang::ast_matchers;
19 
20 namespace clang {
21 namespace tidy {
22 namespace performance {
23 
ForRangeCopyCheck(StringRef Name,ClangTidyContext * Context)24 ForRangeCopyCheck::ForRangeCopyCheck(StringRef Name, ClangTidyContext *Context)
25     : ClangTidyCheck(Name, Context),
26       WarnOnAllAutoCopies(Options.get("WarnOnAllAutoCopies", false)),
27       AllowedTypes(
28           utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
29 
storeOptions(ClangTidyOptions::OptionMap & Opts)30 void ForRangeCopyCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
31   Options.store(Opts, "WarnOnAllAutoCopies", WarnOnAllAutoCopies);
32   Options.store(Opts, "AllowedTypes",
33                 utils::options::serializeStringList(AllowedTypes));
34 }
35 
registerMatchers(MatchFinder * Finder)36 void ForRangeCopyCheck::registerMatchers(MatchFinder *Finder) {
37   // Match loop variables that are not references or pointers or are already
38   // initialized through MaterializeTemporaryExpr which indicates a type
39   // conversion.
40   auto HasReferenceOrPointerTypeOrIsAllowed = hasType(qualType(
41       unless(anyOf(hasCanonicalType(anyOf(referenceType(), pointerType())),
42                    hasDeclaration(namedDecl(
43                        matchers::matchesAnyListedName(AllowedTypes)))))));
44   auto IteratorReturnsValueType = cxxOperatorCallExpr(
45       hasOverloadedOperatorName("*"),
46       callee(
47           cxxMethodDecl(returns(unless(hasCanonicalType(referenceType()))))));
48   auto LoopVar =
49       varDecl(HasReferenceOrPointerTypeOrIsAllowed,
50               unless(hasInitializer(expr(hasDescendant(expr(anyOf(
51                   materializeTemporaryExpr(), IteratorReturnsValueType)))))));
52   Finder->addMatcher(
53       traverse(ast_type_traits::TK_AsIs,
54                cxxForRangeStmt(hasLoopVariable(LoopVar.bind("loopVar")))
55                    .bind("forRange")),
56       this);
57 }
58 
check(const MatchFinder::MatchResult & Result)59 void ForRangeCopyCheck::check(const MatchFinder::MatchResult &Result) {
60   const auto *Var = Result.Nodes.getNodeAs<VarDecl>("loopVar");
61 
62   // Ignore code in macros since we can't place the fixes correctly.
63   if (Var->getBeginLoc().isMacroID())
64     return;
65   if (handleConstValueCopy(*Var, *Result.Context))
66     return;
67   const auto *ForRange = Result.Nodes.getNodeAs<CXXForRangeStmt>("forRange");
68   handleCopyIsOnlyConstReferenced(*Var, *ForRange, *Result.Context);
69 }
70 
handleConstValueCopy(const VarDecl & LoopVar,ASTContext & Context)71 bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl &LoopVar,
72                                              ASTContext &Context) {
73   if (WarnOnAllAutoCopies) {
74     // For aggressive check just test that loop variable has auto type.
75     if (!isa<AutoType>(LoopVar.getType()))
76       return false;
77   } else if (!LoopVar.getType().isConstQualified()) {
78     return false;
79   }
80   llvm::Optional<bool> Expensive =
81       utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
82   if (!Expensive || !*Expensive)
83     return false;
84   auto Diagnostic =
85       diag(LoopVar.getLocation(),
86            "the loop variable's type is not a reference type; this creates a "
87            "copy in each iteration; consider making this a reference")
88       << utils::fixit::changeVarDeclToReference(LoopVar, Context);
89   if (!LoopVar.getType().isConstQualified()) {
90     if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
91             LoopVar, Context, DeclSpec::TQ::TQ_const))
92       Diagnostic << *Fix;
93   }
94   return true;
95 }
96 
handleCopyIsOnlyConstReferenced(const VarDecl & LoopVar,const CXXForRangeStmt & ForRange,ASTContext & Context)97 bool ForRangeCopyCheck::handleCopyIsOnlyConstReferenced(
98     const VarDecl &LoopVar, const CXXForRangeStmt &ForRange,
99     ASTContext &Context) {
100   llvm::Optional<bool> Expensive =
101       utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
102   if (LoopVar.getType().isConstQualified() || !Expensive || !*Expensive)
103     return false;
104   // We omit the case where the loop variable is not used in the loop body. E.g.
105   //
106   // for (auto _ : benchmark_state) {
107   // }
108   //
109   // Because the fix (changing to `const auto &`) will introduce an unused
110   // compiler warning which can't be suppressed.
111   // Since this case is very rare, it is safe to ignore it.
112   if (!ExprMutationAnalyzer(*ForRange.getBody(), Context).isMutated(&LoopVar) &&
113       !utils::decl_ref_expr::allDeclRefExprs(LoopVar, *ForRange.getBody(),
114                                              Context)
115            .empty()) {
116     auto Diag = diag(
117         LoopVar.getLocation(),
118         "loop variable is copied but only used as const reference; consider "
119         "making it a const reference");
120 
121     if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
122             LoopVar, Context, DeclSpec::TQ::TQ_const))
123       Diag << *Fix << utils::fixit::changeVarDeclToReference(LoopVar, Context);
124 
125     return true;
126   }
127   return false;
128 }
129 
130 } // namespace performance
131 } // namespace tidy
132 } // namespace clang
133