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" 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(
78 IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
79 Options.getLocalOrGlobal(
"IncludeStyle",
"llvm"))) {}
82 const auto ExpensiveValueParamDecl =
83 parmVarDecl(hasType(hasCanonicalType(allOf(
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")),
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();
104 *Param, *Function, *Result.Context);
106 *Param, *Function, *Result.Context);
110 if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
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) &&
125 DeclRefExpr, *Function, *Result.Context)) ||
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);
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);
162 if (!CurrentParam.getType().getCanonicalType().isConstQualified())
168 CompilerInstance &Compiler) {
170 Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
171 Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
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")
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;
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
SmallPtrSet< const DeclRefExpr *, 16 > allDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt.
bool isCopyConstructorArgument(const DeclRefExpr &DeclRef, const Decl &Decl, ASTContext &Context)
Returns true if DeclRefExpr is the argument of a copy-constructor call expression within Decl...
static StringRef toString(IncludeStyle Style)
Converts IncludeStyle to string representation.
Base class for all clang-tidy checks.
bool hasNonTrivialMoveConstructor(QualType Type)
Returns true if Type has a non-trivial move constructor.
llvm::Optional< bool > isExpensiveToCopy(QualType Type, const ASTContext &Context)
Returns true if Type is expensive to copy.
SmallPtrSet< const DeclRefExpr *, 16 > constReferenceDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt where VarDecl is guaranteed to be accessed in ...
std::map< std::string, std::string > OptionMap
Produces fixes to insert specified includes to source files, if not yet present.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
bool isCopyAssignmentArgument(const DeclRefExpr &DeclRef, const Decl &Decl, ASTContext &Context)
Returns true if DeclRefExpr is the argument of a copy-assignment operator CallExpr within Decl...
const DeclRefExpr * DeclRef
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
bool hasNonTrivialMoveAssignment(QualType Type)
Return true if Type has a non-trivial move assignment operator.
FixItHint changeVarDeclToConst(const VarDecl &Var)
Creates fix to make VarDecl const qualified.
FixItHint changeVarDeclToReference(const VarDecl &Var, ASTContext &Context)
Creates fix to make VarDecl a reference by adding &.