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