1 //===--- LoopConvertCheck.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 "LoopConvertCheck.h" 10 #include "clang/AST/ASTContext.h" 11 #include "clang/ASTMatchers/ASTMatchFinder.h" 12 #include "clang/Basic/LLVM.h" 13 #include "clang/Basic/LangOptions.h" 14 #include "clang/Basic/SourceLocation.h" 15 #include "clang/Basic/SourceManager.h" 16 #include "clang/Lex/Lexer.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/StringSwitch.h" 21 #include "llvm/Support/Casting.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include <cassert> 24 #include <cstring> 25 #include <utility> 26 27 using namespace clang::ast_matchers; 28 using namespace llvm; 29 30 namespace clang { 31 namespace tidy { 32 33 template <> struct OptionEnumMapping<modernize::Confidence::Level> { 34 static llvm::ArrayRef<std::pair<modernize::Confidence::Level, StringRef>> 35 getEnumMapping() { 36 static constexpr std::pair<modernize::Confidence::Level, StringRef> 37 Mapping[] = {{modernize::Confidence::CL_Reasonable, "reasonable"}, 38 {modernize::Confidence::CL_Safe, "safe"}, 39 {modernize::Confidence::CL_Risky, "risky"}}; 40 return makeArrayRef(Mapping); 41 } 42 }; 43 44 template <> struct OptionEnumMapping<modernize::VariableNamer::NamingStyle> { 45 static llvm::ArrayRef< 46 std::pair<modernize::VariableNamer::NamingStyle, StringRef>> 47 getEnumMapping() { 48 static constexpr std::pair<modernize::VariableNamer::NamingStyle, StringRef> 49 Mapping[] = {{modernize::VariableNamer::NS_CamelCase, "CamelCase"}, 50 {modernize::VariableNamer::NS_CamelBack, "camelBack"}, 51 {modernize::VariableNamer::NS_LowerCase, "lower_case"}, 52 {modernize::VariableNamer::NS_UpperCase, "UPPER_CASE"}}; 53 return makeArrayRef(Mapping); 54 } 55 }; 56 57 namespace modernize { 58 59 static const char LoopNameArray[] = "forLoopArray"; 60 static const char LoopNameIterator[] = "forLoopIterator"; 61 static const char LoopNameReverseIterator[] = "forLoopReverseIterator"; 62 static const char LoopNamePseudoArray[] = "forLoopPseudoArray"; 63 static const char ConditionBoundName[] = "conditionBound"; 64 static const char ConditionVarName[] = "conditionVar"; 65 static const char IncrementVarName[] = "incrementVar"; 66 static const char InitVarName[] = "initVar"; 67 static const char BeginCallName[] = "beginCall"; 68 static const char EndCallName[] = "endCall"; 69 static const char ConditionEndVarName[] = "conditionEndVar"; 70 static const char EndVarName[] = "endVar"; 71 static const char DerefByValueResultName[] = "derefByValueResult"; 72 static const char DerefByRefResultName[] = "derefByRefResult"; 73 // shared matchers 74 static const TypeMatcher anyType() { return anything(); } 75 76 static const StatementMatcher integerComparisonMatcher() { 77 return expr(ignoringParenImpCasts( 78 declRefExpr(to(varDecl(hasType(isInteger())).bind(ConditionVarName))))); 79 } 80 81 static const DeclarationMatcher initToZeroMatcher() { 82 return varDecl( 83 hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0))))) 84 .bind(InitVarName); 85 } 86 87 static const StatementMatcher incrementVarMatcher() { 88 return declRefExpr(to(varDecl(hasType(isInteger())).bind(IncrementVarName))); 89 } 90 91 /// The matcher for loops over arrays. 92 /// 93 /// In this general example, assuming 'j' and 'k' are of integral type: 94 /// \code 95 /// for (int i = 0; j < 3 + 2; ++k) { ... } 96 /// \endcode 97 /// The following string identifiers are bound to these parts of the AST: 98 /// ConditionVarName: 'j' (as a VarDecl) 99 /// ConditionBoundName: '3 + 2' (as an Expr) 100 /// InitVarName: 'i' (as a VarDecl) 101 /// IncrementVarName: 'k' (as a VarDecl) 102 /// LoopName: The entire for loop (as a ForStmt) 103 /// 104 /// Client code will need to make sure that: 105 /// - The three index variables identified by the matcher are the same 106 /// VarDecl. 107 /// - The index variable is only used as an array index. 108 /// - All arrays indexed by the loop are the same. 109 StatementMatcher makeArrayLoopMatcher() { 110 StatementMatcher ArrayBoundMatcher = 111 expr(hasType(isInteger())).bind(ConditionBoundName); 112 113 return forStmt( 114 unless(isInTemplateInstantiation()), 115 hasLoopInit(declStmt(hasSingleDecl(initToZeroMatcher()))), 116 hasCondition(anyOf( 117 binaryOperator(hasOperatorName("<"), 118 hasLHS(integerComparisonMatcher()), 119 hasRHS(ArrayBoundMatcher)), 120 binaryOperator(hasOperatorName(">"), hasLHS(ArrayBoundMatcher), 121 hasRHS(integerComparisonMatcher())))), 122 hasIncrement( 123 unaryOperator(hasOperatorName("++"), 124 hasUnaryOperand(incrementVarMatcher())))) 125 .bind(LoopNameArray); 126 } 127 128 /// The matcher used for iterator-based for loops. 129 /// 130 /// This matcher is more flexible than array-based loops. It will match 131 /// catch loops of the following textual forms (regardless of whether the 132 /// iterator type is actually a pointer type or a class type): 133 /// 134 /// Assuming f, g, and h are of type containerType::iterator, 135 /// \code 136 /// for (containerType::iterator it = container.begin(), 137 /// e = createIterator(); f != g; ++h) { ... } 138 /// for (containerType::iterator it = container.begin(); 139 /// f != anotherContainer.end(); ++h) { ... } 140 /// \endcode 141 /// The following string identifiers are bound to the parts of the AST: 142 /// InitVarName: 'it' (as a VarDecl) 143 /// ConditionVarName: 'f' (as a VarDecl) 144 /// LoopName: The entire for loop (as a ForStmt) 145 /// In the first example only: 146 /// EndVarName: 'e' (as a VarDecl) 147 /// ConditionEndVarName: 'g' (as a VarDecl) 148 /// In the second example only: 149 /// EndCallName: 'container.end()' (as a CXXMemberCallExpr) 150 /// 151 /// Client code will need to make sure that: 152 /// - The iterator variables 'it', 'f', and 'h' are the same. 153 /// - The two containers on which 'begin' and 'end' are called are the same. 154 /// - If the end iterator variable 'g' is defined, it is the same as 'f'. 155 StatementMatcher makeIteratorLoopMatcher(bool IsReverse) { 156 157 auto BeginNameMatcher = IsReverse ? hasAnyName("rbegin", "crbegin") 158 : hasAnyName("begin", "cbegin"); 159 160 auto EndNameMatcher = 161 IsReverse ? hasAnyName("rend", "crend") : hasAnyName("end", "cend"); 162 163 StatementMatcher BeginCallMatcher = 164 cxxMemberCallExpr(argumentCountIs(0), 165 callee(cxxMethodDecl(BeginNameMatcher))) 166 .bind(BeginCallName); 167 168 DeclarationMatcher InitDeclMatcher = 169 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher), 170 materializeTemporaryExpr( 171 ignoringParenImpCasts(BeginCallMatcher)), 172 hasDescendant(BeginCallMatcher)))) 173 .bind(InitVarName); 174 175 DeclarationMatcher EndDeclMatcher = 176 varDecl(hasInitializer(anything())).bind(EndVarName); 177 178 StatementMatcher EndCallMatcher = cxxMemberCallExpr( 179 argumentCountIs(0), callee(cxxMethodDecl(EndNameMatcher))); 180 181 StatementMatcher IteratorBoundMatcher = 182 expr(anyOf(ignoringParenImpCasts( 183 declRefExpr(to(varDecl().bind(ConditionEndVarName)))), 184 ignoringParenImpCasts(expr(EndCallMatcher).bind(EndCallName)), 185 materializeTemporaryExpr(ignoringParenImpCasts( 186 expr(EndCallMatcher).bind(EndCallName))))); 187 188 StatementMatcher IteratorComparisonMatcher = expr( 189 ignoringParenImpCasts(declRefExpr(to(varDecl().bind(ConditionVarName))))); 190 191 auto OverloadedNEQMatcher = ignoringImplicit( 192 cxxOperatorCallExpr(hasOverloadedOperatorName("!="), argumentCountIs(2), 193 hasArgument(0, IteratorComparisonMatcher), 194 hasArgument(1, IteratorBoundMatcher))); 195 196 // This matcher tests that a declaration is a CXXRecordDecl that has an 197 // overloaded operator*(). If the operator*() returns by value instead of by 198 // reference then the return type is tagged with DerefByValueResultName. 199 internal::Matcher<VarDecl> TestDerefReturnsByValue = 200 hasType(hasUnqualifiedDesugaredType( 201 recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl( 202 hasOverloadedOperatorName("*"), 203 anyOf( 204 // Tag the return type if it's by value. 205 returns(qualType(unless(hasCanonicalType(referenceType()))) 206 .bind(DerefByValueResultName)), 207 returns( 208 // Skip loops where the iterator's operator* returns an 209 // rvalue reference. This is just weird. 210 qualType(unless(hasCanonicalType(rValueReferenceType()))) 211 .bind(DerefByRefResultName)))))))))); 212 213 return forStmt( 214 unless(isInTemplateInstantiation()), 215 hasLoopInit(anyOf(declStmt(declCountIs(2), 216 containsDeclaration(0, InitDeclMatcher), 217 containsDeclaration(1, EndDeclMatcher)), 218 declStmt(hasSingleDecl(InitDeclMatcher)))), 219 hasCondition( 220 anyOf(binaryOperator(hasOperatorName("!="), 221 hasLHS(IteratorComparisonMatcher), 222 hasRHS(IteratorBoundMatcher)), 223 binaryOperator(hasOperatorName("!="), 224 hasLHS(IteratorBoundMatcher), 225 hasRHS(IteratorComparisonMatcher)), 226 OverloadedNEQMatcher)), 227 hasIncrement(anyOf( 228 unaryOperator(hasOperatorName("++"), 229 hasUnaryOperand(declRefExpr( 230 to(varDecl(hasType(pointsTo(anyType()))) 231 .bind(IncrementVarName))))), 232 cxxOperatorCallExpr( 233 hasOverloadedOperatorName("++"), 234 hasArgument( 235 0, declRefExpr(to(varDecl(TestDerefReturnsByValue) 236 .bind(IncrementVarName)))))))) 237 .bind(IsReverse ? LoopNameReverseIterator : LoopNameIterator); 238 } 239 240 /// The matcher used for array-like containers (pseudoarrays). 241 /// 242 /// This matcher is more flexible than array-based loops. It will match 243 /// loops of the following textual forms (regardless of whether the 244 /// iterator type is actually a pointer type or a class type): 245 /// 246 /// Assuming f, g, and h are of type containerType::iterator, 247 /// \code 248 /// for (int i = 0, j = container.size(); f < g; ++h) { ... } 249 /// for (int i = 0; f < container.size(); ++h) { ... } 250 /// \endcode 251 /// The following string identifiers are bound to the parts of the AST: 252 /// InitVarName: 'i' (as a VarDecl) 253 /// ConditionVarName: 'f' (as a VarDecl) 254 /// LoopName: The entire for loop (as a ForStmt) 255 /// In the first example only: 256 /// EndVarName: 'j' (as a VarDecl) 257 /// ConditionEndVarName: 'g' (as a VarDecl) 258 /// In the second example only: 259 /// EndCallName: 'container.size()' (as a CXXMemberCallExpr) 260 /// 261 /// Client code will need to make sure that: 262 /// - The index variables 'i', 'f', and 'h' are the same. 263 /// - The containers on which 'size()' is called is the container indexed. 264 /// - The index variable is only used in overloaded operator[] or 265 /// container.at(). 266 /// - If the end iterator variable 'g' is defined, it is the same as 'j'. 267 /// - The container's iterators would not be invalidated during the loop. 268 StatementMatcher makePseudoArrayLoopMatcher() { 269 // Test that the incoming type has a record declaration that has methods 270 // called 'begin' and 'end'. If the incoming type is const, then make sure 271 // these methods are also marked const. 272 // 273 // FIXME: To be completely thorough this matcher should also ensure the 274 // return type of begin/end is an iterator that dereferences to the same as 275 // what operator[] or at() returns. Such a test isn't likely to fail except 276 // for pathological cases. 277 // 278 // FIXME: Also, a record doesn't necessarily need begin() and end(). Free 279 // functions called begin() and end() taking the container as an argument 280 // are also allowed. 281 TypeMatcher RecordWithBeginEnd = qualType(anyOf( 282 qualType( 283 isConstQualified(), 284 hasUnqualifiedDesugaredType(recordType(hasDeclaration(cxxRecordDecl( 285 hasMethod(cxxMethodDecl(hasName("begin"), isConst())), 286 hasMethod(cxxMethodDecl(hasName("end"), 287 isConst())))) // hasDeclaration 288 ))), // qualType 289 qualType(unless(isConstQualified()), 290 hasUnqualifiedDesugaredType(recordType(hasDeclaration( 291 cxxRecordDecl(hasMethod(hasName("begin")), 292 hasMethod(hasName("end"))))))) // qualType 293 )); 294 295 StatementMatcher SizeCallMatcher = cxxMemberCallExpr( 296 argumentCountIs(0), callee(cxxMethodDecl(hasAnyName("size", "length"))), 297 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)), 298 hasType(RecordWithBeginEnd)))); 299 300 StatementMatcher EndInitMatcher = 301 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(EndCallName)), 302 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts( 303 expr(SizeCallMatcher).bind(EndCallName)))))); 304 305 DeclarationMatcher EndDeclMatcher = 306 varDecl(hasInitializer(EndInitMatcher)).bind(EndVarName); 307 308 StatementMatcher IndexBoundMatcher = 309 expr(anyOf(ignoringParenImpCasts(declRefExpr(to( 310 varDecl(hasType(isInteger())).bind(ConditionEndVarName)))), 311 EndInitMatcher)); 312 313 return forStmt( 314 unless(isInTemplateInstantiation()), 315 hasLoopInit( 316 anyOf(declStmt(declCountIs(2), 317 containsDeclaration(0, initToZeroMatcher()), 318 containsDeclaration(1, EndDeclMatcher)), 319 declStmt(hasSingleDecl(initToZeroMatcher())))), 320 hasCondition(anyOf( 321 binaryOperator(hasOperatorName("<"), 322 hasLHS(integerComparisonMatcher()), 323 hasRHS(IndexBoundMatcher)), 324 binaryOperator(hasOperatorName(">"), hasLHS(IndexBoundMatcher), 325 hasRHS(integerComparisonMatcher())))), 326 hasIncrement( 327 unaryOperator(hasOperatorName("++"), 328 hasUnaryOperand(incrementVarMatcher())))) 329 .bind(LoopNamePseudoArray); 330 } 331 332 /// Determine whether Init appears to be an initializing an iterator. 333 /// 334 /// If it is, returns the object whose begin() or end() method is called, and 335 /// the output parameter isArrow is set to indicate whether the initialization 336 /// is called via . or ->. 337 static const Expr *getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, 338 bool *IsArrow, bool IsReverse) { 339 // FIXME: Maybe allow declaration/initialization outside of the for loop. 340 const auto *TheCall = 341 dyn_cast_or_null<CXXMemberCallExpr>(digThroughConstructors(Init)); 342 if (!TheCall || TheCall->getNumArgs() != 0) 343 return nullptr; 344 345 const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee()); 346 if (!Member) 347 return nullptr; 348 StringRef Name = Member->getMemberDecl()->getName(); 349 if (!Name.consume_back(IsBegin ? "begin" : "end")) 350 return nullptr; 351 if (IsReverse && !Name.consume_back("r")) 352 return nullptr; 353 if (!Name.empty() && !Name.equals("c")) 354 return nullptr; 355 356 const Expr *SourceExpr = Member->getBase(); 357 if (!SourceExpr) 358 return nullptr; 359 360 *IsArrow = Member->isArrow(); 361 return SourceExpr; 362 } 363 364 /// Determines the container whose begin() and end() functions are called 365 /// for an iterator-based loop. 366 /// 367 /// BeginExpr must be a member call to a function named "begin()", and EndExpr 368 /// must be a member. 369 static const Expr *findContainer(ASTContext *Context, const Expr *BeginExpr, 370 const Expr *EndExpr, 371 bool *ContainerNeedsDereference, 372 bool IsReverse) { 373 // Now that we know the loop variable and test expression, make sure they are 374 // valid. 375 bool BeginIsArrow = false; 376 bool EndIsArrow = false; 377 const Expr *BeginContainerExpr = getContainerFromBeginEndCall( 378 BeginExpr, /*IsBegin=*/true, &BeginIsArrow, IsReverse); 379 if (!BeginContainerExpr) 380 return nullptr; 381 382 const Expr *EndContainerExpr = getContainerFromBeginEndCall( 383 EndExpr, /*IsBegin=*/false, &EndIsArrow, IsReverse); 384 // Disallow loops that try evil things like this (note the dot and arrow): 385 // for (IteratorType It = Obj.begin(), E = Obj->end(); It != E; ++It) { } 386 if (!EndContainerExpr || BeginIsArrow != EndIsArrow || 387 !areSameExpr(Context, EndContainerExpr, BeginContainerExpr)) 388 return nullptr; 389 390 *ContainerNeedsDereference = BeginIsArrow; 391 return BeginContainerExpr; 392 } 393 394 /// Obtain the original source code text from a SourceRange. 395 static StringRef getStringFromRange(SourceManager &SourceMgr, 396 const LangOptions &LangOpts, 397 SourceRange Range) { 398 if (SourceMgr.getFileID(Range.getBegin()) != 399 SourceMgr.getFileID(Range.getEnd())) { 400 return StringRef(); // Empty string. 401 } 402 403 return Lexer::getSourceText(CharSourceRange(Range, true), SourceMgr, 404 LangOpts); 405 } 406 407 /// If the given expression is actually a DeclRefExpr or a MemberExpr, 408 /// find and return the underlying ValueDecl; otherwise, return NULL. 409 static const ValueDecl *getReferencedVariable(const Expr *E) { 410 if (const DeclRefExpr *DRE = getDeclRef(E)) 411 return dyn_cast<VarDecl>(DRE->getDecl()); 412 if (const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts())) 413 return dyn_cast<FieldDecl>(Mem->getMemberDecl()); 414 return nullptr; 415 } 416 417 /// Returns true when the given expression is a member expression 418 /// whose base is `this` (implicitly or not). 419 static bool isDirectMemberExpr(const Expr *E) { 420 if (const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts())) 421 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts()); 422 return false; 423 } 424 425 /// Given an expression that represents an usage of an element from the 426 /// containter that we are iterating over, returns false when it can be 427 /// guaranteed this element cannot be modified as a result of this usage. 428 static bool canBeModified(ASTContext *Context, const Expr *E) { 429 if (E->getType().isConstQualified()) 430 return false; 431 auto Parents = Context->getParents(*E); 432 if (Parents.size() != 1) 433 return true; 434 if (const auto *Cast = Parents[0].get<ImplicitCastExpr>()) { 435 if ((Cast->getCastKind() == CK_NoOp && 436 Cast->getType() == E->getType().withConst()) || 437 (Cast->getCastKind() == CK_LValueToRValue && 438 !Cast->getType().isNull() && Cast->getType()->isFundamentalType())) 439 return false; 440 } 441 // FIXME: Make this function more generic. 442 return true; 443 } 444 445 /// Returns true when it can be guaranteed that the elements of the 446 /// container are not being modified. 447 static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages) { 448 for (const Usage &U : Usages) { 449 // Lambda captures are just redeclarations (VarDecl) of the same variable, 450 // not expressions. If we want to know if a variable that is captured by 451 // reference can be modified in an usage inside the lambda's body, we need 452 // to find the expression corresponding to that particular usage, later in 453 // this loop. 454 if (U.Kind != Usage::UK_CaptureByCopy && U.Kind != Usage::UK_CaptureByRef && 455 canBeModified(Context, U.Expression)) 456 return false; 457 } 458 return true; 459 } 460 461 /// Returns true if the elements of the container are never accessed 462 /// by reference. 463 static bool usagesReturnRValues(const UsageResult &Usages) { 464 for (const auto &U : Usages) { 465 if (U.Expression && !U.Expression->isRValue()) 466 return false; 467 } 468 return true; 469 } 470 471 /// Returns true if the container is const-qualified. 472 static bool containerIsConst(const Expr *ContainerExpr, bool Dereference) { 473 if (const auto *VDec = getReferencedVariable(ContainerExpr)) { 474 QualType CType = VDec->getType(); 475 if (Dereference) { 476 if (!CType->isPointerType()) 477 return false; 478 CType = CType->getPointeeType(); 479 } 480 // If VDec is a reference to a container, Dereference is false, 481 // but we still need to check the const-ness of the underlying container 482 // type. 483 CType = CType.getNonReferenceType(); 484 return CType.isConstQualified(); 485 } 486 return false; 487 } 488 489 LoopConvertCheck::RangeDescriptor::RangeDescriptor() 490 : ContainerNeedsDereference(false), DerefByConstRef(false), 491 DerefByValue(false), NeedsReverseCall(false) {} 492 493 LoopConvertCheck::LoopConvertCheck(StringRef Name, ClangTidyContext *Context) 494 : ClangTidyCheck(Name, Context), TUInfo(new TUTrackingInfo), 495 MaxCopySize(Options.get("MaxCopySize", 16ULL)), 496 MinConfidence(Options.get("MinConfidence", Confidence::CL_Reasonable)), 497 NamingStyle(Options.get("NamingStyle", VariableNamer::NS_CamelCase)), 498 Inserter(Options.getLocalOrGlobal("IncludeStyle", 499 utils::IncludeSorter::IS_LLVM)), 500 UseCxx20IfAvailable(Options.get("UseCxx20ReverseRanges", true)), 501 ReverseFunction(Options.get("MakeReverseRangeFunction", "")), 502 ReverseHeader(Options.get("MakeReverseRangeHeader", "")) { 503 504 if (ReverseFunction.empty() && !ReverseHeader.empty()) { 505 configurationDiag( 506 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but " 507 "'MakeReverseRangeFunction' is not, disabling reverse loop " 508 "transformation"); 509 UseReverseRanges = false; 510 } else if (ReverseFunction.empty()) { 511 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20; 512 } else { 513 UseReverseRanges = true; 514 } 515 } 516 517 void LoopConvertCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { 518 Options.store(Opts, "MaxCopySize", MaxCopySize); 519 Options.store(Opts, "MinConfidence", MinConfidence); 520 Options.store(Opts, "NamingStyle", NamingStyle); 521 Options.store(Opts, "IncludeStyle", Inserter.getStyle()); 522 Options.store(Opts, "UseCxx20ReverseRanges", UseCxx20IfAvailable); 523 Options.store(Opts, "MakeReverseRangeFunction", ReverseFunction); 524 Options.store(Opts, "MakeReverseRangeHeader", ReverseHeader); 525 } 526 527 void LoopConvertCheck::registerPPCallbacks(const SourceManager &SM, 528 Preprocessor *PP, 529 Preprocessor *ModuleExpanderPP) { 530 Inserter.registerPreprocessor(PP); 531 } 532 533 void LoopConvertCheck::registerMatchers(MatchFinder *Finder) { 534 Finder->addMatcher(traverse(TK_AsIs, makeArrayLoopMatcher()), this); 535 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(false)), this); 536 Finder->addMatcher(traverse(TK_AsIs, makePseudoArrayLoopMatcher()), this); 537 if (UseReverseRanges) 538 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(true)), this); 539 } 540 541 /// Given the range of a single declaration, such as: 542 /// \code 543 /// unsigned &ThisIsADeclarationThatCanSpanSeveralLinesOfCode = 544 /// InitializationValues[I]; 545 /// next_instruction; 546 /// \endcode 547 /// Finds the range that has to be erased to remove this declaration without 548 /// leaving empty lines, by extending the range until the beginning of the 549 /// next instruction. 550 /// 551 /// We need to delete a potential newline after the deleted alias, as 552 /// clang-format will leave empty lines untouched. For all other formatting we 553 /// rely on clang-format to fix it. 554 void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) { 555 bool Invalid = false; 556 const char *TextAfter = 557 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid); 558 if (Invalid) 559 return; 560 unsigned Offset = std::strspn(TextAfter, " \t\r\n"); 561 Range = 562 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset)); 563 } 564 565 /// Computes the changes needed to convert a given for loop, and 566 /// applies them. 567 void LoopConvertCheck::doConversion( 568 ASTContext *Context, const VarDecl *IndexVar, 569 const ValueDecl *MaybeContainer, const UsageResult &Usages, 570 const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit, 571 const ForStmt *Loop, RangeDescriptor Descriptor) { 572 std::string VarName; 573 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl; 574 bool AliasVarIsRef = false; 575 bool CanCopy = true; 576 std::vector<FixItHint> FixIts; 577 if (VarNameFromAlias) { 578 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl()); 579 VarName = AliasVar->getName().str(); 580 581 // Use the type of the alias if it's not the same 582 QualType AliasVarType = AliasVar->getType(); 583 assert(!AliasVarType.isNull() && "Type in VarDecl is null"); 584 if (AliasVarType->isReferenceType()) { 585 AliasVarType = AliasVarType.getNonReferenceType(); 586 AliasVarIsRef = true; 587 } 588 if (Descriptor.ElemType.isNull() || 589 !Context->hasSameUnqualifiedType(AliasVarType, Descriptor.ElemType)) 590 Descriptor.ElemType = AliasVarType; 591 592 // We keep along the entire DeclStmt to keep the correct range here. 593 SourceRange ReplaceRange = AliasDecl->getSourceRange(); 594 595 std::string ReplacementText; 596 if (AliasUseRequired) { 597 ReplacementText = VarName; 598 } else if (AliasFromForInit) { 599 // FIXME: Clang includes the location of the ';' but only for DeclStmt's 600 // in a for loop's init clause. Need to put this ';' back while removing 601 // the declaration of the alias variable. This is probably a bug. 602 ReplacementText = ";"; 603 } else { 604 // Avoid leaving empty lines or trailing whitespaces. 605 getAliasRange(Context->getSourceManager(), ReplaceRange); 606 } 607 608 FixIts.push_back(FixItHint::CreateReplacement( 609 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText)); 610 // No further replacements are made to the loop, since the iterator or index 611 // was used exactly once - in the initialization of AliasVar. 612 } else { 613 VariableNamer Namer(&TUInfo->getGeneratedDecls(), 614 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 615 Loop, IndexVar, MaybeContainer, Context, NamingStyle); 616 VarName = Namer.createIndexName(); 617 // First, replace all usages of the array subscript expression with our new 618 // variable. 619 for (const auto &Usage : Usages) { 620 std::string ReplaceText; 621 SourceRange Range = Usage.Range; 622 if (Usage.Expression) { 623 // If this is an access to a member through the arrow operator, after 624 // the replacement it must be accessed through the '.' operator. 625 ReplaceText = Usage.Kind == Usage::UK_MemberThroughArrow ? VarName + "." 626 : VarName; 627 auto Parents = Context->getParents(*Usage.Expression); 628 if (Parents.size() == 1) { 629 if (const auto *Paren = Parents[0].get<ParenExpr>()) { 630 // Usage.Expression will be replaced with the new index variable, 631 // and parenthesis around a simple DeclRefExpr can always be 632 // removed. 633 Range = Paren->getSourceRange(); 634 } else if (const auto *UOP = Parents[0].get<UnaryOperator>()) { 635 // If we are taking the address of the loop variable, then we must 636 // not use a copy, as it would mean taking the address of the loop's 637 // local index instead. 638 // FIXME: This won't catch cases where the address is taken outside 639 // of the loop's body (for instance, in a function that got the 640 // loop's index as a const reference parameter), or where we take 641 // the address of a member (like "&Arr[i].A.B.C"). 642 if (UOP->getOpcode() == UO_AddrOf) 643 CanCopy = false; 644 } 645 } 646 } else { 647 // The Usage expression is only null in case of lambda captures (which 648 // are VarDecl). If the index is captured by value, add '&' to capture 649 // by reference instead. 650 ReplaceText = 651 Usage.Kind == Usage::UK_CaptureByCopy ? "&" + VarName : VarName; 652 } 653 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar)); 654 FixIts.push_back(FixItHint::CreateReplacement( 655 CharSourceRange::getTokenRange(Range), ReplaceText)); 656 } 657 } 658 659 // Now, we need to construct the new range expression. 660 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc()); 661 662 QualType Type = Context->getAutoDeductType(); 663 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType()) 664 Type = Descriptor.ElemType.getUnqualifiedType(); 665 Type = Type.getDesugaredType(*Context); 666 667 // If the new variable name is from the aliased variable, then the reference 668 // type for the new variable should only be used if the aliased variable was 669 // declared as a reference. 670 bool IsCheapToCopy = 671 !Descriptor.ElemType.isNull() && 672 Descriptor.ElemType.isTriviallyCopyableType(*Context) && 673 // TypeInfo::Width is in bits. 674 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize; 675 bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) || 676 (Descriptor.DerefByConstRef && IsCheapToCopy)); 677 678 if (!UseCopy) { 679 if (Descriptor.DerefByConstRef) { 680 Type = Context->getLValueReferenceType(Context->getConstType(Type)); 681 } else if (Descriptor.DerefByValue) { 682 if (!IsCheapToCopy) 683 Type = Context->getRValueReferenceType(Type); 684 } else { 685 Type = Context->getLValueReferenceType(Type); 686 } 687 } 688 689 SmallString<128> Range; 690 llvm::raw_svector_ostream Output(Range); 691 Output << '('; 692 Type.print(Output, getLangOpts()); 693 Output << ' ' << VarName << " : "; 694 if (Descriptor.NeedsReverseCall) 695 Output << getReverseFunction() << '('; 696 if (Descriptor.ContainerNeedsDereference) 697 Output << '*'; 698 Output << Descriptor.ContainerString; 699 if (Descriptor.NeedsReverseCall) 700 Output << "))"; 701 else 702 Output << ')'; 703 FixIts.push_back(FixItHint::CreateReplacement( 704 CharSourceRange::getTokenRange(ParenRange), Range)); 705 706 if (Descriptor.NeedsReverseCall && !getReverseHeader().empty()) { 707 if (Optional<FixItHint> Insertion = Inserter.createIncludeInsertion( 708 Context->getSourceManager().getFileID(Loop->getBeginLoc()), 709 getReverseHeader())) 710 FixIts.push_back(*Insertion); 711 } 712 diag(Loop->getForLoc(), "use range-based for loop instead") << FixIts; 713 TUInfo->getGeneratedDecls().insert(make_pair(Loop, VarName)); 714 } 715 716 /// Returns a string which refers to the container iterated over. 717 StringRef LoopConvertCheck::getContainerString(ASTContext *Context, 718 const ForStmt *Loop, 719 const Expr *ContainerExpr) { 720 StringRef ContainerString; 721 ContainerExpr = ContainerExpr->IgnoreParenImpCasts(); 722 if (isa<CXXThisExpr>(ContainerExpr)) { 723 ContainerString = "this"; 724 } else { 725 // For CXXOperatorCallExpr (e.g. vector_ptr->size()), its first argument is 726 // the class object (vector_ptr) we are targeting. 727 if (const auto* E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr)) 728 ContainerExpr = E->getArg(0); 729 ContainerString = 730 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(), 731 ContainerExpr->getSourceRange()); 732 } 733 734 return ContainerString; 735 } 736 737 /// Determines what kind of 'auto' must be used after converting a for 738 /// loop that iterates over an array or pseudoarray. 739 void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context, 740 const BoundNodes &Nodes, 741 const Expr *ContainerExpr, 742 const UsageResult &Usages, 743 RangeDescriptor &Descriptor) { 744 // On arrays and pseudoarrays, we must figure out the qualifiers from the 745 // usages. 746 if (usagesAreConst(Context, Usages) || 747 containerIsConst(ContainerExpr, Descriptor.ContainerNeedsDereference)) { 748 Descriptor.DerefByConstRef = true; 749 } 750 if (usagesReturnRValues(Usages)) { 751 // If the index usages (dereference, subscript, at, ...) return rvalues, 752 // then we should not use a reference, because we need to keep the code 753 // correct if it mutates the returned objects. 754 Descriptor.DerefByValue = true; 755 } 756 // Try to find the type of the elements on the container, to check if 757 // they are trivially copyable. 758 for (const Usage &U : Usages) { 759 if (!U.Expression || U.Expression->getType().isNull()) 760 continue; 761 QualType Type = U.Expression->getType().getCanonicalType(); 762 if (U.Kind == Usage::UK_MemberThroughArrow) { 763 if (!Type->isPointerType()) { 764 continue; 765 } 766 Type = Type->getPointeeType(); 767 } 768 Descriptor.ElemType = Type; 769 } 770 } 771 772 /// Determines what kind of 'auto' must be used after converting an 773 /// iterator based for loop. 774 void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context, 775 const BoundNodes &Nodes, 776 RangeDescriptor &Descriptor) { 777 // The matchers for iterator loops provide bound nodes to obtain this 778 // information. 779 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName); 780 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType(); 781 const auto *DerefByValueType = 782 Nodes.getNodeAs<QualType>(DerefByValueResultName); 783 Descriptor.DerefByValue = DerefByValueType; 784 785 if (Descriptor.DerefByValue) { 786 // If the dereference operator returns by value then test for the 787 // canonical const qualification of the init variable type. 788 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified(); 789 Descriptor.ElemType = *DerefByValueType; 790 } else { 791 if (const auto *DerefType = 792 Nodes.getNodeAs<QualType>(DerefByRefResultName)) { 793 // A node will only be bound with DerefByRefResultName if we're dealing 794 // with a user-defined iterator type. Test the const qualification of 795 // the reference type. 796 auto ValueType = DerefType->getNonReferenceType(); 797 798 Descriptor.DerefByConstRef = ValueType.isConstQualified(); 799 Descriptor.ElemType = ValueType; 800 } else { 801 // By nature of the matcher this case is triggered only for built-in 802 // iterator types (i.e. pointers). 803 assert(isa<PointerType>(CanonicalInitVarType) && 804 "Non-class iterator type is not a pointer type"); 805 806 // We test for const qualification of the pointed-at type. 807 Descriptor.DerefByConstRef = 808 CanonicalInitVarType->getPointeeType().isConstQualified(); 809 Descriptor.ElemType = CanonicalInitVarType->getPointeeType(); 810 } 811 } 812 } 813 814 /// Determines the parameters needed to build the range replacement. 815 void LoopConvertCheck::determineRangeDescriptor( 816 ASTContext *Context, const BoundNodes &Nodes, const ForStmt *Loop, 817 LoopFixerKind FixerKind, const Expr *ContainerExpr, 818 const UsageResult &Usages, RangeDescriptor &Descriptor) { 819 Descriptor.ContainerString = 820 std::string(getContainerString(Context, Loop, ContainerExpr)); 821 Descriptor.NeedsReverseCall = (FixerKind == LFK_ReverseIterator); 822 823 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) 824 getIteratorLoopQualifiers(Context, Nodes, Descriptor); 825 else 826 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor); 827 } 828 829 /// Check some of the conditions that must be met for the loop to be 830 /// convertible. 831 bool LoopConvertCheck::isConvertible(ASTContext *Context, 832 const ast_matchers::BoundNodes &Nodes, 833 const ForStmt *Loop, 834 LoopFixerKind FixerKind) { 835 // If we already modified the range of this for loop, don't do any further 836 // updates on this iteration. 837 if (TUInfo->getReplacedVars().count(Loop)) 838 return false; 839 840 // Check that we have exactly one index variable and at most one end variable. 841 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(IncrementVarName); 842 const auto *CondVar = Nodes.getNodeAs<VarDecl>(ConditionVarName); 843 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName); 844 if (!areSameVariable(LoopVar, CondVar) || !areSameVariable(LoopVar, InitVar)) 845 return false; 846 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName); 847 const auto *ConditionEndVar = Nodes.getNodeAs<VarDecl>(ConditionEndVarName); 848 if (EndVar && !areSameVariable(EndVar, ConditionEndVar)) 849 return false; 850 851 // FIXME: Try to put most of this logic inside a matcher. 852 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) { 853 QualType InitVarType = InitVar->getType(); 854 QualType CanonicalInitVarType = InitVarType.getCanonicalType(); 855 856 const auto *BeginCall = Nodes.getNodeAs<CXXMemberCallExpr>(BeginCallName); 857 assert(BeginCall && "Bad Callback. No begin call expression"); 858 QualType CanonicalBeginType = 859 BeginCall->getMethodDecl()->getReturnType().getCanonicalType(); 860 if (CanonicalBeginType->isPointerType() && 861 CanonicalInitVarType->isPointerType()) { 862 // If the initializer and the variable are both pointers check if the 863 // un-qualified pointee types match, otherwise we don't use auto. 864 if (!Context->hasSameUnqualifiedType( 865 CanonicalBeginType->getPointeeType(), 866 CanonicalInitVarType->getPointeeType())) 867 return false; 868 } 869 } else if (FixerKind == LFK_PseudoArray) { 870 // This call is required to obtain the container. 871 const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName); 872 if (!EndCall || !dyn_cast<MemberExpr>(EndCall->getCallee())) 873 return false; 874 } 875 return true; 876 } 877 878 void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) { 879 const BoundNodes &Nodes = Result.Nodes; 880 Confidence ConfidenceLevel(Confidence::CL_Safe); 881 ASTContext *Context = Result.Context; 882 883 const ForStmt *Loop; 884 LoopFixerKind FixerKind; 885 RangeDescriptor Descriptor; 886 887 if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameArray))) { 888 FixerKind = LFK_Array; 889 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameIterator))) { 890 FixerKind = LFK_Iterator; 891 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameReverseIterator))) { 892 FixerKind = LFK_ReverseIterator; 893 } else { 894 Loop = Nodes.getNodeAs<ForStmt>(LoopNamePseudoArray); 895 assert(Loop && "Bad Callback. No for statement"); 896 FixerKind = LFK_PseudoArray; 897 } 898 899 if (!isConvertible(Context, Nodes, Loop, FixerKind)) 900 return; 901 902 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(IncrementVarName); 903 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName); 904 905 // If the loop calls end()/size() after each iteration, lower our confidence 906 // level. 907 if (FixerKind != LFK_Array && !EndVar) 908 ConfidenceLevel.lowerTo(Confidence::CL_Reasonable); 909 910 // If the end comparison isn't a variable, we can try to work with the 911 // expression the loop variable is being tested against instead. 912 const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName); 913 const auto *BoundExpr = Nodes.getNodeAs<Expr>(ConditionBoundName); 914 915 // Find container expression of iterators and pseudoarrays, and determine if 916 // this expression needs to be dereferenced to obtain the container. 917 // With array loops, the container is often discovered during the 918 // ForLoopIndexUseVisitor traversal. 919 const Expr *ContainerExpr = nullptr; 920 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) { 921 ContainerExpr = findContainer( 922 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall, 923 &Descriptor.ContainerNeedsDereference, 924 /*IsReverse=*/FixerKind == LFK_ReverseIterator); 925 } else if (FixerKind == LFK_PseudoArray) { 926 ContainerExpr = EndCall->getImplicitObjectArgument(); 927 Descriptor.ContainerNeedsDereference = 928 dyn_cast<MemberExpr>(EndCall->getCallee())->isArrow(); 929 } 930 931 // We must know the container or an array length bound. 932 if (!ContainerExpr && !BoundExpr) 933 return; 934 935 ForLoopIndexUseVisitor Finder(Context, LoopVar, EndVar, ContainerExpr, 936 BoundExpr, 937 Descriptor.ContainerNeedsDereference); 938 939 // Find expressions and variables on which the container depends. 940 if (ContainerExpr) { 941 ComponentFinderASTVisitor ComponentFinder; 942 ComponentFinder.findExprComponents(ContainerExpr->IgnoreParenImpCasts()); 943 Finder.addComponents(ComponentFinder.getComponents()); 944 } 945 946 // Find usages of the loop index. If they are not used in a convertible way, 947 // stop here. 948 if (!Finder.findAndVerifyUsages(Loop->getBody())) 949 return; 950 ConfidenceLevel.lowerTo(Finder.getConfidenceLevel()); 951 952 // Obtain the container expression, if we don't have it yet. 953 if (FixerKind == LFK_Array) { 954 ContainerExpr = Finder.getContainerIndexed()->IgnoreParenImpCasts(); 955 956 // Very few loops are over expressions that generate arrays rather than 957 // array variables. Consider loops over arrays that aren't just represented 958 // by a variable to be risky conversions. 959 if (!getReferencedVariable(ContainerExpr) && 960 !isDirectMemberExpr(ContainerExpr)) 961 ConfidenceLevel.lowerTo(Confidence::CL_Risky); 962 } 963 964 // Find out which qualifiers we have to use in the loop range. 965 TraversalKindScope RAII(*Context, TK_AsIs); 966 const UsageResult &Usages = Finder.getUsages(); 967 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr, 968 Usages, Descriptor); 969 970 // Ensure that we do not try to move an expression dependent on a local 971 // variable declared inside the loop outside of it. 972 // FIXME: Determine when the external dependency isn't an expression converted 973 // by another loop. 974 TUInfo->getParentFinder().gatherAncestors(*Context); 975 DependencyFinderASTVisitor DependencyFinder( 976 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 977 &TUInfo->getParentFinder().getDeclToParentStmtMap(), 978 &TUInfo->getReplacedVars(), Loop); 979 980 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) || 981 Descriptor.ContainerString.empty() || Usages.empty() || 982 ConfidenceLevel.getLevel() < MinConfidence) 983 return; 984 985 doConversion(Context, LoopVar, getReferencedVariable(ContainerExpr), Usages, 986 Finder.getAliasDecl(), Finder.aliasUseRequired(), 987 Finder.aliasFromForInit(), Loop, Descriptor); 988 } 989 990 llvm::StringRef LoopConvertCheck::getReverseFunction() const { 991 if (!ReverseFunction.empty()) 992 return ReverseFunction; 993 if (UseReverseRanges) 994 return "std::ranges::reverse_view"; 995 return ""; 996 } 997 998 llvm::StringRef LoopConvertCheck::getReverseHeader() const { 999 if (!ReverseHeader.empty()) 1000 return ReverseHeader; 1001 if (UseReverseRanges && ReverseFunction.empty()) { 1002 return "<ranges>"; 1003 } 1004 return ""; 1005 } 1006 1007 } // namespace modernize 1008 } // namespace tidy 1009 } // namespace clang 1010