blob: cde30a621bcd25c3438143d71132f68f4c0d6394 [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
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000050bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const Decl &Decl,
Felix Berger519de4b2016-12-16 02:47:56 +000051 ASTContext &Context) {
52 auto Matches =
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000053 match(decl(forEachDescendant(declRefExpr(
Felix Berger519de4b2016-12-16 02:47:56 +000054 equalsNode(&DeclRef),
55 unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000056 whileStmt(), doStmt()))))))),
57 Decl, Context);
Felix Berger519de4b2016-12-16 02:47:56 +000058 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(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000075 functionDecl(hasBody(stmt()), isDefinition(),
Felix Bergere4ab0602016-12-02 14:44:16 +000076 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
Malcolm Parsons3de05a22017-01-23 13:18:08 +000077 unless(anyOf(isInstantiated(), isImplicit())),
Felix Berger3c8edde2016-03-29 02:42:38 +000078 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
Felix Berger7f882752016-07-01 20:12:15 +000092 auto AllDeclRefExprs = utils::decl_ref_expr::allDeclRefExprs(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000093 *Param, *Function, *Result.Context);
Felix Berger7f882752016-07-01 20:12:15 +000094 auto ConstDeclRefExprs = utils::decl_ref_expr::constReferenceDeclRefExprs(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +000095 *Param, *Function, *Result.Context);
96
97 // Do not trigger on non-const value parameters when they are not only used as
98 // const.
Felix Berger7f882752016-07-01 20:12:15 +000099 if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
100 return;
101
102 // If the parameter is non-const, check if it has a move constructor and is
103 // only referenced once to copy-construct another object or whether it has a
104 // move assignment operator and is only referenced once when copy-assigned.
105 // In this case wrap DeclRefExpr with std::move() to avoid the unnecessary
106 // copy.
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000107 if (!IsConstQualified && AllDeclRefExprs.size() == 1) {
Felix Berger7f882752016-07-01 20:12:15 +0000108 auto CanonicalType = Param->getType().getCanonicalType();
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000109 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
110
111 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
Felix Berger7f882752016-07-01 20:12:15 +0000112 ((utils::type_traits::hasNonTrivialMoveConstructor(CanonicalType) &&
113 utils::decl_ref_expr::isCopyConstructorArgument(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000114 DeclRefExpr, *Function, *Result.Context)) ||
Felix Berger7f882752016-07-01 20:12:15 +0000115 (utils::type_traits::hasNonTrivialMoveAssignment(CanonicalType) &&
116 utils::decl_ref_expr::isCopyAssignmentArgument(
Malcolm Parsonscfa7d372017-01-03 12:10:44 +0000117 DeclRefExpr, *Function, *Result.Context)))) {
118 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
Felix Berger7f882752016-07-01 20:12:15 +0000119 return;
120 }
121 }
122
Felix Berger3c8edde2016-03-29 02:42:38 +0000123 auto Diag =
124 diag(Param->getLocation(),
125 IsConstQualified ? "the const qualified parameter %0 is "
126 "copied for each invocation; consider "
127 "making it a reference"
128 : "the parameter %0 is copied for each "
129 "invocation but only used as a const reference; "
130 "consider making it a const reference")
131 << paramNameOrIndex(Param->getName(), Index);
Felix Berger85f9e8b32016-11-10 01:28:22 +0000132 // Do not propose fixes when:
133 // 1. the ParmVarDecl is in a macro, since we cannot place them correctly
134 // 2. the function is virtual as it might break overrides
135 // 3. the function is referenced outside of a call expression within the
136 // compilation unit as the signature change could introduce build errors.
Felix Berger17934da2016-07-05 14:40:44 +0000137 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
Felix Berger85f9e8b32016-11-10 01:28:22 +0000138 if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
139 isReferencedOutsideOfCallExpr(*Function, *Result.Context))
Felix Berger3c8edde2016-03-29 02:42:38 +0000140 return;
141 for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
142 FunctionDecl = FunctionDecl->getPreviousDecl()) {
143 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +0000144 Diag << utils::fixit::changeVarDeclToReference(CurrentParam,
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +0000145 *Result.Context);
Felix Berger7c6d2892016-11-04 20:51:31 +0000146 // The parameter of each declaration needs to be checked individually as to
147 // whether it is const or not as constness can differ between definition and
148 // declaration.
149 if (!CurrentParam.getType().getCanonicalType().isConstQualified())
Etienne Bergeron2a4c00f2016-05-03 02:54:05 +0000150 Diag << utils::fixit::changeVarDeclToConst(CurrentParam);
Felix Berger3c8edde2016-03-29 02:42:38 +0000151 }
152}
153
Felix Berger7f882752016-07-01 20:12:15 +0000154void UnnecessaryValueParamCheck::registerPPCallbacks(
155 CompilerInstance &Compiler) {
156 Inserter.reset(new utils::IncludeInserter(
157 Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
158 Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
159}
160
161void UnnecessaryValueParamCheck::storeOptions(
162 ClangTidyOptions::OptionMap &Opts) {
163 Options.store(Opts, "IncludeStyle",
164 utils::IncludeSorter::toString(IncludeStyle));
165}
166
167void UnnecessaryValueParamCheck::handleMoveFix(const ParmVarDecl &Var,
168 const DeclRefExpr &CopyArgument,
169 const ASTContext &Context) {
170 auto Diag = diag(CopyArgument.getLocStart(),
171 "parameter %0 is passed by value and only copied once; "
172 "consider moving it to avoid unnecessary copies")
173 << &Var;
174 // Do not propose fixes in macros since we cannot place them correctly.
175 if (CopyArgument.getLocStart().isMacroID())
176 return;
177 const auto &SM = Context.getSourceManager();
Kirill Bobyrev11cea452016-08-01 12:06:18 +0000178 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
179 Context.getLangOpts());
Felix Berger7f882752016-07-01 20:12:15 +0000180 Diag << FixItHint::CreateInsertion(CopyArgument.getLocStart(), "std::move(")
181 << FixItHint::CreateInsertion(EndLoc, ")");
182 if (auto IncludeFixit = Inserter->CreateIncludeInsertion(
183 SM.getFileID(CopyArgument.getLocStart()), "utility",
184 /*IsAngled=*/true))
185 Diag << *IncludeFixit;
186}
187
Felix Berger3c8edde2016-03-29 02:42:38 +0000188} // namespace performance
189} // namespace tidy
190} // namespace clang