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