1 //===--- MakeSmartPtrCheck.cpp - clang-tidy--------------------------------===// 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-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "MakeSharedCheck.h" 10 #include "clang/Frontend/CompilerInstance.h" 11 #include "clang/Lex/Lexer.h" 12 #include "clang/Lex/Preprocessor.h" 13 14 using namespace clang::ast_matchers; 15 16 namespace clang { 17 namespace tidy { 18 namespace modernize { 19 20 namespace { 21 22 constexpr char StdMemoryHeader[] = "memory"; 23 constexpr char ConstructorCall[] = "constructorCall"; 24 constexpr char ResetCall[] = "resetCall"; 25 constexpr char NewExpression[] = "newExpression"; 26 27 std::string GetNewExprName(const CXXNewExpr *NewExpr, 28 const SourceManager &SM, 29 const LangOptions &Lang) { 30 StringRef WrittenName = Lexer::getSourceText( 31 CharSourceRange::getTokenRange( 32 NewExpr->getAllocatedTypeSourceInfo()->getTypeLoc().getSourceRange()), 33 SM, Lang); 34 if (NewExpr->isArray()) { 35 return (WrittenName + "[]").str(); 36 } 37 return WrittenName.str(); 38 } 39 40 } // namespace 41 42 const char MakeSmartPtrCheck::PointerType[] = "pointerType"; 43 44 MakeSmartPtrCheck::MakeSmartPtrCheck(StringRef Name, ClangTidyContext *Context, 45 StringRef MakeSmartPtrFunctionName) 46 : ClangTidyCheck(Name, Context), 47 IncludeStyle(Options.getLocalOrGlobal("IncludeStyle", 48 utils::IncludeSorter::getMapping(), 49 utils::IncludeSorter::IS_LLVM)), 50 MakeSmartPtrFunctionHeader( 51 Options.get("MakeSmartPtrFunctionHeader", StdMemoryHeader)), 52 MakeSmartPtrFunctionName( 53 Options.get("MakeSmartPtrFunction", MakeSmartPtrFunctionName)), 54 IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)) {} 55 56 void MakeSmartPtrCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { 57 Options.store(Opts, "IncludeStyle", IncludeStyle, 58 utils::IncludeSorter::getMapping()); 59 Options.store(Opts, "MakeSmartPtrFunctionHeader", MakeSmartPtrFunctionHeader); 60 Options.store(Opts, "MakeSmartPtrFunction", MakeSmartPtrFunctionName); 61 Options.store(Opts, "IgnoreMacros", IgnoreMacros); 62 } 63 64 bool MakeSmartPtrCheck::isLanguageVersionSupported( 65 const LangOptions &LangOpts) const { 66 return LangOpts.CPlusPlus11; 67 } 68 69 void MakeSmartPtrCheck::registerPPCallbacks(const SourceManager &SM, 70 Preprocessor *PP, 71 Preprocessor *ModuleExpanderPP) { 72 Inserter = std::make_unique<utils::IncludeInserter>(SM, getLangOpts(), 73 IncludeStyle); 74 PP->addPPCallbacks(Inserter->CreatePPCallbacks()); 75 } 76 77 void MakeSmartPtrCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { 78 // Calling make_smart_ptr from within a member function of a type with a 79 // private or protected constructor would be ill-formed. 80 auto CanCallCtor = unless(has(ignoringImpCasts( 81 cxxConstructExpr(hasDeclaration(decl(unless(isPublic()))))))); 82 83 auto IsPlacement = hasAnyPlacementArg(anything()); 84 85 Finder->addMatcher( 86 cxxBindTemporaryExpr(has(ignoringParenImpCasts( 87 cxxConstructExpr( 88 hasType(getSmartPointerTypeMatcher()), argumentCountIs(1), 89 hasArgument(0, 90 cxxNewExpr(hasType(pointsTo(qualType(hasCanonicalType( 91 equalsBoundNode(PointerType))))), 92 CanCallCtor, unless(IsPlacement)) 93 .bind(NewExpression)), 94 unless(isInTemplateInstantiation())) 95 .bind(ConstructorCall)))), 96 this); 97 98 Finder->addMatcher( 99 cxxMemberCallExpr( 100 thisPointerType(getSmartPointerTypeMatcher()), 101 callee(cxxMethodDecl(hasName("reset"))), 102 hasArgument( 103 0, 104 cxxNewExpr(CanCallCtor, unless(IsPlacement)).bind(NewExpression)), 105 unless(isInTemplateInstantiation())) 106 .bind(ResetCall), 107 this); 108 } 109 110 void MakeSmartPtrCheck::check(const MatchFinder::MatchResult &Result) { 111 // 'smart_ptr' refers to 'std::shared_ptr' or 'std::unique_ptr' or other 112 // pointer, 'make_smart_ptr' refers to 'std::make_shared' or 113 // 'std::make_unique' or other function that creates smart_ptr. 114 115 SourceManager &SM = *Result.SourceManager; 116 const auto *Construct = 117 Result.Nodes.getNodeAs<CXXConstructExpr>(ConstructorCall); 118 const auto *Reset = Result.Nodes.getNodeAs<CXXMemberCallExpr>(ResetCall); 119 const auto *Type = Result.Nodes.getNodeAs<QualType>(PointerType); 120 const auto *New = Result.Nodes.getNodeAs<CXXNewExpr>(NewExpression); 121 122 // Skip when this is a new-expression with `auto`, e.g. new auto(1) 123 if (New->getType()->getPointeeType()->getContainedAutoType()) 124 return; 125 126 // Be conservative for cases where we construct an array without any 127 // initialization. 128 // For example, 129 // P.reset(new int[5]) // check fix: P = std::make_unique<int []>(5) 130 // 131 // The fix of the check has side effect, it introduces default initialization 132 // which maybe unexpected and cause performance regression. 133 if (New->isArray() && !New->hasInitializer()) 134 return; 135 if (Construct) 136 checkConstruct(SM, Result.Context, Construct, Type, New); 137 else if (Reset) 138 checkReset(SM, Result.Context, Reset, New); 139 } 140 141 void MakeSmartPtrCheck::checkConstruct(SourceManager &SM, ASTContext *Ctx, 142 const CXXConstructExpr *Construct, 143 const QualType *Type, 144 const CXXNewExpr *New) { 145 SourceLocation ConstructCallStart = Construct->getExprLoc(); 146 bool InMacro = ConstructCallStart.isMacroID(); 147 148 if (InMacro && IgnoreMacros) { 149 return; 150 } 151 152 bool Invalid = false; 153 StringRef ExprStr = Lexer::getSourceText( 154 CharSourceRange::getCharRange( 155 ConstructCallStart, Construct->getParenOrBraceRange().getBegin()), 156 SM, getLangOpts(), &Invalid); 157 if (Invalid) 158 return; 159 160 auto Diag = diag(ConstructCallStart, "use %0 instead") 161 << MakeSmartPtrFunctionName; 162 163 // Disable the fix in macros. 164 if (InMacro) { 165 return; 166 } 167 168 if (!replaceNew(Diag, New, SM, Ctx)) { 169 return; 170 } 171 172 // Find the location of the template's left angle. 173 size_t LAngle = ExprStr.find("<"); 174 SourceLocation ConstructCallEnd; 175 if (LAngle == StringRef::npos) { 176 // If the template argument is missing (because it is part of the alias) 177 // we have to add it back. 178 ConstructCallEnd = ConstructCallStart.getLocWithOffset(ExprStr.size()); 179 Diag << FixItHint::CreateInsertion( 180 ConstructCallEnd, 181 "<" + GetNewExprName(New, SM, getLangOpts()) + ">"); 182 } else { 183 ConstructCallEnd = ConstructCallStart.getLocWithOffset(LAngle); 184 } 185 186 Diag << FixItHint::CreateReplacement( 187 CharSourceRange::getCharRange(ConstructCallStart, ConstructCallEnd), 188 MakeSmartPtrFunctionName); 189 190 // If the smart_ptr is built with brace enclosed direct initialization, use 191 // parenthesis instead. 192 if (Construct->isListInitialization()) { 193 SourceRange BraceRange = Construct->getParenOrBraceRange(); 194 Diag << FixItHint::CreateReplacement( 195 CharSourceRange::getCharRange( 196 BraceRange.getBegin(), BraceRange.getBegin().getLocWithOffset(1)), 197 "("); 198 Diag << FixItHint::CreateReplacement( 199 CharSourceRange::getCharRange(BraceRange.getEnd(), 200 BraceRange.getEnd().getLocWithOffset(1)), 201 ")"); 202 } 203 204 insertHeader(Diag, SM.getFileID(ConstructCallStart)); 205 } 206 207 void MakeSmartPtrCheck::checkReset(SourceManager &SM, ASTContext *Ctx, 208 const CXXMemberCallExpr *Reset, 209 const CXXNewExpr *New) { 210 const auto *Expr = cast<MemberExpr>(Reset->getCallee()); 211 SourceLocation OperatorLoc = Expr->getOperatorLoc(); 212 SourceLocation ResetCallStart = Reset->getExprLoc(); 213 SourceLocation ExprStart = Expr->getBeginLoc(); 214 SourceLocation ExprEnd = 215 Lexer::getLocForEndOfToken(Expr->getEndLoc(), 0, SM, getLangOpts()); 216 217 bool InMacro = ExprStart.isMacroID(); 218 219 if (InMacro && IgnoreMacros) { 220 return; 221 } 222 223 // There are some cases where we don't have operator ("." or "->") of the 224 // "reset" expression, e.g. call "reset()" method directly in the subclass of 225 // "std::unique_ptr<>". We skip these cases. 226 if (OperatorLoc.isInvalid()) { 227 return; 228 } 229 230 auto Diag = diag(ResetCallStart, "use %0 instead") 231 << MakeSmartPtrFunctionName; 232 233 // Disable the fix in macros. 234 if (InMacro) { 235 return; 236 } 237 238 if (!replaceNew(Diag, New, SM, Ctx)) { 239 return; 240 } 241 242 Diag << FixItHint::CreateReplacement( 243 CharSourceRange::getCharRange(OperatorLoc, ExprEnd), 244 (llvm::Twine(" = ") + MakeSmartPtrFunctionName + "<" + 245 GetNewExprName(New, SM, getLangOpts()) + ">") 246 .str()); 247 248 if (Expr->isArrow()) 249 Diag << FixItHint::CreateInsertion(ExprStart, "*"); 250 251 insertHeader(Diag, SM.getFileID(OperatorLoc)); 252 } 253 254 bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag, 255 const CXXNewExpr *New, SourceManager &SM, 256 ASTContext *Ctx) { 257 auto SkipParensParents = [&](const Expr *E) { 258 for (const Expr *OldE = nullptr; E != OldE;) { 259 OldE = E; 260 for (const auto &Node : Ctx->getParents(*E)) { 261 if (const Expr *Parent = Node.get<ParenExpr>()) { 262 E = Parent; 263 break; 264 } 265 } 266 } 267 return E; 268 }; 269 270 SourceRange NewRange = SkipParensParents(New)->getSourceRange(); 271 SourceLocation NewStart = NewRange.getBegin(); 272 SourceLocation NewEnd = NewRange.getEnd(); 273 274 // Skip when the source location of the new expression is invalid. 275 if (NewStart.isInvalid() || NewEnd.isInvalid()) 276 return false; 277 278 std::string ArraySizeExpr; 279 if (const auto* ArraySize = New->getArraySize().getValueOr(nullptr)) { 280 ArraySizeExpr = Lexer::getSourceText(CharSourceRange::getTokenRange( 281 ArraySize->getSourceRange()), 282 SM, getLangOpts()) 283 .str(); 284 } 285 // Returns true if the given constructor expression has any braced-init-list 286 // argument, e.g. 287 // Foo({1, 2}, 1) => true 288 // Foo(Bar{1, 2}) => true 289 // Foo(1) => false 290 // Foo{1} => false 291 auto HasListIntializedArgument = [](const CXXConstructExpr *CE) { 292 for (const auto *Arg : CE->arguments()) { 293 Arg = Arg->IgnoreImplicit(); 294 295 if (isa<CXXStdInitializerListExpr>(Arg) || isa<InitListExpr>(Arg)) 296 return true; 297 // Check whether we implicitly construct a class from a 298 // std::initializer_list. 299 if (const auto *CEArg = dyn_cast<CXXConstructExpr>(Arg)) { 300 // Strip the elidable move constructor, it is present in the AST for 301 // C++11/14, e.g. Foo(Bar{1, 2}), the move constructor is around the 302 // init-list constructor. 303 if (CEArg->isElidable()) { 304 if (const auto *TempExp = CEArg->getArg(0)) { 305 if (const auto *UnwrappedCE = 306 dyn_cast<CXXConstructExpr>(TempExp->IgnoreImplicit())) 307 CEArg = UnwrappedCE; 308 } 309 } 310 if (CEArg->isStdInitListInitialization()) 311 return true; 312 } 313 } 314 return false; 315 }; 316 switch (New->getInitializationStyle()) { 317 case CXXNewExpr::NoInit: { 318 if (ArraySizeExpr.empty()) { 319 Diag << FixItHint::CreateRemoval(SourceRange(NewStart, NewEnd)); 320 } else { 321 // New array expression without written initializer: 322 // smart_ptr<Foo[]>(new Foo[5]); 323 Diag << FixItHint::CreateReplacement(SourceRange(NewStart, NewEnd), 324 ArraySizeExpr); 325 } 326 break; 327 } 328 case CXXNewExpr::CallInit: { 329 // FIXME: Add fixes for constructors with parameters that can be created 330 // with a C++11 braced-init-list (e.g. std::vector, std::map). 331 // Unlike ordinal cases, braced list can not be deduced in 332 // std::make_smart_ptr, we need to specify the type explicitly in the fixes: 333 // struct S { S(std::initializer_list<int>, int); }; 334 // struct S2 { S2(std::vector<int>); }; 335 // struct S3 { S3(S2, int); }; 336 // smart_ptr<S>(new S({1, 2, 3}, 1)); // C++98 call-style initialization 337 // smart_ptr<S>(new S({}, 1)); 338 // smart_ptr<S2>(new S2({1})); // implicit conversion: 339 // // std::initializer_list => std::vector 340 // smart_ptr<S3>(new S3({1, 2}, 3)); 341 // The above samples have to be replaced with: 342 // std::make_smart_ptr<S>(std::initializer_list<int>({1, 2, 3}), 1); 343 // std::make_smart_ptr<S>(std::initializer_list<int>({}), 1); 344 // std::make_smart_ptr<S2>(std::vector<int>({1})); 345 // std::make_smart_ptr<S3>(S2{1, 2}, 3); 346 if (const auto *CE = New->getConstructExpr()) { 347 if (HasListIntializedArgument(CE)) 348 return false; 349 } 350 if (ArraySizeExpr.empty()) { 351 SourceRange InitRange = New->getDirectInitRange(); 352 Diag << FixItHint::CreateRemoval( 353 SourceRange(NewStart, InitRange.getBegin())); 354 Diag << FixItHint::CreateRemoval(SourceRange(InitRange.getEnd(), NewEnd)); 355 } 356 else { 357 // New array expression with default/value initialization: 358 // smart_ptr<Foo[]>(new int[5]()); 359 // smart_ptr<Foo[]>(new Foo[5]()); 360 Diag << FixItHint::CreateReplacement(SourceRange(NewStart, NewEnd), 361 ArraySizeExpr); 362 } 363 break; 364 } 365 case CXXNewExpr::ListInit: { 366 // Range of the substring that we do not want to remove. 367 SourceRange InitRange; 368 if (const auto *NewConstruct = New->getConstructExpr()) { 369 if (NewConstruct->isStdInitListInitialization() || 370 HasListIntializedArgument(NewConstruct)) { 371 // FIXME: Add fixes for direct initialization with the initializer-list 372 // constructor. Similar to the above CallInit case, the type has to be 373 // specified explicitly in the fixes. 374 // struct S { S(std::initializer_list<int>); }; 375 // struct S2 { S2(S, int); }; 376 // smart_ptr<S>(new S{1, 2, 3}); // C++11 direct list-initialization 377 // smart_ptr<S>(new S{}); // use initializer-list constructor 378 // smart_ptr<S2>()new S2{ {1,2}, 3 }; // have a list-initialized arg 379 // The above cases have to be replaced with: 380 // std::make_smart_ptr<S>(std::initializer_list<int>({1, 2, 3})); 381 // std::make_smart_ptr<S>(std::initializer_list<int>({})); 382 // std::make_smart_ptr<S2>(S{1, 2}, 3); 383 return false; 384 } else { 385 // Direct initialization with ordinary constructors. 386 // struct S { S(int x); S(); }; 387 // smart_ptr<S>(new S{5}); 388 // smart_ptr<S>(new S{}); // use default constructor 389 // The arguments in the initialization list are going to be forwarded to 390 // the constructor, so this has to be replaced with: 391 // std::make_smart_ptr<S>(5); 392 // std::make_smart_ptr<S>(); 393 InitRange = SourceRange( 394 NewConstruct->getParenOrBraceRange().getBegin().getLocWithOffset(1), 395 NewConstruct->getParenOrBraceRange().getEnd().getLocWithOffset(-1)); 396 } 397 } else { 398 // Aggregate initialization. 399 // smart_ptr<Pair>(new Pair{first, second}); 400 // Has to be replaced with: 401 // smart_ptr<Pair>(Pair{first, second}); 402 // 403 // The fix (std::make_unique) needs to see copy/move constructor of 404 // Pair. If we found any invisible or deleted copy/move constructor, we 405 // stop generating fixes -- as the C++ rule is complicated and we are less 406 // certain about the correct fixes. 407 if (const CXXRecordDecl *RD = New->getType()->getPointeeCXXRecordDecl()) { 408 if (llvm::find_if(RD->ctors(), [](const CXXConstructorDecl *Ctor) { 409 return Ctor->isCopyOrMoveConstructor() && 410 (Ctor->isDeleted() || Ctor->getAccess() == AS_private); 411 }) != RD->ctor_end()) { 412 return false; 413 } 414 } 415 InitRange = SourceRange( 416 New->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(), 417 New->getInitializer()->getSourceRange().getEnd()); 418 } 419 Diag << FixItHint::CreateRemoval( 420 CharSourceRange::getCharRange(NewStart, InitRange.getBegin())); 421 Diag << FixItHint::CreateRemoval( 422 SourceRange(InitRange.getEnd().getLocWithOffset(1), NewEnd)); 423 break; 424 } 425 } 426 return true; 427 } 428 429 void MakeSmartPtrCheck::insertHeader(DiagnosticBuilder &Diag, FileID FD) { 430 if (MakeSmartPtrFunctionHeader.empty()) { 431 return; 432 } 433 Diag << Inserter->CreateIncludeInsertion( 434 FD, MakeSmartPtrFunctionHeader, 435 /*IsAngled=*/MakeSmartPtrFunctionHeader == StdMemoryHeader); 436 } 437 438 } // namespace modernize 439 } // namespace tidy 440 } // namespace clang 441