blob: 0b5838432295d046e19ed6d3febd8a7e32f8fc53 [file] [log] [blame]
Felix Berger3c8edde2016-03-29 02:42:38 +00001//===--- UnnecessaryValueParamCheck.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 "UnnecessaryValueParamCheck.h"
11
12#include "../utils/DeclRefExprUtils.h"
13#include "../utils/FixItHintUtils.h"
14#include "../utils/Matchers.h"
Felix Berger7f882752016-07-01 20:12:15 +000015#include "../utils/TypeTraits.h"
16#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Lex/Lexer.h"
18#include "clang/Lex/Preprocessor.h"
Felix Berger3c8edde2016-03-29 02:42:38 +000019
20using namespace clang::ast_matchers;
21
22namespace clang {
23namespace tidy {
24namespace performance {
25
26namespace {
27
28std::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
Felix Berger7f882752016-07-01 20:12:15 +000034template <typename S>
35bool isSubset(const S &SubsetCandidate, const S &SupersetCandidate) {
36 for (const auto &E : SubsetCandidate)
37 if (SupersetCandidate.count(E) == 0)
38 return false;
39 return true;
40}
41
Felix Berger85f9e8b32016-11-10 01:28:22 +000042bool isReferencedOutsideOfCallExpr(const FunctionDecl &Function,
43 ASTContext &Context) {
44 auto Matches = match(declRefExpr(to(functionDecl(equalsNode(&Function))),
45 unless(hasAncestor(callExpr()))),
46 Context);
47 return !Matches.empty();
48}
49
Felix Berger519de4b2016-12-16 02:47:56 +000050bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Stmt &Stmt,
51 ASTContext &Context) {
52 auto Matches =
53 match(findAll(declRefExpr(
54 equalsNode(&DeclRef),
55 unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
56 whileStmt(), doStmt())))))),
57 Stmt, Context);
58 return Matches.empty();
59}
60
Felix Berger3c8edde2016-03-29 02:42:38 +000061} // namespace
62
Felix Berger7f882752016-07-01 20:12:15 +000063UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
64 StringRef Name, ClangTidyContext *Context)
65 : ClangTidyCheck(Name, Context),
66 IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
67 Options.get("IncludeStyle", "llvm"))) {}
68
Felix Berger3c8edde2016-03-29 02:42:38 +000069void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
70 const auto ExpensiveValueParamDecl =
71 parmVarDecl(hasType(hasCanonicalType(allOf(matchers::isExpensiveToCopy(),
72 unless(referenceType())))),
73 decl().bind("param"));
74 Finder->addMatcher(
Felix Bergere4ab0602016-12-02 14:44:16 +000075 functionDecl(isDefinition(),
76 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
Felix Berger3c8edde2016-03-29 02:42:38 +000077 unless(isInstantiated()),
78 has(typeLoc(forEach(ExpensiveValueParamDecl))),
79 decl().bind("functionDecl")),
80 this);
81}
82
83void 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 const size_t Index = std::find(Function->parameters().begin(),
87 Function->parameters().end(), Param) -
88 Function->parameters().begin();
89 bool IsConstQualified =
90 Param->getType().getCanonicalType().isConstQualified();
91
Etienne Bergeron2c82ebe2016-04-07 14:58:13 +000092 // Skip declarations delayed by late template parsing without a body.
93 if (!Function->getBody())
94 return;
95
Felix Berger3c8edde2016-03-29 02:42:38 +000096 // Do not trigger on non-const value parameters when:
97 // 1. they are in a constructor definition since they can likely trigger
98 // misc-move-constructor-init which will suggest to move the argument.
Felix Berger3c8edde2016-03-29 02:42:38 +000099 if (!IsConstQualified && (llvm::isa<CXXConstructorDecl>(Function) ||
Felix Berger7f882752016-07-01 20:12:15 +0000100 !Function->doesThisDeclarationHaveABody()))
Felix Berger3c8edde2016-03-29 02:42:38 +0000101 return;
Felix Berger7f882752016-07-01 20:12:15 +0000102
103 auto AllDeclRefExprs = utils::decl_ref_expr::allDeclRefExprs(
104 *Param, *Function->getBody(), *Result.Context);
105 auto ConstDeclRefExprs = utils::decl_ref_expr::constReferenceDeclRefExprs(
106 *Param, *Function->getBody(), *Result.Context);
107 // 2. they are not only used as const.
108 if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
109 return;
110
111 // If the parameter is non-const, check if it has a move constructor and is
112 // only referenced once to copy-construct another object or whether it has a
113 // move assignment operator and is only referenced once when copy-assigned.
114 // In this case wrap DeclRefExpr with std::move() to avoid the unnecessary
115 // copy.
116 if (!IsConstQualified) {
117 auto CanonicalType = Param->getType().getCanonicalType();
118 if (AllDeclRefExprs.size() == 1 &&
Felix Berger519de4b2016-12-16 02:47:56 +0000119 !hasLoopStmtAncestor(**AllDeclRefExprs.begin(), *Function->getBody(),
120 *Result.Context) &&
Felix Berger7f882752016-07-01 20:12:15 +0000121 ((utils::type_traits::hasNonTrivialMoveConstructor(CanonicalType) &&
122 utils::decl_ref_expr::isCopyConstructorArgument(
123 **AllDeclRefExprs.begin(), *Function->getBody(),
124 *Result.Context)) ||
125 (utils::type_traits::hasNonTrivialMoveAssignment(CanonicalType) &&
126 utils::decl_ref_expr::isCopyAssignmentArgument(
127 **AllDeclRefExprs.begin(), *Function->getBody(),
128 *Result.Context)))) {
129 handleMoveFix(*Param, **AllDeclRefExprs.begin(), *Result.Context);
130 return;
131 }
132 }
133
Felix Berger3c8edde2016-03-29 02:42:38 +0000134 auto Diag =
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);
Felix Berger85f9e8b32016-11-10 01:28:22 +0000143 // 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.
Felix Berger17934da2016-07-05 14:40:44 +0000148 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
Felix Berger85f9e8b32016-11-10 01:28:22 +0000149 if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
150 isReferencedOutsideOfCallExpr(*Function, *Result.Context))
Felix Berger3c8edde2016-03-29 02:42:38 +0000151 return;
152 for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
153 FunctionDecl = FunctionDecl->getPreviousDecl()) {
154 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +0000155 Diag << utils::fixit::changeVarDeclToReference(CurrentParam,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000156 *Result.Context);
Felix Berger7c6d2892016-11-04 20:51:31 +0000157 // The parameter of each declaration needs to be checked individually as to
158 // whether it is const or not as constness can differ between definition and
159 // declaration.
160 if (!CurrentParam.getType().getCanonicalType().isConstQualified())
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +0000161 Diag << utils::fixit::changeVarDeclToConst(CurrentParam);
Felix Berger3c8edde2016-03-29 02:42:38 +0000162 }
163}
164
Felix Berger7f882752016-07-01 20:12:15 +0000165void UnnecessaryValueParamCheck::registerPPCallbacks(
166 CompilerInstance &Compiler) {
167 Inserter.reset(new utils::IncludeInserter(
168 Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
169 Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
170}
171
172void UnnecessaryValueParamCheck::storeOptions(
173 ClangTidyOptions::OptionMap &Opts) {
174 Options.store(Opts, "IncludeStyle",
175 utils::IncludeSorter::toString(IncludeStyle));
176}
177
178void UnnecessaryValueParamCheck::handleMoveFix(const ParmVarDecl &Var,
179 const DeclRefExpr &CopyArgument,
180 const ASTContext &Context) {
181 auto Diag = diag(CopyArgument.getLocStart(),
182 "parameter %0 is passed by value and only copied once; "
183 "consider moving it to avoid unnecessary copies")
184 << &Var;
185 // Do not propose fixes in macros since we cannot place them correctly.
186 if (CopyArgument.getLocStart().isMacroID())
187 return;
188 const auto &SM = Context.getSourceManager();
Kirill Bobyrev11cea452016-08-01 12:06:18 +0000189 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
190 Context.getLangOpts());
Felix Berger7f882752016-07-01 20:12:15 +0000191 Diag << FixItHint::CreateInsertion(CopyArgument.getLocStart(), "std::move(")
192 << FixItHint::CreateInsertion(EndLoc, ")");
193 if (auto IncludeFixit = Inserter->CreateIncludeInsertion(
194 SM.getFileID(CopyArgument.getLocStart()), "utility",
195 /*IsAngled=*/true))
196 Diag << *IncludeFixit;
197}
198
Felix Berger3c8edde2016-03-29 02:42:38 +0000199} // namespace performance
200} // namespace tidy
201} // namespace clang