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"))) {}
86 const auto ExpensiveValueParamDecl =
87 parmVarDecl(hasType(hasCanonicalType(allOf(
89 decl().bind(
"param"));
91 functionDecl(hasBody(stmt()), isDefinition(), unless(isImplicit()),
92 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
93 has(typeLoc(forEach(ExpensiveValueParamDecl))),
94 unless(isInstantiated()), decl().bind(
"functionDecl")),
99 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>(
"param");
100 const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>(
"functionDecl");
101 const size_t Index = std::find(Function->parameters().begin(),
102 Function->parameters().end(), Param) -
103 Function->parameters().begin();
104 bool IsConstQualified =
105 Param->getType().getCanonicalType().isConstQualified();
108 *Param, *Function, *Result.Context);
110 *Param, *Function, *Result.Context);
114 if (!isSubset(AllDeclRefExprs, ConstDeclRefExprs))
122 if (!IsConstQualified && AllDeclRefExprs.size() == 1) {
123 auto CanonicalType = Param->getType().getCanonicalType();
124 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
126 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
129 DeclRefExpr, *Function, *Result.Context)) ||
132 DeclRefExpr, *Function, *Result.Context)))) {
133 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
139 diag(Param->getLocation(),
140 IsConstQualified ?
"the const qualified parameter %0 is " 141 "copied for each invocation; consider " 142 "making it a reference" 143 :
"the parameter %0 is copied for each " 144 "invocation but only used as a const reference; " 145 "consider making it a const reference")
146 << paramNameOrIndex(Param->getName(), Index);
153 const auto *Method = llvm::dyn_cast<CXXMethodDecl>(Function);
154 if (Param->getLocStart().isMacroID() || (Method && Method->isVirtual()) ||
155 isReferencedOutsideOfCallExpr(*Function, *Result.Context) ||
156 isExplicitTemplateSpecialization(*Function))
158 for (
const auto *FunctionDecl = Function; FunctionDecl !=
nullptr;
159 FunctionDecl = FunctionDecl->getPreviousDecl()) {
160 const auto &CurrentParam = *FunctionDecl->getParamDecl(Index);
166 if (!CurrentParam.getType().getCanonicalType().isConstQualified())
172 CompilerInstance &Compiler) {
174 Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle));
175 Compiler.getPreprocessor().addPPCallbacks(Inserter->CreatePPCallbacks());
184 void UnnecessaryValueParamCheck::handleMoveFix(
const ParmVarDecl &Var,
185 const DeclRefExpr &CopyArgument,
186 const ASTContext &Context) {
187 auto Diag =
diag(CopyArgument.getLocStart(),
188 "parameter %0 is passed by value and only copied once; " 189 "consider moving it to avoid unnecessary copies")
192 if (CopyArgument.getLocStart().isMacroID())
194 const auto &SM = Context.getSourceManager();
195 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
196 Context.getLangOpts());
197 Diag << FixItHint::CreateInsertion(CopyArgument.getLocStart(),
"std::move(")
198 << FixItHint::CreateInsertion(EndLoc,
")");
199 if (
auto IncludeFixit = Inserter->CreateIncludeInsertion(
200 SM.getFileID(CopyArgument.getLocStart()),
"utility",
202 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.
Some operations such as code completion produce a set of candidates.
SmallPtrSet< const DeclRefExpr *, 16 > allDeclRefExprs(const VarDecl &VarDecl, const Stmt &Stmt, ASTContext &Context)
Returns set of all DeclRefExprs to VarDecl within Stmt.
LangOptions getLangOpts() const
Returns the language options from the context.
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
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
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 &.