394 lines · cpp
1//===----------------------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "UnnecessaryCopyInitializationCheck.h"10#include "../utils/DeclRefExprUtils.h"11#include "../utils/FixItHintUtils.h"12#include "../utils/LexerUtils.h"13#include "../utils/Matchers.h"14#include "../utils/OptionsUtils.h"15#include "clang/AST/Decl.h"16#include "clang/Basic/Diagnostic.h"17#include <optional>18 19namespace clang::tidy::performance {20 21using namespace ::clang::ast_matchers;22using llvm::StringRef;23using utils::decl_ref_expr::allDeclRefExprs;24using utils::decl_ref_expr::isOnlyUsedAsConst;25 26static constexpr StringRef ObjectArgId = "objectArg";27static constexpr StringRef InitFunctionCallId = "initFunctionCall";28static constexpr StringRef MethodDeclId = "methodDecl";29static constexpr StringRef FunctionDeclId = "functionDecl";30static constexpr StringRef OldVarDeclId = "oldVarDecl";31 32static void recordFixes(const VarDecl &Var, ASTContext &Context,33 DiagnosticBuilder &Diagnostic) {34 Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);35 if (!Var.getType().isLocalConstQualified()) {36 if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(37 Var, Context, Qualifiers::Const))38 Diagnostic << *Fix;39 }40}41 42static std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,43 SourceManager &SM) {44 bool Invalid = false;45 const char *TextAfter = SM.getCharacterData(Loc, &Invalid);46 if (Invalid) {47 return std::nullopt;48 }49 const size_t Offset = std::strcspn(TextAfter, "\n");50 return Loc.getLocWithOffset(TextAfter[Offset] == '\0' ? Offset : Offset + 1);51}52 53static void recordRemoval(const DeclStmt &Stmt, ASTContext &Context,54 DiagnosticBuilder &Diagnostic) {55 auto &SM = Context.getSourceManager();56 // Attempt to remove trailing comments as well.57 auto Tok = utils::lexer::findNextTokenSkippingComments(Stmt.getEndLoc(), SM,58 Context.getLangOpts());59 std::optional<SourceLocation> PastNewLine =60 firstLocAfterNewLine(Stmt.getEndLoc(), SM);61 if (Tok && PastNewLine) {62 auto BeforeFirstTokenAfterComment = Tok->getLocation().getLocWithOffset(-1);63 // Remove until the end of the line or the end of a trailing comment which64 // ever comes first.65 auto End =66 SM.isBeforeInTranslationUnit(*PastNewLine, BeforeFirstTokenAfterComment)67 ? *PastNewLine68 : BeforeFirstTokenAfterComment;69 Diagnostic << FixItHint::CreateRemoval(70 SourceRange(Stmt.getBeginLoc(), End));71 } else {72 Diagnostic << FixItHint::CreateRemoval(Stmt.getSourceRange());73 }74}75 76namespace {77 78AST_MATCHER_FUNCTION_P(StatementMatcher,79 isRefReturningMethodCallWithConstOverloads,80 std::vector<StringRef>, ExcludedContainerTypes) {81 // Match method call expressions where the `this` argument is only used as82 // const, this will be checked in `check()` part. This returned reference is83 // highly likely to outlive the local const reference of the variable being84 // declared. The assumption is that the reference being returned either points85 // to a global static variable or to a member of the called object.86 const auto MethodDecl =87 cxxMethodDecl(returns(hasCanonicalType(referenceType())))88 .bind(MethodDeclId);89 const auto ReceiverExpr =90 ignoringParenImpCasts(declRefExpr(to(varDecl().bind(ObjectArgId))));91 const auto OnExpr = anyOf(92 // Direct reference to `*this`: `a.f()` or `a->f()`.93 ReceiverExpr,94 // Access through dereference, typically used for `operator[]`: `(*a)[3]`.95 unaryOperator(hasOperatorName("*"), hasUnaryOperand(ReceiverExpr)));96 const auto ReceiverType =97 hasCanonicalType(recordType(hasDeclaration(namedDecl(98 unless(matchers::matchesAnyListedName(ExcludedContainerTypes))))));99 100 return expr(101 anyOf(cxxMemberCallExpr(callee(MethodDecl), on(OnExpr),102 thisPointerType(ReceiverType)),103 cxxOperatorCallExpr(callee(MethodDecl), hasArgument(0, OnExpr),104 hasArgument(0, hasType(ReceiverType)))));105}106 107AST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); }108 109AST_MATCHER_FUNCTION(StatementMatcher, isConstRefReturningFunctionCall) {110 // Only allow initialization of a const reference from a free function or111 // static member function if it has no arguments. Otherwise it could return112 // an alias to one of its arguments and the arguments need to be checked113 // for const use as well.114 return callExpr(argumentCountIs(0),115 callee(functionDecl(returns(hasCanonicalType(116 matchers::isReferenceToConst())),117 unless(cxxMethodDecl(unless(isStatic()))))118 .bind(FunctionDeclId)))119 .bind(InitFunctionCallId);120}121 122AST_MATCHER_FUNCTION_P(StatementMatcher, initializerReturnsReferenceToConst,123 std::vector<StringRef>, ExcludedContainerTypes) {124 auto OldVarDeclRef =125 declRefExpr(to(varDecl(hasLocalStorage()).bind(OldVarDeclId)));126 return expr(127 anyOf(isConstRefReturningFunctionCall(),128 isRefReturningMethodCallWithConstOverloads(ExcludedContainerTypes),129 ignoringImpCasts(OldVarDeclRef),130 ignoringImpCasts(unaryOperator(hasOperatorName("&"),131 hasUnaryOperand(OldVarDeclRef)))));132}133 134} // namespace135 136// This checks that the variable itself is only used as const, and also makes137// sure that it does not reference another variable that could be modified in138// the BlockStmt. It does this by checking the following:139// 1. If the variable is neither a reference nor a pointer then the140// isOnlyUsedAsConst() check is sufficient.141// 2. If the (reference or pointer) variable is not initialized in a DeclStmt in142// the BlockStmt. In this case its pointee is likely not modified (unless it143// is passed as an alias into the method as well).144// 3. If the reference is initialized from a reference to const. This is145// the same set of criteria we apply when identifying the unnecessary copied146// variable in this check to begin with. In this case we check whether the147// object arg or variable that is referenced is immutable as well.148static bool isInitializingVariableImmutable(149 const VarDecl &InitializingVar, const Stmt &BlockStmt, ASTContext &Context,150 const std::vector<StringRef> &ExcludedContainerTypes) {151 const QualType T = InitializingVar.getType().getCanonicalType();152 if (!isOnlyUsedAsConst(InitializingVar, BlockStmt, Context,153 T->isPointerType() ? 1 : 0))154 return false;155 156 // The variable is a value type and we know it is only used as const. Safe157 // to reference it and avoid the copy.158 if (!isa<ReferenceType, PointerType>(T))159 return true;160 161 // The reference or pointer is not declared and hence not initialized anywhere162 // in the function. We assume its pointee is not modified then.163 if (!InitializingVar.isLocalVarDecl() || !InitializingVar.hasInit()) {164 return true;165 }166 167 auto Matches =168 match(initializerReturnsReferenceToConst(ExcludedContainerTypes),169 *InitializingVar.getInit(), Context);170 // The reference is initialized from a free function without arguments171 // returning a const reference. This is a global immutable object.172 if (selectFirst<CallExpr>(InitFunctionCallId, Matches) != nullptr)173 return true;174 // Check that the object argument is immutable as well.175 if (const auto *OrigVar = selectFirst<VarDecl>(ObjectArgId, Matches))176 return isInitializingVariableImmutable(*OrigVar, BlockStmt, Context,177 ExcludedContainerTypes);178 // Check that the old variable we reference is immutable as well.179 if (const auto *OrigVar = selectFirst<VarDecl>(OldVarDeclId, Matches))180 return isInitializingVariableImmutable(*OrigVar, BlockStmt, Context,181 ExcludedContainerTypes);182 183 return false;184}185 186static bool isVariableUnused(const VarDecl &Var, const Stmt &BlockStmt,187 ASTContext &Context) {188 return allDeclRefExprs(Var, BlockStmt, Context).empty();189}190 191static const SubstTemplateTypeParmType *192getSubstitutedType(const QualType &Type, ASTContext &Context) {193 auto Matches = match(194 qualType(anyOf(substTemplateTypeParmType().bind("subst"),195 hasDescendant(substTemplateTypeParmType().bind("subst")))),196 Type, Context);197 return selectFirst<SubstTemplateTypeParmType>("subst", Matches);198}199 200static bool differentReplacedTemplateParams(const QualType &VarType,201 const QualType &InitializerType,202 ASTContext &Context) {203 if (const SubstTemplateTypeParmType *VarTmplType =204 getSubstitutedType(VarType, Context)) {205 if (const SubstTemplateTypeParmType *InitializerTmplType =206 getSubstitutedType(InitializerType, Context)) {207 const TemplateTypeParmDecl *VarTTP = VarTmplType->getReplacedParameter();208 const TemplateTypeParmDecl *InitTTP =209 InitializerTmplType->getReplacedParameter();210 return (VarTTP->getDepth() != InitTTP->getDepth() ||211 VarTTP->getIndex() != InitTTP->getIndex() ||212 VarTTP->isParameterPack() != InitTTP->isParameterPack());213 }214 }215 return false;216}217 218static QualType constructorArgumentType(const VarDecl *OldVar,219 const BoundNodes &Nodes) {220 if (OldVar) {221 return OldVar->getType();222 }223 if (const auto *FuncDecl = Nodes.getNodeAs<FunctionDecl>(FunctionDeclId)) {224 return FuncDecl->getReturnType();225 }226 const auto *MethodDecl = Nodes.getNodeAs<CXXMethodDecl>(MethodDeclId);227 return MethodDecl->getReturnType();228}229 230UnnecessaryCopyInitializationCheck::UnnecessaryCopyInitializationCheck(231 StringRef Name, ClangTidyContext *Context)232 : ClangTidyCheck(Name, Context),233 AllowedTypes(234 utils::options::parseStringList(Options.get("AllowedTypes", ""))),235 ExcludedContainerTypes(utils::options::parseStringList(236 Options.get("ExcludedContainerTypes", ""))) {}237 238void UnnecessaryCopyInitializationCheck::registerMatchers(MatchFinder *Finder) {239 auto LocalVarCopiedFrom =240 [this](const ast_matchers::internal::Matcher<Expr> &CopyCtorArg) {241 return compoundStmt(242 forEachDescendant(243 declStmt(244 unless(has(decompositionDecl())),245 has(varDecl(246 hasLocalStorage(),247 hasType(qualType(248 hasCanonicalType(allOf(249 matchers::isExpensiveToCopy(),250 unless(hasDeclaration(namedDecl(251 hasName("::std::function")))))),252 unless(hasDeclaration(namedDecl(253 matchers::matchesAnyListedName(254 AllowedTypes)))))),255 unless(isImplicit()),256 hasInitializer(traverse(257 TK_AsIs,258 cxxConstructExpr(259 hasDeclaration(cxxConstructorDecl(260 isCopyConstructor())),261 hasArgument(0, CopyCtorArg))262 .bind("ctorCall"))))263 .bind("newVarDecl")))264 .bind("declStmt")))265 .bind("blockStmt");266 };267 268 Finder->addMatcher(269 LocalVarCopiedFrom(anyOf(270 isConstRefReturningFunctionCall(),271 isRefReturningMethodCallWithConstOverloads(ExcludedContainerTypes))),272 this);273 274 Finder->addMatcher(LocalVarCopiedFrom(declRefExpr(275 to(varDecl(hasLocalStorage()).bind(OldVarDeclId)))),276 this);277}278 279void UnnecessaryCopyInitializationCheck::check(280 const MatchFinder::MatchResult &Result) {281 const auto &NewVar = *Result.Nodes.getNodeAs<VarDecl>("newVarDecl");282 const auto &BlockStmt = *Result.Nodes.getNodeAs<Stmt>("blockStmt");283 const auto &VarDeclStmt = *Result.Nodes.getNodeAs<DeclStmt>("declStmt");284 // Do not propose fixes if the DeclStmt has multiple VarDecls or in285 // macros since we cannot place them correctly.286 const bool IssueFix =287 VarDeclStmt.isSingleDecl() && !NewVar.getLocation().isMacroID();288 const bool IsVarUnused = isVariableUnused(NewVar, BlockStmt, *Result.Context);289 const bool IsVarOnlyUsedAsConst =290 isOnlyUsedAsConst(NewVar, BlockStmt, *Result.Context,291 // `NewVar` is always of non-pointer type.292 0);293 const CheckContext Context{294 NewVar, BlockStmt, VarDeclStmt, *Result.Context,295 IssueFix, IsVarUnused, IsVarOnlyUsedAsConst};296 const auto *OldVar = Result.Nodes.getNodeAs<VarDecl>(OldVarDeclId);297 const auto *ObjectArg = Result.Nodes.getNodeAs<VarDecl>(ObjectArgId);298 const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctorCall");299 300 const TraversalKindScope RAII(*Result.Context, TK_AsIs);301 302 // A constructor that looks like T(const T& t, bool arg = false) counts as a303 // copy only when it is called with default arguments for the arguments after304 // the first.305 for (unsigned int I = 1; I < CtorCall->getNumArgs(); ++I)306 if (!CtorCall->getArg(I)->isDefaultArgument())307 return;308 309 // Don't apply the check if the variable and its initializer have different310 // replaced template parameter types. In this case the check triggers for a311 // template instantiation where the substituted types are the same, but312 // instantiations where the types differ and rely on implicit conversion would313 // no longer compile if we switched to a reference.314 if (differentReplacedTemplateParams(315 Context.Var.getType(), constructorArgumentType(OldVar, Result.Nodes),316 *Result.Context))317 return;318 319 if (OldVar == nullptr) {320 // `auto NewVar = functionCall();`321 handleCopyFromMethodReturn(Context, ObjectArg);322 } else {323 // `auto NewVar = OldVar;`324 handleCopyFromLocalVar(Context, *OldVar);325 }326}327 328void UnnecessaryCopyInitializationCheck::handleCopyFromMethodReturn(329 const CheckContext &Ctx, const VarDecl *ObjectArg) {330 const bool IsConstQualified = Ctx.Var.getType().isConstQualified();331 if (!IsConstQualified && !Ctx.IsVarOnlyUsedAsConst)332 return;333 if (ObjectArg != nullptr &&334 !isInitializingVariableImmutable(*ObjectArg, Ctx.BlockStmt, Ctx.ASTCtx,335 ExcludedContainerTypes))336 return;337 diagnoseCopyFromMethodReturn(Ctx);338}339 340void UnnecessaryCopyInitializationCheck::handleCopyFromLocalVar(341 const CheckContext &Ctx, const VarDecl &OldVar) {342 if (!Ctx.IsVarOnlyUsedAsConst ||343 !isInitializingVariableImmutable(OldVar, Ctx.BlockStmt, Ctx.ASTCtx,344 ExcludedContainerTypes))345 return;346 diagnoseCopyFromLocalVar(Ctx, OldVar);347}348 349void UnnecessaryCopyInitializationCheck::diagnoseCopyFromMethodReturn(350 const CheckContext &Ctx) {351 auto Diagnostic =352 diag(Ctx.Var.getLocation(),353 "the %select{|const qualified }0variable %1 of type %2 is "354 "copy-constructed "355 "from a const reference%select{%select{ but is only used as const "356 "reference|}0| but is never used}3; consider "357 "%select{making it a const reference|removing the statement}3")358 << Ctx.Var.getType().isConstQualified() << &Ctx.Var << Ctx.Var.getType()359 << Ctx.IsVarUnused;360 maybeIssueFixes(Ctx, Diagnostic);361}362 363void UnnecessaryCopyInitializationCheck::diagnoseCopyFromLocalVar(364 const CheckContext &Ctx, const VarDecl &OldVar) {365 auto Diagnostic =366 diag(Ctx.Var.getLocation(),367 "local copy %0 of the variable %1 of type %2 is never "368 "modified%select{"369 "| and never used}3; consider %select{avoiding the copy|removing "370 "the statement}3")371 << &Ctx.Var << &OldVar << Ctx.Var.getType() << Ctx.IsVarUnused;372 maybeIssueFixes(Ctx, Diagnostic);373}374 375void UnnecessaryCopyInitializationCheck::maybeIssueFixes(376 const CheckContext &Ctx, DiagnosticBuilder &Diagnostic) {377 if (Ctx.IssueFix) {378 if (Ctx.IsVarUnused)379 recordRemoval(Ctx.VarDeclStmt, Ctx.ASTCtx, Diagnostic);380 else381 recordFixes(Ctx.Var, Ctx.ASTCtx, Diagnostic);382 }383}384 385void UnnecessaryCopyInitializationCheck::storeOptions(386 ClangTidyOptions::OptionMap &Opts) {387 Options.store(Opts, "AllowedTypes",388 utils::options::serializeStringList(AllowedTypes));389 Options.store(Opts, "ExcludedContainerTypes",390 utils::options::serializeStringList(ExcludedContainerTypes));391}392 393} // namespace clang::tidy::performance394