clang-tools  8.0.0
ForRangeCopyCheck.cpp
Go to the documentation of this file.
1 //===--- ForRangeCopyCheck.cpp - clang-tidy--------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "ForRangeCopyCheck.h"
11 #include "../utils/DeclRefExprUtils.h"
12 #include "../utils/FixItHintUtils.h"
13 #include "../utils/Matchers.h"
14 #include "../utils/OptionsUtils.h"
15 #include "../utils/TypeTraits.h"
16 #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
17 
18 using namespace clang::ast_matchers;
19 
20 namespace clang {
21 namespace tidy {
22 namespace performance {
23 
24 ForRangeCopyCheck::ForRangeCopyCheck(StringRef Name, ClangTidyContext *Context)
25  : ClangTidyCheck(Name, Context),
26  WarnOnAllAutoCopies(Options.get("WarnOnAllAutoCopies", 0)),
27  AllowedTypes(
28  utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
29 
31  Options.store(Opts, "WarnOnAllAutoCopies", WarnOnAllAutoCopies);
32  Options.store(Opts, "AllowedTypes",
34 }
35 
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 LoopVar = varDecl(
41  hasType(qualType(
42  unless(anyOf(hasCanonicalType(anyOf(referenceType(), pointerType())),
43  hasDeclaration(namedDecl(
44  matchers::matchesAnyListedName(AllowedTypes))))))),
45  unless(hasInitializer(expr(hasDescendant(materializeTemporaryExpr())))));
46  Finder->addMatcher(cxxForRangeStmt(hasLoopVariable(LoopVar.bind("loopVar")))
47  .bind("forRange"),
48  this);
49 }
50 
51 void ForRangeCopyCheck::check(const MatchFinder::MatchResult &Result) {
52  const auto *Var = Result.Nodes.getNodeAs<VarDecl>("loopVar");
53 
54  // Ignore code in macros since we can't place the fixes correctly.
55  if (Var->getBeginLoc().isMacroID())
56  return;
57  if (handleConstValueCopy(*Var, *Result.Context))
58  return;
59  const auto *ForRange = Result.Nodes.getNodeAs<CXXForRangeStmt>("forRange");
60  handleCopyIsOnlyConstReferenced(*Var, *ForRange, *Result.Context);
61 }
62 
63 bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl &LoopVar,
64  ASTContext &Context) {
65  if (WarnOnAllAutoCopies) {
66  // For aggressive check just test that loop variable has auto type.
67  if (!isa<AutoType>(LoopVar.getType()))
68  return false;
69  } else if (!LoopVar.getType().isConstQualified()) {
70  return false;
71  }
72  llvm::Optional<bool> Expensive =
73  utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
74  if (!Expensive || !*Expensive)
75  return false;
76  auto Diagnostic =
77  diag(LoopVar.getLocation(),
78  "the loop variable's type is not a reference type; this creates a "
79  "copy in each iteration; consider making this a reference")
80  << utils::fixit::changeVarDeclToReference(LoopVar, Context);
81  if (!LoopVar.getType().isConstQualified())
82  Diagnostic << utils::fixit::changeVarDeclToConst(LoopVar);
83  return true;
84 }
85 
86 bool ForRangeCopyCheck::handleCopyIsOnlyConstReferenced(
87  const VarDecl &LoopVar, const CXXForRangeStmt &ForRange,
88  ASTContext &Context) {
89  llvm::Optional<bool> Expensive =
90  utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
91  if (LoopVar.getType().isConstQualified() || !Expensive || !*Expensive)
92  return false;
93  // We omit the case where the loop variable is not used in the loop body. E.g.
94  //
95  // for (auto _ : benchmark_state) {
96  // }
97  //
98  // Because the fix (changing to `const auto &`) will introduce an unused
99  // compiler warning which can't be suppressed.
100  // Since this case is very rare, it is safe to ignore it.
101  if (!ExprMutationAnalyzer(*ForRange.getBody(), Context).isMutated(&LoopVar) &&
102  !utils::decl_ref_expr::allDeclRefExprs(LoopVar, *ForRange.getBody(),
103  Context)
104  .empty()) {
105  diag(LoopVar.getLocation(),
106  "loop variable is copied but only used as const reference; consider "
107  "making it a const reference")
109  << utils::fixit::changeVarDeclToReference(LoopVar, Context);
110  return true;
111  }
112  return false;
113 }
114 
115 } // namespace performance
116 } // namespace tidy
117 } // namespace clang
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.
Definition: ClangTidy.cpp:473
std::string serializeStringList(ArrayRef< std::string > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
SmallPtrSet< const DeclRefExpr *, 16 > allDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt.
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
std::vector< std::string > parseStringList(StringRef Option)
Parse a semicolon separated list of strings.
llvm::Optional< bool > isExpensiveToCopy(QualType Type, const ASTContext &Context)
Returns true if Type is expensive to copy.
Definition: TypeTraits.cpp:42
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
static constexpr llvm::StringLiteral Name
std::map< std::string, std::string > OptionMap
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Definition: ClangTidy.cpp:438
FixItHint changeVarDeclToConst(const VarDecl &Var)
Creates fix to make VarDecl const qualified.
FixItHint changeVarDeclToReference(const VarDecl &Var, ASTContext &Context)
Creates fix to make VarDecl a reference by adding &.