1 //===--- UnnecessaryValueParamCheck.cpp - clang-tidy-----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "UnnecessaryValueParamCheck.h"
12 #include "../utils/DeclRefExprUtils.h"
13 #include "../utils/FixItHintUtils.h"
14 #include "../utils/Matchers.h"
15 #include "../utils/TypeTraits.h"
16 #include "clang/Frontend/CompilerInstance.h"
17 #include "clang/Lex/Lexer.h"
18 #include "clang/Lex/Preprocessor.h"
20 using namespace clang::ast_matchers;
24 namespace performance {
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('\''))
35 bool isSubset(const S &SubsetCandidate, const S &SupersetCandidate) {
36 for (const auto &E : SubsetCandidate)
37 if (SupersetCandidate.count(E) == 0)
42 bool isReferencedOutsideOfCallExpr(const FunctionDecl &Function,
43 ASTContext &Context) {
44 auto Matches = match(declRefExpr(to(functionDecl(equalsNode(&Function))),
45 unless(hasAncestor(callExpr()))),
47 return !Matches.empty();
50 bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl,
51 ASTContext &Context) {
53 match(decl(forEachDescendant(declRefExpr(
55 unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
56 whileStmt(), doStmt()))))))),
58 return Matches.empty();
61 bool isExplicitTemplateSpecialization(const FunctionDecl &Function) {
62 if (const auto *SpecializationInfo = Function.getTemplateSpecializationInfo())
63 if (SpecializationInfo->getTemplateSpecializationKind() ==
64 TSK_ExplicitSpecialization)
66 if (const auto *Method = llvm::dyn_cast<CXXMethodDecl>(&Function))
67 if (Method->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
68 Method->getMemberSpecializationInfo()->isExplicitSpecialization())
75 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
76 StringRef Name, ClangTidyContext *Context)
77 : ClangTidyCheck(Name, Context),
78 IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
79 Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
81 void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
82 const auto ExpensiveValueParamDecl =
83 parmVarDecl(hasType(hasCanonicalType(allOf(
84 unless(referenceType()), matchers::isExpensiveToCopy()))),
85 decl().bind("param"));
87 functionDecl(hasBody(stmt()), isDefinition(), unless(isImplicit()),
88 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
89 has(typeLoc(forEach(ExpensiveValueParamDecl))),
90 unless(isInstantiated()), decl().bind("functionDecl")),
94 void UnnecessaryValueParamCheck::check(const MatchFinder::MatchResult &Result) {
95 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>("param");
96 const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>("functionDecl");
97 const size_t Index = std::find(Function->parameters().begin(),
98 Function->parameters().end(), Param) -
99 Function->parameters().begin();
100 bool IsConstQualified =
101 Param->getType().getCanonicalType().isConstQualified();
103 auto AllDeclRefExprs = utils::decl_ref_expr::allDeclRefExprs(
104 *Param, *Function, *Result.Context);
105 auto ConstDeclRefExprs = utils::decl_ref_expr::constReferenceDeclRefExprs(
106 *Param, *Function, *Result.Context);
108 // Do not trigger on non-const value parameters when they are not only used as
110 if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
113 // If the parameter is non-const, check if it has a move constructor and is
114 // only referenced once to copy-construct another object or whether it has a
115 // move assignment operator and is only referenced once when copy-assigned.
116 // In this case wrap DeclRefExpr with std::move() to avoid the unnecessary
118 if (!IsConstQualified && AllDeclRefExprs.size() == 1) {
119 auto CanonicalType = Param->getType().getCanonicalType();
120 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
122 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
123 ((utils::type_traits::hasNonTrivialMoveConstructor(CanonicalType) &&
124 utils::decl_ref_expr::isCopyConstructorArgument(
125 DeclRefExpr, *Function, *Result.Context)) ||
126 (utils::type_traits::hasNonTrivialMoveAssignment(CanonicalType) &&
127 utils::decl_ref_expr::isCopyAssignmentArgument(
128 DeclRefExpr, *Function, *Result.Context)))) {
129 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
135 diag(Param->getLocation(),
136 IsConstQualified ? "the const qualified parameter %0 is "
137 "copied for each invocation; consider "
138 "making it a reference"
139 : "the parameter %0 is copied for each "
140 "invocation but only used as a const reference; "
141 "consider making it a const reference")
142 << paramNameOrIndex(Param->getName(), Index);
143 // Do not propose fixes when:
144 // 1. the ParmVarDecl is in a macro, since we cannot place them correctly
145 // 2. the function is virtual as it might break overrides
146 // 3. the function is referenced outside of a call expression within the
147 // compilation unit as the signature change could introduce build errors.
148 // 4. the function is an explicit template specialization.
149 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
150 if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
151 isReferencedOutsideOfCallExpr(*Function, *Result.Context) ||
152 isExplicitTemplateSpecialization(*Function))
154 for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
155 FunctionDecl = FunctionDecl->getPreviousDecl()) {
156 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
157 Diag << utils::fixit::changeVarDeclToReference(CurrentParam,
159 // The parameter of each declaration needs to be checked individually as to
160 // whether it is const or not as constness can differ between definition and
162 if (!CurrentParam.getType().getCanonicalType().isConstQualified())
163 Diag << utils::fixit::changeVarDeclToConst(CurrentParam);
167 void UnnecessaryValueParamCheck::registerPPCallbacks(
168 CompilerInstance &Compiler) {
169 Inserter.reset(new utils::IncludeInserter(
170 Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
171 Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
174 void UnnecessaryValueParamCheck::storeOptions(
175 ClangTidyOptions::OptionMap &Opts) {
176 Options.store(Opts, "IncludeStyle",
177 utils::IncludeSorter::toString(IncludeStyle));
180 void UnnecessaryValueParamCheck::handleMoveFix(const ParmVarDecl &Var,
181 const DeclRefExpr &CopyArgument,
182 const ASTContext &Context) {
183 auto Diag = diag(CopyArgument.getLocStart(),
184 "parameter %0 is passed by value and only copied once; "
185 "consider moving it to avoid unnecessary copies")
187 // Do not propose fixes in macros since we cannot place them correctly.
188 if (CopyArgument.getLocStart().isMacroID())
190 const auto &SM = Context.getSourceManager();
191 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
192 Context.getLangOpts());
193 Diag << FixItHint::CreateInsertion(CopyArgument.getLocStart(), "std::move(")
194 << FixItHint::CreateInsertion(EndLoc, ")");
195 if (auto IncludeFixit = Inserter->CreateIncludeInsertion(
196 SM.getFileID(CopyArgument.getLocStart()), "utility",
198 Diag << *IncludeFixit;
201 } // namespace performance