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