1 //===--- UnnecessaryValueParamCheck.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 "UnnecessaryValueParamCheck.h"
10
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/Frontend/CompilerInstance.h"
17 #include "clang/Lex/Lexer.h"
18 #include "clang/Lex/Preprocessor.h"
19
20 using namespace clang::ast_matchers;
21
22 namespace clang {
23 namespace tidy {
24 namespace performance {
25
26 namespace {
27
paramNameOrIndex(StringRef Name,size_t Index)28 std::string paramNameOrIndex(StringRef Name, size_t Index) {
29 return (Name.empty() ? llvm::Twine('#') + llvm::Twine(Index + 1)
30 : llvm::Twine('\'') + Name + llvm::Twine('\''))
31 .str();
32 }
33
isReferencedOutsideOfCallExpr(const FunctionDecl & Function,ASTContext & Context)34 bool isReferencedOutsideOfCallExpr(const FunctionDecl &Function,
35 ASTContext &Context) {
36 auto Matches = match(declRefExpr(to(functionDecl(equalsNode(&Function))),
37 unless(hasAncestor(callExpr()))),
38 Context);
39 return !Matches.empty();
40 }
41
hasLoopStmtAncestor(const DeclRefExpr & DeclRef,const Decl & Decl,ASTContext & Context)42 bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl,
43 ASTContext &Context) {
44 auto Matches = match(
45 traverse(TK_AsIs,
46 decl(forEachDescendant(declRefExpr(
47 equalsNode(&DeclRef),
48 unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
49 whileStmt(), doStmt())))))))),
50 Decl, Context);
51 return Matches.empty();
52 }
53
54 } // namespace
55
UnnecessaryValueParamCheck(StringRef Name,ClangTidyContext * Context)56 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
57 StringRef Name, ClangTidyContext *Context)
58 : ClangTidyCheck(Name, Context),
59 Inserter(Options.getLocalOrGlobal("IncludeStyle",
60 utils::IncludeSorter::IS_LLVM),
61 areDiagsSelfContained()),
62 AllowedTypes(
63 utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
64
registerMatchers(MatchFinder * Finder)65 void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
66 const auto ExpensiveValueParamDecl = parmVarDecl(
67 hasType(qualType(
68 hasCanonicalType(matchers::isExpensiveToCopy()),
69 unless(anyOf(hasCanonicalType(referenceType()),
70 hasDeclaration(namedDecl(
71 matchers::matchesAnyListedName(AllowedTypes))))))),
72 decl().bind("param"));
73 Finder->addMatcher(
74 traverse(
75 TK_AsIs,
76 functionDecl(hasBody(stmt()), isDefinition(), unless(isImplicit()),
77 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
78 has(typeLoc(forEach(ExpensiveValueParamDecl))),
79 unless(isInstantiated()), decl().bind("functionDecl"))),
80 this);
81 }
82
check(const MatchFinder::MatchResult & Result)83 void UnnecessaryValueParamCheck::check(const MatchFinder::MatchResult &Result) {
84 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>("param");
85 const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>("functionDecl");
86
87 TraversalKindScope RAII(*Result.Context, TK_AsIs);
88
89 FunctionParmMutationAnalyzer &Analyzer =
90 MutationAnalyzers.try_emplace(Function, *Function, *Result.Context)
91 .first->second;
92 if (Analyzer.isMutated(Param))
93 return;
94
95 const bool IsConstQualified =
96 Param->getType().getCanonicalType().isConstQualified();
97
98 // If the parameter is non-const, check if it has a move constructor and is
99 // only referenced once to copy-construct another object or whether it has a
100 // move assignment operator and is only referenced once when copy-assigned.
101 // In this case wrap DeclRefExpr with std::move() to avoid the unnecessary
102 // copy.
103 if (!IsConstQualified) {
104 auto AllDeclRefExprs = utils::decl_ref_expr::allDeclRefExprs(
105 *Param, *Function, *Result.Context);
106 if (AllDeclRefExprs.size() == 1) {
107 auto CanonicalType = Param->getType().getCanonicalType();
108 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
109
110 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
111 ((utils::type_traits::hasNonTrivialMoveConstructor(CanonicalType) &&
112 utils::decl_ref_expr::isCopyConstructorArgument(
113 DeclRefExpr, *Function, *Result.Context)) ||
114 (utils::type_traits::hasNonTrivialMoveAssignment(CanonicalType) &&
115 utils::decl_ref_expr::isCopyAssignmentArgument(
116 DeclRefExpr, *Function, *Result.Context)))) {
117 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
118 return;
119 }
120 }
121 }
122
123 const size_t Index = std::find(Function->parameters().begin(),
124 Function->parameters().end(), Param) -
125 Function->parameters().begin();
126
127 auto Diag =
128 diag(Param->getLocation(),
129 "the %select{|const qualified }0parameter %1 is copied for each "
130 "invocation%select{ but only used as a const reference|}0; consider "
131 "making it a %select{const |}0reference")
132 << IsConstQualified << paramNameOrIndex(Param->getName(), Index);
133 // Do not propose fixes when:
134 // 1. the ParmVarDecl is in a macro, since we cannot place them correctly
135 // 2. the function is virtual as it might break overrides
136 // 3. the function is referenced outside of a call expression within the
137 // compilation unit as the signature change could introduce build errors.
138 // 4. the function is a primary template or an explicit template
139 // specialization.
140 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
141 if (Param->getBeginLoc().isMacroID() || (Method && Method->isVirtual()) ||
142 isReferencedOutsideOfCallExpr(*Function, *Result.Context) ||
143 (Function->getTemplatedKind() != FunctionDecl::TK_NonTemplate))
144 return;
145 for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
146 FunctionDecl = FunctionDecl->getPreviousDecl()) {
147 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
148 Diag << utils::fixit::changeVarDeclToReference(CurrentParam,
149 *Result.Context);
150 // The parameter of each declaration needs to be checked individually as to
151 // whether it is const or not as constness can differ between definition and
152 // declaration.
153 if (!CurrentParam.getType().getCanonicalType().isConstQualified()) {
154 if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
155 CurrentParam, *Result.Context, DeclSpec::TQ::TQ_const))
156 Diag << *Fix;
157 }
158 }
159 }
160
registerPPCallbacks(const SourceManager & SM,Preprocessor * PP,Preprocessor * ModuleExpanderPP)161 void UnnecessaryValueParamCheck::registerPPCallbacks(
162 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
163 Inserter.registerPreprocessor(PP);
164 }
165
storeOptions(ClangTidyOptions::OptionMap & Opts)166 void UnnecessaryValueParamCheck::storeOptions(
167 ClangTidyOptions::OptionMap &Opts) {
168 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
169 Options.store(Opts, "AllowedTypes",
170 utils::options::serializeStringList(AllowedTypes));
171 }
172
onEndOfTranslationUnit()173 void UnnecessaryValueParamCheck::onEndOfTranslationUnit() {
174 MutationAnalyzers.clear();
175 }
176
handleMoveFix(const ParmVarDecl & Var,const DeclRefExpr & CopyArgument,const ASTContext & Context)177 void UnnecessaryValueParamCheck::handleMoveFix(const ParmVarDecl &Var,
178 const DeclRefExpr &CopyArgument,
179 const ASTContext &Context) {
180 auto Diag = diag(CopyArgument.getBeginLoc(),
181 "parameter %0 is passed by value and only copied once; "
182 "consider moving it to avoid unnecessary copies")
183 << &Var;
184 // Do not propose fixes in macros since we cannot place them correctly.
185 if (CopyArgument.getBeginLoc().isMacroID())
186 return;
187 const auto &SM = Context.getSourceManager();
188 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
189 Context.getLangOpts());
190 Diag << FixItHint::CreateInsertion(CopyArgument.getBeginLoc(), "std::move(")
191 << FixItHint::CreateInsertion(EndLoc, ")")
192 << Inserter.createIncludeInsertion(
193 SM.getFileID(CopyArgument.getBeginLoc()), "<utility>");
194 }
195
196 } // namespace performance
197 } // namespace tidy
198 } // namespace clang
199