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