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