12 #include "../utils/DeclRefExprUtils.h" 13 #include "../utils/FixItHintUtils.h" 14 #include "../utils/Matchers.h" 15 #include "../utils/OptionsUtils.h" 16 #include "../utils/TypeTraits.h" 17 #include "clang/Frontend/CompilerInstance.h" 18 #include "clang/Lex/Lexer.h" 19 #include "clang/Lex/Preprocessor.h" 25 namespace performance {
29 std::string paramNameOrIndex(StringRef
Name,
size_t Index) {
30 return (Name.empty() ? llvm::Twine(
'#') + llvm::Twine(Index + 1)
31 :
llvm::Twine(
'\'') + Name +
llvm::Twine(
'\''))
35 bool isReferencedOutsideOfCallExpr(
const FunctionDecl &Function,
36 ASTContext &Context) {
37 auto Matches = match(declRefExpr(to(functionDecl(equalsNode(&Function))),
38 unless(hasAncestor(callExpr()))),
40 return !Matches.empty();
43 bool hasLoopStmtAncestor(
const DeclRefExpr &
DeclRef,
const Decl &Decl,
44 ASTContext &Context) {
46 match(decl(forEachDescendant(declRefExpr(
48 unless(hasAncestor(stmt(anyOf(forStmt(), cxxForRangeStmt(),
49 whileStmt(), doStmt()))))))),
51 return Matches.empty();
54 bool isExplicitTemplateSpecialization(
const FunctionDecl &Function) {
55 if (
const auto *SpecializationInfo = Function.getTemplateSpecializationInfo())
56 if (SpecializationInfo->getTemplateSpecializationKind() ==
57 TSK_ExplicitSpecialization)
59 if (
const auto *Method = llvm::dyn_cast<CXXMethodDecl>(&Function))
60 if (
Method->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
61 Method->getMemberSpecializationInfo()->isExplicitSpecialization())
68 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
71 IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
72 Options.getLocalOrGlobal(
"IncludeStyle",
"llvm"))),
81 const auto ExpensiveValueParamDecl = parmVarDecl(
84 unless(anyOf(hasCanonicalType(referenceType()),
85 hasDeclaration(namedDecl(
86 matchers::matchesAnyListedName(AllowedTypes))))))),
87 decl().bind(
"param"));
89 functionDecl(hasBody(stmt()), isDefinition(), unless(isImplicit()),
90 unless(cxxMethodDecl(anyOf(isOverride(), isFinal()))),
91 has(typeLoc(forEach(ExpensiveValueParamDecl))),
92 unless(isInstantiated()), decl().bind(
"functionDecl")),
97 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>(
"param");
98 const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>(
"functionDecl");
100 FunctionParmMutationAnalyzer &Analyzer =
101 MutationAnalyzers.try_emplace(Function, *Function, *Result.Context)
103 if (Analyzer.isMutated(Param))
106 const bool IsConstQualified =
107 Param->getType().getCanonicalType().isConstQualified();
114 if (!IsConstQualified) {
116 *Param, *Function, *Result.Context);
117 if (AllDeclRefExprs.size() == 1) {
118 auto CanonicalType = Param->getType().getCanonicalType();
119 const auto &DeclRefExpr = **AllDeclRefExprs.begin();
121 if (!hasLoopStmtAncestor(DeclRefExpr, *Function, *Result.Context) &&
124 DeclRefExpr, *Function, *Result.Context)) ||
127 DeclRefExpr, *Function, *Result.Context)))) {
128 handleMoveFix(*Param, DeclRefExpr, *Result.Context);
134 const size_t Index = std::find(Function->parameters().begin(),
135 Function->parameters().end(), Param) -
136 Function->parameters().begin();
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->getBeginLoc().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());
187 MutationAnalyzers.clear();
190 void UnnecessaryValueParamCheck::handleMoveFix(
const ParmVarDecl &Var,
191 const DeclRefExpr &CopyArgument,
192 const ASTContext &Context) {
193 auto Diag =
diag(CopyArgument.getBeginLoc(),
194 "parameter %0 is passed by value and only copied once; " 195 "consider moving it to avoid unnecessary copies")
198 if (CopyArgument.getBeginLoc().isMacroID())
200 const auto &SM = Context.getSourceManager();
201 auto EndLoc = Lexer::getLocForEndOfToken(CopyArgument.getLocation(), 0, SM,
202 Context.getLangOpts());
203 Diag << FixItHint::CreateInsertion(CopyArgument.getBeginLoc(),
"std::move(")
204 << FixItHint::CreateInsertion(EndLoc,
")");
205 if (
auto IncludeFixit = Inserter->CreateIncludeInsertion(
206 SM.getFileID(CopyArgument.getBeginLoc()),
"utility",
208 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.
std::string serializeStringList(ArrayRef< std::string > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
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.
std::vector< std::string > parseStringList(StringRef Option)
Parse a semicolon separated list of strings.
llvm::Optional< bool > isExpensiveToCopy(QualType Type, const ASTContext &Context)
Returns true if Type is expensive to copy.
static constexpr llvm::StringLiteral Name
std::map< std::string, std::string > OptionMap
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
===– 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.
const SymbolIndex * Index
FixItHint changeVarDeclToReference(const VarDecl &Var, ASTContext &Context)
Creates fix to make VarDecl a reference by adding &.