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