1 //===--- LoopConvertCheck.cpp - clang-tidy---------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "LoopConvertCheck.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 14 using namespace clang; 15 using namespace clang::ast_matchers; 16 using namespace llvm; 17 18 namespace clang { 19 namespace tidy { 20 namespace modernize { 21 22 const char LoopNameArray[] = "forLoopArray"; 23 const char LoopNameIterator[] = "forLoopIterator"; 24 const char LoopNamePseudoArray[] = "forLoopPseudoArray"; 25 const char ConditionBoundName[] = "conditionBound"; 26 const char ConditionVarName[] = "conditionVar"; 27 const char IncrementVarName[] = "incrementVar"; 28 const char InitVarName[] = "initVar"; 29 const char BeginCallName[] = "beginCall"; 30 const char EndCallName[] = "endCall"; 31 const char ConditionEndVarName[] = "conditionEndVar"; 32 const char EndVarName[] = "endVar"; 33 const char DerefByValueResultName[] = "derefByValueResult"; 34 const char DerefByRefResultName[] = "derefByRefResult"; 35 36 // shared matchers 37 static const TypeMatcher AnyType = anything(); 38 39 static const StatementMatcher IntegerComparisonMatcher = 40 expr(ignoringParenImpCasts( 41 declRefExpr(to(varDecl(hasType(isInteger())).bind(ConditionVarName))))); 42 43 static const DeclarationMatcher InitToZeroMatcher = 44 varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0))))) 45 .bind(InitVarName); 46 47 static const StatementMatcher IncrementVarMatcher = 48 declRefExpr(to(varDecl(hasType(isInteger())).bind(IncrementVarName))); 49 50 /// \brief The matcher for loops over arrays. 51 /// 52 /// In this general example, assuming 'j' and 'k' are of integral type: 53 /// \code 54 /// for (int i = 0; j < 3 + 2; ++k) { ... } 55 /// \endcode 56 /// The following string identifiers are bound to these parts of the AST: 57 /// ConditionVarName: 'j' (as a VarDecl) 58 /// ConditionBoundName: '3 + 2' (as an Expr) 59 /// InitVarName: 'i' (as a VarDecl) 60 /// IncrementVarName: 'k' (as a VarDecl) 61 /// LoopName: The entire for loop (as a ForStmt) 62 /// 63 /// Client code will need to make sure that: 64 /// - The three index variables identified by the matcher are the same 65 /// VarDecl. 66 /// - The index variable is only used as an array index. 67 /// - All arrays indexed by the loop are the same. 68 StatementMatcher makeArrayLoopMatcher() { 69 StatementMatcher ArrayBoundMatcher = 70 expr(hasType(isInteger())).bind(ConditionBoundName); 71 72 return forStmt( 73 unless(isInTemplateInstantiation()), 74 hasLoopInit(declStmt(hasSingleDecl(InitToZeroMatcher))), 75 hasCondition(anyOf( 76 binaryOperator(hasOperatorName("<"), 77 hasLHS(IntegerComparisonMatcher), 78 hasRHS(ArrayBoundMatcher)), 79 binaryOperator(hasOperatorName(">"), hasLHS(ArrayBoundMatcher), 80 hasRHS(IntegerComparisonMatcher)))), 81 hasIncrement(unaryOperator(hasOperatorName("++"), 82 hasUnaryOperand(IncrementVarMatcher)))) 83 .bind(LoopNameArray); 84 } 85 86 /// \brief The matcher used for iterator-based for loops. 87 /// 88 /// This matcher is more flexible than array-based loops. It will match 89 /// catch loops of the following textual forms (regardless of whether the 90 /// iterator type is actually a pointer type or a class type): 91 /// 92 /// Assuming f, g, and h are of type containerType::iterator, 93 /// \code 94 /// for (containerType::iterator it = container.begin(), 95 /// e = createIterator(); f != g; ++h) { ... } 96 /// for (containerType::iterator it = container.begin(); 97 /// f != anotherContainer.end(); ++h) { ... } 98 /// \endcode 99 /// The following string identifiers are bound to the parts of the AST: 100 /// InitVarName: 'it' (as a VarDecl) 101 /// ConditionVarName: 'f' (as a VarDecl) 102 /// LoopName: The entire for loop (as a ForStmt) 103 /// In the first example only: 104 /// EndVarName: 'e' (as a VarDecl) 105 /// ConditionEndVarName: 'g' (as a VarDecl) 106 /// In the second example only: 107 /// EndCallName: 'container.end()' (as a CXXMemberCallExpr) 108 /// 109 /// Client code will need to make sure that: 110 /// - The iterator variables 'it', 'f', and 'h' are the same. 111 /// - The two containers on which 'begin' and 'end' are called are the same. 112 /// - If the end iterator variable 'g' is defined, it is the same as 'f'. 113 StatementMatcher makeIteratorLoopMatcher() { 114 StatementMatcher BeginCallMatcher = 115 cxxMemberCallExpr(argumentCountIs(0), 116 callee(cxxMethodDecl(hasName("begin")))) 117 .bind(BeginCallName); 118 119 DeclarationMatcher InitDeclMatcher = 120 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher), 121 materializeTemporaryExpr( 122 ignoringParenImpCasts(BeginCallMatcher)), 123 hasDescendant(BeginCallMatcher)))) 124 .bind(InitVarName); 125 126 DeclarationMatcher EndDeclMatcher = 127 varDecl(hasInitializer(anything())).bind(EndVarName); 128 129 StatementMatcher EndCallMatcher = cxxMemberCallExpr( 130 argumentCountIs(0), callee(cxxMethodDecl(hasName("end")))); 131 132 StatementMatcher IteratorBoundMatcher = 133 expr(anyOf(ignoringParenImpCasts( 134 declRefExpr(to(varDecl().bind(ConditionEndVarName)))), 135 ignoringParenImpCasts(expr(EndCallMatcher).bind(EndCallName)), 136 materializeTemporaryExpr(ignoringParenImpCasts( 137 expr(EndCallMatcher).bind(EndCallName))))); 138 139 StatementMatcher IteratorComparisonMatcher = expr( 140 ignoringParenImpCasts(declRefExpr(to(varDecl().bind(ConditionVarName))))); 141 142 StatementMatcher OverloadedNEQMatcher = 143 cxxOperatorCallExpr(hasOverloadedOperatorName("!="), argumentCountIs(2), 144 hasArgument(0, IteratorComparisonMatcher), 145 hasArgument(1, IteratorBoundMatcher)); 146 147 // This matcher tests that a declaration is a CXXRecordDecl that has an 148 // overloaded operator*(). If the operator*() returns by value instead of by 149 // reference then the return type is tagged with DerefByValueResultName. 150 internal::Matcher<VarDecl> TestDerefReturnsByValue = 151 hasType(cxxRecordDecl(hasMethod(allOf( 152 hasOverloadedOperatorName("*"), 153 anyOf( 154 // Tag the return type if it's by value. 155 returns(qualType(unless(hasCanonicalType(referenceType()))) 156 .bind(DerefByValueResultName)), 157 returns( 158 // Skip loops where the iterator's operator* returns an 159 // rvalue reference. This is just weird. 160 qualType(unless(hasCanonicalType(rValueReferenceType()))) 161 .bind(DerefByRefResultName))))))); 162 163 return forStmt( 164 unless(isInTemplateInstantiation()), 165 hasLoopInit(anyOf(declStmt(declCountIs(2), 166 containsDeclaration(0, InitDeclMatcher), 167 containsDeclaration(1, EndDeclMatcher)), 168 declStmt(hasSingleDecl(InitDeclMatcher)))), 169 hasCondition( 170 anyOf(binaryOperator(hasOperatorName("!="), 171 hasLHS(IteratorComparisonMatcher), 172 hasRHS(IteratorBoundMatcher)), 173 binaryOperator(hasOperatorName("!="), 174 hasLHS(IteratorBoundMatcher), 175 hasRHS(IteratorComparisonMatcher)), 176 OverloadedNEQMatcher)), 177 hasIncrement(anyOf( 178 unaryOperator(hasOperatorName("++"), 179 hasUnaryOperand(declRefExpr( 180 to(varDecl(hasType(pointsTo(AnyType))) 181 .bind(IncrementVarName))))), 182 cxxOperatorCallExpr( 183 hasOverloadedOperatorName("++"), 184 hasArgument( 185 0, declRefExpr(to(varDecl(TestDerefReturnsByValue) 186 .bind(IncrementVarName)))))))) 187 .bind(LoopNameIterator); 188 } 189 190 /// \brief The matcher used for array-like containers (pseudoarrays). 191 /// 192 /// This matcher is more flexible than array-based loops. It will match 193 /// loops of the following textual forms (regardless of whether the 194 /// iterator type is actually a pointer type or a class type): 195 /// 196 /// Assuming f, g, and h are of type containerType::iterator, 197 /// \code 198 /// for (int i = 0, j = container.size(); f < g; ++h) { ... } 199 /// for (int i = 0; f < container.size(); ++h) { ... } 200 /// \endcode 201 /// The following string identifiers are bound to the parts of the AST: 202 /// InitVarName: 'i' (as a VarDecl) 203 /// ConditionVarName: 'f' (as a VarDecl) 204 /// LoopName: The entire for loop (as a ForStmt) 205 /// In the first example only: 206 /// EndVarName: 'j' (as a VarDecl) 207 /// ConditionEndVarName: 'g' (as a VarDecl) 208 /// In the second example only: 209 /// EndCallName: 'container.size()' (as a CXXMemberCallExpr) 210 /// 211 /// Client code will need to make sure that: 212 /// - The index variables 'i', 'f', and 'h' are the same. 213 /// - The containers on which 'size()' is called is the container indexed. 214 /// - The index variable is only used in overloaded operator[] or 215 /// container.at(). 216 /// - If the end iterator variable 'g' is defined, it is the same as 'j'. 217 /// - The container's iterators would not be invalidated during the loop. 218 StatementMatcher makePseudoArrayLoopMatcher() { 219 // Test that the incoming type has a record declaration that has methods 220 // called 'begin' and 'end'. If the incoming type is const, then make sure 221 // these methods are also marked const. 222 // 223 // FIXME: To be completely thorough this matcher should also ensure the 224 // return type of begin/end is an iterator that dereferences to the same as 225 // what operator[] or at() returns. Such a test isn't likely to fail except 226 // for pathological cases. 227 // 228 // FIXME: Also, a record doesn't necessarily need begin() and end(). Free 229 // functions called begin() and end() taking the container as an argument 230 // are also allowed. 231 TypeMatcher RecordWithBeginEnd = qualType( 232 anyOf(qualType(isConstQualified(), 233 hasDeclaration(cxxRecordDecl( 234 hasMethod(cxxMethodDecl(hasName("begin"), isConst())), 235 hasMethod(cxxMethodDecl(hasName("end"), 236 isConst())))) // hasDeclaration 237 ), // qualType 238 qualType(unless(isConstQualified()), 239 hasDeclaration( 240 cxxRecordDecl(hasMethod(hasName("begin")), 241 hasMethod(hasName("end"))))) // qualType 242 )); 243 244 StatementMatcher SizeCallMatcher = cxxMemberCallExpr( 245 argumentCountIs(0), 246 callee(cxxMethodDecl(anyOf(hasName("size"), hasName("length")))), 247 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)), 248 hasType(RecordWithBeginEnd)))); 249 250 StatementMatcher EndInitMatcher = 251 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(EndCallName)), 252 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts( 253 expr(SizeCallMatcher).bind(EndCallName)))))); 254 255 DeclarationMatcher EndDeclMatcher = 256 varDecl(hasInitializer(EndInitMatcher)).bind(EndVarName); 257 258 StatementMatcher IndexBoundMatcher = 259 expr(anyOf(ignoringParenImpCasts(declRefExpr(to( 260 varDecl(hasType(isInteger())).bind(ConditionEndVarName)))), 261 EndInitMatcher)); 262 263 return forStmt( 264 unless(isInTemplateInstantiation()), 265 hasLoopInit( 266 anyOf(declStmt(declCountIs(2), 267 containsDeclaration(0, InitToZeroMatcher), 268 containsDeclaration(1, EndDeclMatcher)), 269 declStmt(hasSingleDecl(InitToZeroMatcher)))), 270 hasCondition(anyOf( 271 binaryOperator(hasOperatorName("<"), 272 hasLHS(IntegerComparisonMatcher), 273 hasRHS(IndexBoundMatcher)), 274 binaryOperator(hasOperatorName(">"), hasLHS(IndexBoundMatcher), 275 hasRHS(IntegerComparisonMatcher)))), 276 hasIncrement(unaryOperator(hasOperatorName("++"), 277 hasUnaryOperand(IncrementVarMatcher)))) 278 .bind(LoopNamePseudoArray); 279 } 280 281 /// \brief Determine whether Init appears to be an initializing an iterator. 282 /// 283 /// If it is, returns the object whose begin() or end() method is called, and 284 /// the output parameter isArrow is set to indicate whether the initialization 285 /// is called via . or ->. 286 static const Expr *getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, 287 bool *IsArrow) { 288 // FIXME: Maybe allow declaration/initialization outside of the for loop. 289 const auto *TheCall = 290 dyn_cast_or_null<CXXMemberCallExpr>(digThroughConstructors(Init)); 291 if (!TheCall || TheCall->getNumArgs() != 0) 292 return nullptr; 293 294 const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee()); 295 if (!Member) 296 return nullptr; 297 StringRef Name = Member->getMemberDecl()->getName(); 298 StringRef TargetName = IsBegin ? "begin" : "end"; 299 if (Name != TargetName) 300 return nullptr; 301 302 const Expr *SourceExpr = Member->getBase(); 303 if (!SourceExpr) 304 return nullptr; 305 306 *IsArrow = Member->isArrow(); 307 return SourceExpr; 308 } 309 310 /// \brief Determines the container whose begin() and end() functions are called 311 /// for an iterator-based loop. 312 /// 313 /// BeginExpr must be a member call to a function named "begin()", and EndExpr 314 /// must be a member. 315 static const Expr *findContainer(ASTContext *Context, const Expr *BeginExpr, 316 const Expr *EndExpr, 317 bool *ContainerNeedsDereference) { 318 // Now that we know the loop variable and test expression, make sure they are 319 // valid. 320 bool BeginIsArrow = false; 321 bool EndIsArrow = false; 322 const Expr *BeginContainerExpr = 323 getContainerFromBeginEndCall(BeginExpr, /*IsBegin=*/true, &BeginIsArrow); 324 if (!BeginContainerExpr) 325 return nullptr; 326 327 const Expr *EndContainerExpr = 328 getContainerFromBeginEndCall(EndExpr, /*IsBegin=*/false, &EndIsArrow); 329 // Disallow loops that try evil things like this (note the dot and arrow): 330 // for (IteratorType It = Obj.begin(), E = Obj->end(); It != E; ++It) { } 331 if (!EndContainerExpr || BeginIsArrow != EndIsArrow || 332 !areSameExpr(Context, EndContainerExpr, BeginContainerExpr)) 333 return nullptr; 334 335 *ContainerNeedsDereference = BeginIsArrow; 336 return BeginContainerExpr; 337 } 338 339 /// \brief Obtain the original source code text from a SourceRange. 340 static StringRef getStringFromRange(SourceManager &SourceMgr, 341 const LangOptions &LangOpts, 342 SourceRange Range) { 343 if (SourceMgr.getFileID(Range.getBegin()) != 344 SourceMgr.getFileID(Range.getEnd())) { 345 return StringRef(); // Empty string. 346 } 347 348 return Lexer::getSourceText(CharSourceRange(Range, true), SourceMgr, 349 LangOpts); 350 } 351 352 /// \brief If the given expression is actually a DeclRefExpr, find and return 353 /// the underlying VarDecl; otherwise, return NULL. 354 static const VarDecl *getReferencedVariable(const Expr *E) { 355 if (const DeclRefExpr *DRE = getDeclRef(E)) 356 return dyn_cast<VarDecl>(DRE->getDecl()); 357 return nullptr; 358 } 359 360 /// \brief Returns true when the given expression is a member expression 361 /// whose base is `this` (implicitly or not). 362 static bool isDirectMemberExpr(const Expr *E) { 363 if (const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts())) 364 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts()); 365 return false; 366 } 367 368 /// \brief Returns true when it can be guaranteed that the elements of the 369 /// container are not being modified. 370 static bool usagesAreConst(const UsageResult &Usages) { 371 // FIXME: Make this function more generic. 372 return Usages.empty(); 373 } 374 375 /// \brief Returns true if the elements of the container are never accessed 376 /// by reference. 377 static bool usagesReturnRValues(const UsageResult &Usages) { 378 for (const auto &U : Usages) { 379 if (U.Expression && !U.Expression->isRValue()) 380 return false; 381 } 382 return true; 383 } 384 385 /// \brief Returns true if the container is const-qualified. 386 static bool containerIsConst(const Expr *ContainerExpr, bool Dereference) { 387 if (const auto *VDec = getReferencedVariable(ContainerExpr)) { 388 QualType CType = VDec->getType(); 389 if (Dereference) { 390 if (!CType->isPointerType()) 391 return false; 392 CType = CType->getPointeeType(); 393 } 394 // If VDec is a reference to a container, Dereference is false, 395 // but we still need to check the const-ness of the underlying container 396 // type. 397 if (const auto &RT = CType->getAs<ReferenceType>()) { 398 CType = RT->getPointeeType(); 399 } 400 return CType.isConstQualified(); 401 } 402 return false; 403 } 404 405 LoopConvertCheck::RangeDescriptor::RangeDescriptor() 406 : ContainerNeedsDereference(false), DerefByConstRef(false), 407 DerefByValue(false), IsTriviallyCopyable(false) {} 408 409 LoopConvertCheck::LoopConvertCheck(StringRef Name, ClangTidyContext *Context) 410 : ClangTidyCheck(Name, Context), TUInfo(new TUTrackingInfo), 411 MinConfidence(StringSwitch<Confidence::Level>( 412 Options.get("MinConfidence", "reasonable")) 413 .Case("safe", Confidence::CL_Safe) 414 .Case("risky", Confidence::CL_Risky) 415 .Default(Confidence::CL_Reasonable)) {} 416 417 void LoopConvertCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { 418 SmallVector<std::string, 3> Confs{"risky", "reasonable", "safe"}; 419 Options.store(Opts, "MinConfidence", Confs[static_cast<int>(MinConfidence)]); 420 } 421 422 void LoopConvertCheck::registerMatchers(MatchFinder *Finder) { 423 // Only register the matchers for C++. Because this checker is used for 424 // modernization, it is reasonable to run it on any C++ standard with the 425 // assumption the user is trying to modernize their codebase. 426 if (!getLangOpts().CPlusPlus) 427 return; 428 429 Finder->addMatcher(makeArrayLoopMatcher(), this); 430 Finder->addMatcher(makeIteratorLoopMatcher(), this); 431 Finder->addMatcher(makePseudoArrayLoopMatcher(), this); 432 } 433 434 /// \brief Computes the changes needed to convert a given for loop, and 435 /// applies them. 436 void LoopConvertCheck::doConversion( 437 ASTContext *Context, const VarDecl *IndexVar, const VarDecl *MaybeContainer, 438 const UsageResult &Usages, const DeclStmt *AliasDecl, bool AliasUseRequired, 439 bool AliasFromForInit, const ForStmt *Loop, RangeDescriptor Descriptor) { 440 auto Diag = diag(Loop->getForLoc(), "use range-based for loop instead"); 441 442 std::string VarName; 443 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl; 444 bool AliasVarIsRef = false; 445 446 if (VarNameFromAlias) { 447 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl()); 448 VarName = AliasVar->getName().str(); 449 AliasVarIsRef = AliasVar->getType()->isReferenceType(); 450 451 // We keep along the entire DeclStmt to keep the correct range here. 452 const SourceRange &ReplaceRange = AliasDecl->getSourceRange(); 453 454 std::string ReplacementText; 455 if (AliasUseRequired) { 456 ReplacementText = VarName; 457 } else if (AliasFromForInit) { 458 // FIXME: Clang includes the location of the ';' but only for DeclStmt's 459 // in a for loop's init clause. Need to put this ';' back while removing 460 // the declaration of the alias variable. This is probably a bug. 461 ReplacementText = ";"; 462 } 463 464 Diag << FixItHint::CreateReplacement( 465 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText); 466 // No further replacements are made to the loop, since the iterator or index 467 // was used exactly once - in the initialization of AliasVar. 468 } else { 469 VariableNamer Namer(&TUInfo->getGeneratedDecls(), 470 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 471 Loop, IndexVar, MaybeContainer, Context); 472 VarName = Namer.createIndexName(); 473 // First, replace all usages of the array subscript expression with our new 474 // variable. 475 for (const auto &Usage : Usages) { 476 std::string ReplaceText; 477 if (Usage.Expression) { 478 // If this is an access to a member through the arrow operator, after 479 // the replacement it must be accessed through the '.' operator. 480 ReplaceText = Usage.Kind == Usage::UK_MemberThroughArrow ? VarName + "." 481 : VarName; 482 } else { 483 // The Usage expression is only null in case of lambda captures (which 484 // are VarDecl). If the index is captured by value, add '&' to capture 485 // by reference instead. 486 ReplaceText = 487 Usage.Kind == Usage::UK_CaptureByCopy ? "&" + VarName : VarName; 488 } 489 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar)); 490 Diag << FixItHint::CreateReplacement( 491 CharSourceRange::getTokenRange(Usage.Range), ReplaceText); 492 } 493 } 494 495 // Now, we need to construct the new range expression. 496 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc()); 497 498 QualType AutoType = Context->getAutoDeductType(); 499 500 // If the new variable name is from the aliased variable, then the reference 501 // type for the new variable should only be used if the aliased variable was 502 // declared as a reference. 503 if (!VarNameFromAlias || AliasVarIsRef) { 504 if (Descriptor.DerefByConstRef) { 505 AutoType = 506 Context->getLValueReferenceType(Context->getConstType(AutoType)); 507 } else if (Descriptor.DerefByValue) { 508 if (!Descriptor.IsTriviallyCopyable) 509 AutoType = Context->getRValueReferenceType(AutoType); 510 } else { 511 AutoType = Context->getLValueReferenceType(AutoType); 512 } 513 } 514 515 StringRef MaybeDereference = Descriptor.ContainerNeedsDereference ? "*" : ""; 516 std::string TypeString = AutoType.getAsString(); 517 std::string Range = ("(" + TypeString + " " + VarName + " : " + 518 MaybeDereference + Descriptor.ContainerString + ")") 519 .str(); 520 Diag << FixItHint::CreateReplacement( 521 CharSourceRange::getTokenRange(ParenRange), Range); 522 TUInfo->getGeneratedDecls().insert(make_pair(Loop, VarName)); 523 } 524 525 /// \brief Returns a string which refers to the container iterated over. 526 StringRef LoopConvertCheck::getContainerString(ASTContext *Context, 527 const ForStmt *Loop, 528 const Expr *ContainerExpr) { 529 StringRef ContainerString; 530 if (isa<CXXThisExpr>(ContainerExpr->IgnoreParenImpCasts())) { 531 ContainerString = "this"; 532 } else { 533 ContainerString = 534 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(), 535 ContainerExpr->getSourceRange()); 536 } 537 538 return ContainerString; 539 } 540 541 /// \brief Determines what kind of 'auto' must be used after converting a for 542 /// loop that iterates over an array or pseudoarray. 543 void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context, 544 const BoundNodes &Nodes, 545 const Expr *ContainerExpr, 546 const UsageResult &Usages, 547 RangeDescriptor &Descriptor) { 548 // On arrays and pseudoarrays, we must figure out the qualifiers from the 549 // usages. 550 if (usagesAreConst(Usages)) { 551 Descriptor.DerefByConstRef = true; 552 } else { 553 if (usagesReturnRValues(Usages)) { 554 // If the index usages (dereference, subscript, at, ...) return rvalues, 555 // then we should not use a reference, because we need to keep the code 556 // correct if it mutates the returned objects. 557 Descriptor.DerefByValue = true; 558 // Try to find the type of the elements on the container, to check if 559 // they are trivially copyable. 560 for (const Usage &U : Usages) { 561 if (!U.Expression || U.Expression->getType().isNull()) 562 continue; 563 QualType Type = U.Expression->getType().getCanonicalType(); 564 if (U.Kind == Usage::UK_MemberThroughArrow) { 565 if (!Type->isPointerType()) 566 continue; 567 Type = Type->getPointeeType(); 568 } 569 Descriptor.IsTriviallyCopyable = Type.isTriviallyCopyableType(*Context); 570 break; 571 } 572 } else if (containerIsConst(ContainerExpr, 573 Descriptor.ContainerNeedsDereference)) { 574 // The usages are lvalue references, we add a 'const' if the container 575 // is 'const'. This will always be the case with const arrays (unless 576 // usagesAreConst() returned true). 577 Descriptor.DerefByConstRef = true; 578 } 579 } 580 } 581 582 /// \brief Determines what kind of 'auto' must be used after converting an 583 /// iterator based for loop. 584 void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context, 585 const BoundNodes &Nodes, 586 RangeDescriptor &Descriptor) { 587 // The matchers for iterator loops provide bound nodes to obtain this 588 // information. 589 const auto *InitVar = Nodes.getDeclAs<VarDecl>(InitVarName); 590 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType(); 591 const auto *DerefByValueType = 592 Nodes.getNodeAs<QualType>(DerefByValueResultName); 593 Descriptor.DerefByValue = DerefByValueType; 594 595 if (Descriptor.DerefByValue) { 596 // If the dereference operator returns by value then test for the 597 // canonical const qualification of the init variable type. 598 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified(); 599 Descriptor.IsTriviallyCopyable = 600 DerefByValueType->isTriviallyCopyableType(*Context); 601 } else { 602 if (const auto *DerefType = 603 Nodes.getNodeAs<QualType>(DerefByRefResultName)) { 604 // A node will only be bound with DerefByRefResultName if we're dealing 605 // with a user-defined iterator type. Test the const qualification of 606 // the reference type. 607 Descriptor.DerefByConstRef = (*DerefType) 608 ->getAs<ReferenceType>() 609 ->getPointeeType() 610 .isConstQualified(); 611 } else { 612 // By nature of the matcher this case is triggered only for built-in 613 // iterator types (i.e. pointers). 614 assert(isa<PointerType>(CanonicalInitVarType) && 615 "Non-class iterator type is not a pointer type"); 616 617 // We test for const qualification of the pointed-at type. 618 Descriptor.DerefByConstRef = 619 CanonicalInitVarType->getPointeeType().isConstQualified(); 620 } 621 } 622 } 623 624 /// \brief Determines the parameters needed to build the range replacement. 625 void LoopConvertCheck::determineRangeDescriptor( 626 ASTContext *Context, const BoundNodes &Nodes, const ForStmt *Loop, 627 LoopFixerKind FixerKind, const Expr *ContainerExpr, 628 const UsageResult &Usages, RangeDescriptor &Descriptor) { 629 Descriptor.ContainerString = getContainerString(Context, Loop, ContainerExpr); 630 631 if (FixerKind == LFK_Iterator) 632 getIteratorLoopQualifiers(Context, Nodes, Descriptor); 633 else 634 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor); 635 } 636 637 /// \brief Check some of the conditions that must be met for the loop to be 638 /// convertible. 639 bool LoopConvertCheck::isConvertible(ASTContext *Context, 640 const ast_matchers::BoundNodes &Nodes, 641 const ForStmt *Loop, 642 LoopFixerKind FixerKind) { 643 // If we already modified the range of this for loop, don't do any further 644 // updates on this iteration. 645 if (TUInfo->getReplacedVars().count(Loop)) 646 return false; 647 648 // Check that we have exactly one index variable and at most one end variable. 649 const auto *LoopVar = Nodes.getDeclAs<VarDecl>(IncrementVarName); 650 const auto *CondVar = Nodes.getDeclAs<VarDecl>(ConditionVarName); 651 const auto *InitVar = Nodes.getDeclAs<VarDecl>(InitVarName); 652 if (!areSameVariable(LoopVar, CondVar) || !areSameVariable(LoopVar, InitVar)) 653 return false; 654 const auto *EndVar = Nodes.getDeclAs<VarDecl>(EndVarName); 655 const auto *ConditionEndVar = Nodes.getDeclAs<VarDecl>(ConditionEndVarName); 656 if (EndVar && !areSameVariable(EndVar, ConditionEndVar)) 657 return false; 658 659 // FIXME: Try to put most of this logic inside a matcher. 660 if (FixerKind == LFK_Iterator) { 661 QualType InitVarType = InitVar->getType(); 662 QualType CanonicalInitVarType = InitVarType.getCanonicalType(); 663 664 const auto *BeginCall = Nodes.getNodeAs<CXXMemberCallExpr>(BeginCallName); 665 assert(BeginCall && "Bad Callback. No begin call expression"); 666 QualType CanonicalBeginType = 667 BeginCall->getMethodDecl()->getReturnType().getCanonicalType(); 668 if (CanonicalBeginType->isPointerType() && 669 CanonicalInitVarType->isPointerType()) { 670 // If the initializer and the variable are both pointers check if the 671 // un-qualified pointee types match, otherwise we don't use auto. 672 if (!Context->hasSameUnqualifiedType( 673 CanonicalBeginType->getPointeeType(), 674 CanonicalInitVarType->getPointeeType())) 675 return false; 676 } else if (!Context->hasSameType(CanonicalInitVarType, 677 CanonicalBeginType)) { 678 // Check for qualified types to avoid conversions from non-const to const 679 // iterator types. 680 return false; 681 } 682 } else if (FixerKind == LFK_PseudoArray) { 683 // This call is required to obtain the container. 684 const auto *EndCall = Nodes.getStmtAs<CXXMemberCallExpr>(EndCallName); 685 if (!EndCall || !dyn_cast<MemberExpr>(EndCall->getCallee())) 686 return false; 687 } 688 return true; 689 } 690 691 void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) { 692 const BoundNodes &Nodes = Result.Nodes; 693 Confidence ConfidenceLevel(Confidence::CL_Safe); 694 ASTContext *Context = Result.Context; 695 696 const ForStmt *Loop; 697 LoopFixerKind FixerKind; 698 RangeDescriptor Descriptor; 699 700 if ((Loop = Nodes.getStmtAs<ForStmt>(LoopNameArray))) { 701 FixerKind = LFK_Array; 702 } else if ((Loop = Nodes.getStmtAs<ForStmt>(LoopNameIterator))) { 703 FixerKind = LFK_Iterator; 704 } else { 705 Loop = Nodes.getStmtAs<ForStmt>(LoopNamePseudoArray); 706 assert(Loop && "Bad Callback. No for statement"); 707 FixerKind = LFK_PseudoArray; 708 } 709 710 if (!isConvertible(Context, Nodes, Loop, FixerKind)) 711 return; 712 713 const auto *LoopVar = Nodes.getDeclAs<VarDecl>(IncrementVarName); 714 const auto *EndVar = Nodes.getDeclAs<VarDecl>(EndVarName); 715 716 // If the loop calls end()/size() after each iteration, lower our confidence 717 // level. 718 if (FixerKind != LFK_Array && !EndVar) 719 ConfidenceLevel.lowerTo(Confidence::CL_Reasonable); 720 721 // If the end comparison isn't a variable, we can try to work with the 722 // expression the loop variable is being tested against instead. 723 const auto *EndCall = Nodes.getStmtAs<CXXMemberCallExpr>(EndCallName); 724 const auto *BoundExpr = Nodes.getStmtAs<Expr>(ConditionBoundName); 725 726 // Find container expression of iterators and pseudoarrays, and determine if 727 // this expression needs to be dereferenced to obtain the container. 728 // With array loops, the container is often discovered during the 729 // ForLoopIndexUseVisitor traversal. 730 const Expr *ContainerExpr = nullptr; 731 if (FixerKind == LFK_Iterator) { 732 ContainerExpr = findContainer(Context, LoopVar->getInit(), 733 EndVar ? EndVar->getInit() : EndCall, 734 &Descriptor.ContainerNeedsDereference); 735 } else if (FixerKind == LFK_PseudoArray) { 736 ContainerExpr = EndCall->getImplicitObjectArgument(); 737 Descriptor.ContainerNeedsDereference = 738 dyn_cast<MemberExpr>(EndCall->getCallee())->isArrow(); 739 } 740 741 // We must know the container or an array length bound. 742 if (!ContainerExpr && !BoundExpr) 743 return; 744 745 ForLoopIndexUseVisitor Finder(Context, LoopVar, EndVar, ContainerExpr, 746 BoundExpr, 747 Descriptor.ContainerNeedsDereference); 748 749 // Find expressions and variables on which the container depends. 750 if (ContainerExpr) { 751 ComponentFinderASTVisitor ComponentFinder; 752 ComponentFinder.findExprComponents(ContainerExpr->IgnoreParenImpCasts()); 753 Finder.addComponents(ComponentFinder.getComponents()); 754 } 755 756 // Find usages of the loop index. If they are not used in a convertible way, 757 // stop here. 758 if (!Finder.findAndVerifyUsages(Loop->getBody())) 759 return; 760 ConfidenceLevel.lowerTo(Finder.getConfidenceLevel()); 761 762 // Obtain the container expression, if we don't have it yet. 763 if (FixerKind == LFK_Array) { 764 ContainerExpr = Finder.getContainerIndexed()->IgnoreParenImpCasts(); 765 766 // Very few loops are over expressions that generate arrays rather than 767 // array variables. Consider loops over arrays that aren't just represented 768 // by a variable to be risky conversions. 769 if (!getReferencedVariable(ContainerExpr) && 770 !isDirectMemberExpr(ContainerExpr)) 771 ConfidenceLevel.lowerTo(Confidence::CL_Risky); 772 } 773 774 // Find out which qualifiers we have to use in the loop range. 775 const UsageResult &Usages = Finder.getUsages(); 776 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr, 777 Usages, Descriptor); 778 779 // Ensure that we do not try to move an expression dependent on a local 780 // variable declared inside the loop outside of it. 781 // FIXME: Determine when the external dependency isn't an expression converted 782 // by another loop. 783 TUInfo->getParentFinder().gatherAncestors(Context->getTranslationUnitDecl()); 784 DependencyFinderASTVisitor DependencyFinder( 785 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 786 &TUInfo->getParentFinder().getDeclToParentStmtMap(), 787 &TUInfo->getReplacedVars(), Loop); 788 789 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) || 790 Descriptor.ContainerString.empty() || Usages.empty() || 791 ConfidenceLevel.getLevel() < MinConfidence) 792 return; 793 794 doConversion(Context, LoopVar, getReferencedVariable(ContainerExpr), Usages, 795 Finder.getAliasDecl(), Finder.aliasUseRequired(), 796 Finder.aliasFromForInit(), Loop, Descriptor); 797 } 798 799 } // namespace modernize 800 } // namespace tidy 801 } // namespace clang 802