1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===// 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 // This file defines the LoopInfo class that is used to identify natural loops 10 // and determine the loop depth of various nodes of the CFG. Note that the 11 // loops identified may actually be several natural loops that share the same 12 // header node... not just a single natural loop. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/Analysis/LoopInfo.h" 17 #include "llvm/ADT/DepthFirstIterator.h" 18 #include "llvm/ADT/ScopeExit.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/Analysis/IVDescriptors.h" 21 #include "llvm/Analysis/LoopInfoImpl.h" 22 #include "llvm/Analysis/LoopIterator.h" 23 #include "llvm/Analysis/MemorySSA.h" 24 #include "llvm/Analysis/MemorySSAUpdater.h" 25 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 26 #include "llvm/Analysis/ValueTracking.h" 27 #include "llvm/Config/llvm-config.h" 28 #include "llvm/IR/CFG.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/DebugLoc.h" 31 #include "llvm/IR/Dominators.h" 32 #include "llvm/IR/IRPrintingPasses.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/Metadata.h" 36 #include "llvm/IR/PassManager.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops. 44 template class llvm::LoopBase<BasicBlock, Loop>; 45 template class llvm::LoopInfoBase<BasicBlock, Loop>; 46 47 // Always verify loopinfo if expensive checking is enabled. 48 #ifdef EXPENSIVE_CHECKS 49 bool llvm::VerifyLoopInfo = true; 50 #else 51 bool llvm::VerifyLoopInfo = false; 52 #endif 53 static cl::opt<bool, true> 54 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), 55 cl::Hidden, cl::desc("Verify loop info (time consuming)")); 56 57 //===----------------------------------------------------------------------===// 58 // Loop implementation 59 // 60 61 bool Loop::isLoopInvariant(const Value *V) const { 62 if (const Instruction *I = dyn_cast<Instruction>(V)) 63 return !contains(I); 64 return true; // All non-instructions are loop invariant 65 } 66 67 bool Loop::hasLoopInvariantOperands(const Instruction *I) const { 68 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); }); 69 } 70 71 bool Loop::makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt, 72 MemorySSAUpdater *MSSAU) const { 73 if (Instruction *I = dyn_cast<Instruction>(V)) 74 return makeLoopInvariant(I, Changed, InsertPt, MSSAU); 75 return true; // All non-instructions are loop-invariant. 76 } 77 78 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed, 79 Instruction *InsertPt, 80 MemorySSAUpdater *MSSAU) const { 81 // Test if the value is already loop-invariant. 82 if (isLoopInvariant(I)) 83 return true; 84 if (!isSafeToSpeculativelyExecute(I)) 85 return false; 86 if (I->mayReadFromMemory()) 87 return false; 88 // EH block instructions are immobile. 89 if (I->isEHPad()) 90 return false; 91 // Determine the insertion point, unless one was given. 92 if (!InsertPt) { 93 BasicBlock *Preheader = getLoopPreheader(); 94 // Without a preheader, hoisting is not feasible. 95 if (!Preheader) 96 return false; 97 InsertPt = Preheader->getTerminator(); 98 } 99 // Don't hoist instructions with loop-variant operands. 100 for (Value *Operand : I->operands()) 101 if (!makeLoopInvariant(Operand, Changed, InsertPt, MSSAU)) 102 return false; 103 104 // Hoist. 105 I->moveBefore(InsertPt); 106 if (MSSAU) 107 if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(I)) 108 MSSAU->moveToPlace(MUD, InsertPt->getParent(), MemorySSA::End); 109 110 // There is possibility of hoisting this instruction above some arbitrary 111 // condition. Any metadata defined on it can be control dependent on this 112 // condition. Conservatively strip it here so that we don't give any wrong 113 // information to the optimizer. 114 I->dropUnknownNonDebugMetadata(); 115 116 Changed = true; 117 return true; 118 } 119 120 bool Loop::getIncomingAndBackEdge(BasicBlock *&Incoming, 121 BasicBlock *&Backedge) const { 122 BasicBlock *H = getHeader(); 123 124 Incoming = nullptr; 125 Backedge = nullptr; 126 pred_iterator PI = pred_begin(H); 127 assert(PI != pred_end(H) && "Loop must have at least one backedge!"); 128 Backedge = *PI++; 129 if (PI == pred_end(H)) 130 return false; // dead loop 131 Incoming = *PI++; 132 if (PI != pred_end(H)) 133 return false; // multiple backedges? 134 135 if (contains(Incoming)) { 136 if (contains(Backedge)) 137 return false; 138 std::swap(Incoming, Backedge); 139 } else if (!contains(Backedge)) 140 return false; 141 142 assert(Incoming && Backedge && "expected non-null incoming and backedges"); 143 return true; 144 } 145 146 PHINode *Loop::getCanonicalInductionVariable() const { 147 BasicBlock *H = getHeader(); 148 149 BasicBlock *Incoming = nullptr, *Backedge = nullptr; 150 if (!getIncomingAndBackEdge(Incoming, Backedge)) 151 return nullptr; 152 153 // Loop over all of the PHI nodes, looking for a canonical indvar. 154 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) { 155 PHINode *PN = cast<PHINode>(I); 156 if (ConstantInt *CI = 157 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming))) 158 if (CI->isZero()) 159 if (Instruction *Inc = 160 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge))) 161 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN) 162 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1))) 163 if (CI->isOne()) 164 return PN; 165 } 166 return nullptr; 167 } 168 169 /// Get the latch condition instruction. 170 static ICmpInst *getLatchCmpInst(const Loop &L) { 171 if (BasicBlock *Latch = L.getLoopLatch()) 172 if (BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator())) 173 if (BI->isConditional()) 174 return dyn_cast<ICmpInst>(BI->getCondition()); 175 176 return nullptr; 177 } 178 179 /// Return the final value of the loop induction variable if found. 180 static Value *findFinalIVValue(const Loop &L, const PHINode &IndVar, 181 const Instruction &StepInst) { 182 ICmpInst *LatchCmpInst = getLatchCmpInst(L); 183 if (!LatchCmpInst) 184 return nullptr; 185 186 Value *Op0 = LatchCmpInst->getOperand(0); 187 Value *Op1 = LatchCmpInst->getOperand(1); 188 if (Op0 == &IndVar || Op0 == &StepInst) 189 return Op1; 190 191 if (Op1 == &IndVar || Op1 == &StepInst) 192 return Op0; 193 194 return nullptr; 195 } 196 197 Optional<Loop::LoopBounds> Loop::LoopBounds::getBounds(const Loop &L, 198 PHINode &IndVar, 199 ScalarEvolution &SE) { 200 InductionDescriptor IndDesc; 201 if (!InductionDescriptor::isInductionPHI(&IndVar, &L, &SE, IndDesc)) 202 return None; 203 204 Value *InitialIVValue = IndDesc.getStartValue(); 205 Instruction *StepInst = IndDesc.getInductionBinOp(); 206 if (!InitialIVValue || !StepInst) 207 return None; 208 209 const SCEV *Step = IndDesc.getStep(); 210 Value *StepInstOp1 = StepInst->getOperand(1); 211 Value *StepInstOp0 = StepInst->getOperand(0); 212 Value *StepValue = nullptr; 213 if (SE.getSCEV(StepInstOp1) == Step) 214 StepValue = StepInstOp1; 215 else if (SE.getSCEV(StepInstOp0) == Step) 216 StepValue = StepInstOp0; 217 218 Value *FinalIVValue = findFinalIVValue(L, IndVar, *StepInst); 219 if (!FinalIVValue) 220 return None; 221 222 return LoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue, 223 SE); 224 } 225 226 using Direction = Loop::LoopBounds::Direction; 227 228 ICmpInst::Predicate Loop::LoopBounds::getCanonicalPredicate() const { 229 BasicBlock *Latch = L.getLoopLatch(); 230 assert(Latch && "Expecting valid latch"); 231 232 BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator()); 233 assert(BI && BI->isConditional() && "Expecting conditional latch branch"); 234 235 ICmpInst *LatchCmpInst = dyn_cast<ICmpInst>(BI->getCondition()); 236 assert(LatchCmpInst && 237 "Expecting the latch compare instruction to be a CmpInst"); 238 239 // Need to inverse the predicate when first successor is not the loop 240 // header 241 ICmpInst::Predicate Pred = (BI->getSuccessor(0) == L.getHeader()) 242 ? LatchCmpInst->getPredicate() 243 : LatchCmpInst->getInversePredicate(); 244 245 if (LatchCmpInst->getOperand(0) == &getFinalIVValue()) 246 Pred = ICmpInst::getSwappedPredicate(Pred); 247 248 // Need to flip strictness of the predicate when the latch compare instruction 249 // is not using StepInst 250 if (LatchCmpInst->getOperand(0) == &getStepInst() || 251 LatchCmpInst->getOperand(1) == &getStepInst()) 252 return Pred; 253 254 // Cannot flip strictness of NE and EQ 255 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ) 256 return ICmpInst::getFlippedStrictnessPredicate(Pred); 257 258 Direction D = getDirection(); 259 if (D == Direction::Increasing) 260 return ICmpInst::ICMP_SLT; 261 262 if (D == Direction::Decreasing) 263 return ICmpInst::ICMP_SGT; 264 265 // If cannot determine the direction, then unable to find the canonical 266 // predicate 267 return ICmpInst::BAD_ICMP_PREDICATE; 268 } 269 270 Direction Loop::LoopBounds::getDirection() const { 271 if (const SCEVAddRecExpr *StepAddRecExpr = 272 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&getStepInst()))) 273 if (const SCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) { 274 if (SE.isKnownPositive(StepRecur)) 275 return Direction::Increasing; 276 if (SE.isKnownNegative(StepRecur)) 277 return Direction::Decreasing; 278 } 279 280 return Direction::Unknown; 281 } 282 283 Optional<Loop::LoopBounds> Loop::getBounds(ScalarEvolution &SE) const { 284 if (PHINode *IndVar = getInductionVariable(SE)) 285 return LoopBounds::getBounds(*this, *IndVar, SE); 286 287 return None; 288 } 289 290 PHINode *Loop::getInductionVariable(ScalarEvolution &SE) const { 291 if (!isLoopSimplifyForm()) 292 return nullptr; 293 294 BasicBlock *Header = getHeader(); 295 assert(Header && "Expected a valid loop header"); 296 ICmpInst *CmpInst = getLatchCmpInst(*this); 297 if (!CmpInst) 298 return nullptr; 299 300 Instruction *LatchCmpOp0 = dyn_cast<Instruction>(CmpInst->getOperand(0)); 301 Instruction *LatchCmpOp1 = dyn_cast<Instruction>(CmpInst->getOperand(1)); 302 303 for (PHINode &IndVar : Header->phis()) { 304 InductionDescriptor IndDesc; 305 if (!InductionDescriptor::isInductionPHI(&IndVar, this, &SE, IndDesc)) 306 continue; 307 308 Instruction *StepInst = IndDesc.getInductionBinOp(); 309 310 // case 1: 311 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}] 312 // StepInst = IndVar + step 313 // cmp = StepInst < FinalValue 314 if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1) 315 return &IndVar; 316 317 // case 2: 318 // IndVar = phi[{InitialValue, preheader}, {StepInst, latch}] 319 // StepInst = IndVar + step 320 // cmp = IndVar < FinalValue 321 if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1) 322 return &IndVar; 323 } 324 325 return nullptr; 326 } 327 328 bool Loop::getInductionDescriptor(ScalarEvolution &SE, 329 InductionDescriptor &IndDesc) const { 330 if (PHINode *IndVar = getInductionVariable(SE)) 331 return InductionDescriptor::isInductionPHI(IndVar, this, &SE, IndDesc); 332 333 return false; 334 } 335 336 bool Loop::isAuxiliaryInductionVariable(PHINode &AuxIndVar, 337 ScalarEvolution &SE) const { 338 // Located in the loop header 339 BasicBlock *Header = getHeader(); 340 if (AuxIndVar.getParent() != Header) 341 return false; 342 343 // No uses outside of the loop 344 for (User *U : AuxIndVar.users()) 345 if (const Instruction *I = dyn_cast<Instruction>(U)) 346 if (!contains(I)) 347 return false; 348 349 InductionDescriptor IndDesc; 350 if (!InductionDescriptor::isInductionPHI(&AuxIndVar, this, &SE, IndDesc)) 351 return false; 352 353 // The step instruction opcode should be add or sub. 354 if (IndDesc.getInductionOpcode() != Instruction::Add && 355 IndDesc.getInductionOpcode() != Instruction::Sub) 356 return false; 357 358 // Incremented by a loop invariant step for each loop iteration 359 return SE.isLoopInvariant(IndDesc.getStep(), this); 360 } 361 362 BranchInst *Loop::getLoopGuardBranch() const { 363 assert(isLoopSimplifyForm() && "Only valid for loop in simplify form"); 364 BasicBlock *Preheader = getLoopPreheader(); 365 assert(Preheader && getLoopLatch() && 366 "Expecting a loop with valid preheader and latch"); 367 assert(isLoopExiting(getLoopLatch()) && "Only valid for rotated loop"); 368 369 // Disallow loops with more than one unique exit block, as we do not verify 370 // that GuardOtherSucc post dominates all exit blocks. 371 BasicBlock *ExitFromLatch = getUniqueExitBlock(); 372 if (!ExitFromLatch) 373 return nullptr; 374 375 BasicBlock *ExitFromLatchSucc = ExitFromLatch->getUniqueSuccessor(); 376 if (!ExitFromLatchSucc) 377 return nullptr; 378 379 BasicBlock *GuardBB = Preheader->getUniquePredecessor(); 380 if (!GuardBB) 381 return nullptr; 382 383 assert(GuardBB->getTerminator() && "Expecting valid guard terminator"); 384 385 BranchInst *GuardBI = dyn_cast<BranchInst>(GuardBB->getTerminator()); 386 if (!GuardBI || GuardBI->isUnconditional()) 387 return nullptr; 388 389 BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader) 390 ? GuardBI->getSuccessor(1) 391 : GuardBI->getSuccessor(0); 392 return (GuardOtherSucc == ExitFromLatchSucc) ? GuardBI : nullptr; 393 } 394 395 bool Loop::isCanonical(ScalarEvolution &SE) const { 396 InductionDescriptor IndDesc; 397 if (!getInductionDescriptor(SE, IndDesc)) 398 return false; 399 400 ConstantInt *Init = dyn_cast_or_null<ConstantInt>(IndDesc.getStartValue()); 401 if (!Init || !Init->isZero()) 402 return false; 403 404 if (IndDesc.getInductionOpcode() != Instruction::Add) 405 return false; 406 407 ConstantInt *Step = IndDesc.getConstIntStepValue(); 408 if (!Step || !Step->isOne()) 409 return false; 410 411 return true; 412 } 413 414 // Check that 'BB' doesn't have any uses outside of the 'L' 415 static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB, 416 DominatorTree &DT) { 417 for (const Instruction &I : BB) { 418 // Tokens can't be used in PHI nodes and live-out tokens prevent loop 419 // optimizations, so for the purposes of considered LCSSA form, we 420 // can ignore them. 421 if (I.getType()->isTokenTy()) 422 continue; 423 424 for (const Use &U : I.uses()) { 425 const Instruction *UI = cast<Instruction>(U.getUser()); 426 const BasicBlock *UserBB = UI->getParent(); 427 if (const PHINode *P = dyn_cast<PHINode>(UI)) 428 UserBB = P->getIncomingBlock(U); 429 430 // Check the current block, as a fast-path, before checking whether 431 // the use is anywhere in the loop. Most values are used in the same 432 // block they are defined in. Also, blocks not reachable from the 433 // entry are special; uses in them don't need to go through PHIs. 434 if (UserBB != &BB && !L.contains(UserBB) && 435 DT.isReachableFromEntry(UserBB)) 436 return false; 437 } 438 } 439 return true; 440 } 441 442 bool Loop::isLCSSAForm(DominatorTree &DT) const { 443 // For each block we check that it doesn't have any uses outside of this loop. 444 return all_of(this->blocks(), [&](const BasicBlock *BB) { 445 return isBlockInLCSSAForm(*this, *BB, DT); 446 }); 447 } 448 449 bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const { 450 // For each block we check that it doesn't have any uses outside of its 451 // innermost loop. This process will transitively guarantee that the current 452 // loop and all of the nested loops are in LCSSA form. 453 return all_of(this->blocks(), [&](const BasicBlock *BB) { 454 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT); 455 }); 456 } 457 458 bool Loop::isLoopSimplifyForm() const { 459 // Normal-form loops have a preheader, a single backedge, and all of their 460 // exits have all their predecessors inside the loop. 461 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits(); 462 } 463 464 // Routines that reform the loop CFG and split edges often fail on indirectbr. 465 bool Loop::isSafeToClone() const { 466 // Return false if any loop blocks contain indirectbrs, or there are any calls 467 // to noduplicate functions. 468 // FIXME: it should be ok to clone CallBrInst's if we correctly update the 469 // operand list to reflect the newly cloned labels. 470 for (BasicBlock *BB : this->blocks()) { 471 if (isa<IndirectBrInst>(BB->getTerminator()) || 472 isa<CallBrInst>(BB->getTerminator())) 473 return false; 474 475 for (Instruction &I : *BB) 476 if (auto CS = CallSite(&I)) 477 if (CS.cannotDuplicate()) 478 return false; 479 } 480 return true; 481 } 482 483 MDNode *Loop::getLoopID() const { 484 MDNode *LoopID = nullptr; 485 486 // Go through the latch blocks and check the terminator for the metadata. 487 SmallVector<BasicBlock *, 4> LatchesBlocks; 488 getLoopLatches(LatchesBlocks); 489 for (BasicBlock *BB : LatchesBlocks) { 490 Instruction *TI = BB->getTerminator(); 491 MDNode *MD = TI->getMetadata(LLVMContext::MD_loop); 492 493 if (!MD) 494 return nullptr; 495 496 if (!LoopID) 497 LoopID = MD; 498 else if (MD != LoopID) 499 return nullptr; 500 } 501 if (!LoopID || LoopID->getNumOperands() == 0 || 502 LoopID->getOperand(0) != LoopID) 503 return nullptr; 504 return LoopID; 505 } 506 507 void Loop::setLoopID(MDNode *LoopID) const { 508 assert((!LoopID || LoopID->getNumOperands() > 0) && 509 "Loop ID needs at least one operand"); 510 assert((!LoopID || LoopID->getOperand(0) == LoopID) && 511 "Loop ID should refer to itself"); 512 513 SmallVector<BasicBlock *, 4> LoopLatches; 514 getLoopLatches(LoopLatches); 515 for (BasicBlock *BB : LoopLatches) 516 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID); 517 } 518 519 void Loop::setLoopAlreadyUnrolled() { 520 LLVMContext &Context = getHeader()->getContext(); 521 522 MDNode *DisableUnrollMD = 523 MDNode::get(Context, MDString::get(Context, "llvm.loop.unroll.disable")); 524 MDNode *LoopID = getLoopID(); 525 MDNode *NewLoopID = makePostTransformationMetadata( 526 Context, LoopID, {"llvm.loop.unroll."}, {DisableUnrollMD}); 527 setLoopID(NewLoopID); 528 } 529 530 bool Loop::isAnnotatedParallel() const { 531 MDNode *DesiredLoopIdMetadata = getLoopID(); 532 533 if (!DesiredLoopIdMetadata) 534 return false; 535 536 MDNode *ParallelAccesses = 537 findOptionMDForLoop(this, "llvm.loop.parallel_accesses"); 538 SmallPtrSet<MDNode *, 4> 539 ParallelAccessGroups; // For scalable 'contains' check. 540 if (ParallelAccesses) { 541 for (const MDOperand &MD : drop_begin(ParallelAccesses->operands(), 1)) { 542 MDNode *AccGroup = cast<MDNode>(MD.get()); 543 assert(isValidAsAccessGroup(AccGroup) && 544 "List item must be an access group"); 545 ParallelAccessGroups.insert(AccGroup); 546 } 547 } 548 549 // The loop branch contains the parallel loop metadata. In order to ensure 550 // that any parallel-loop-unaware optimization pass hasn't added loop-carried 551 // dependencies (thus converted the loop back to a sequential loop), check 552 // that all the memory instructions in the loop belong to an access group that 553 // is parallel to this loop. 554 for (BasicBlock *BB : this->blocks()) { 555 for (Instruction &I : *BB) { 556 if (!I.mayReadOrWriteMemory()) 557 continue; 558 559 if (MDNode *AccessGroup = I.getMetadata(LLVMContext::MD_access_group)) { 560 auto ContainsAccessGroup = [&ParallelAccessGroups](MDNode *AG) -> bool { 561 if (AG->getNumOperands() == 0) { 562 assert(isValidAsAccessGroup(AG) && "Item must be an access group"); 563 return ParallelAccessGroups.count(AG); 564 } 565 566 for (const MDOperand &AccessListItem : AG->operands()) { 567 MDNode *AccGroup = cast<MDNode>(AccessListItem.get()); 568 assert(isValidAsAccessGroup(AccGroup) && 569 "List item must be an access group"); 570 if (ParallelAccessGroups.count(AccGroup)) 571 return true; 572 } 573 return false; 574 }; 575 576 if (ContainsAccessGroup(AccessGroup)) 577 continue; 578 } 579 580 // The memory instruction can refer to the loop identifier metadata 581 // directly or indirectly through another list metadata (in case of 582 // nested parallel loops). The loop identifier metadata refers to 583 // itself so we can check both cases with the same routine. 584 MDNode *LoopIdMD = 585 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access); 586 587 if (!LoopIdMD) 588 return false; 589 590 bool LoopIdMDFound = false; 591 for (const MDOperand &MDOp : LoopIdMD->operands()) { 592 if (MDOp == DesiredLoopIdMetadata) { 593 LoopIdMDFound = true; 594 break; 595 } 596 } 597 598 if (!LoopIdMDFound) 599 return false; 600 } 601 } 602 return true; 603 } 604 605 DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); } 606 607 Loop::LocRange Loop::getLocRange() const { 608 // If we have a debug location in the loop ID, then use it. 609 if (MDNode *LoopID = getLoopID()) { 610 DebugLoc Start; 611 // We use the first DebugLoc in the header as the start location of the loop 612 // and if there is a second DebugLoc in the header we use it as end location 613 // of the loop. 614 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 615 if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) { 616 if (!Start) 617 Start = DebugLoc(L); 618 else 619 return LocRange(Start, DebugLoc(L)); 620 } 621 } 622 623 if (Start) 624 return LocRange(Start); 625 } 626 627 // Try the pre-header first. 628 if (BasicBlock *PHeadBB = getLoopPreheader()) 629 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc()) 630 return LocRange(DL); 631 632 // If we have no pre-header or there are no instructions with debug 633 // info in it, try the header. 634 if (BasicBlock *HeadBB = getHeader()) 635 return LocRange(HeadBB->getTerminator()->getDebugLoc()); 636 637 return LocRange(); 638 } 639 640 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 641 LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); } 642 643 LLVM_DUMP_METHOD void Loop::dumpVerbose() const { 644 print(dbgs(), /*Depth=*/0, /*Verbose=*/true); 645 } 646 #endif 647 648 //===----------------------------------------------------------------------===// 649 // UnloopUpdater implementation 650 // 651 652 namespace { 653 /// Find the new parent loop for all blocks within the "unloop" whose last 654 /// backedges has just been removed. 655 class UnloopUpdater { 656 Loop &Unloop; 657 LoopInfo *LI; 658 659 LoopBlocksDFS DFS; 660 661 // Map unloop's immediate subloops to their nearest reachable parents. Nested 662 // loops within these subloops will not change parents. However, an immediate 663 // subloop's new parent will be the nearest loop reachable from either its own 664 // exits *or* any of its nested loop's exits. 665 DenseMap<Loop *, Loop *> SubloopParents; 666 667 // Flag the presence of an irreducible backedge whose destination is a block 668 // directly contained by the original unloop. 669 bool FoundIB; 670 671 public: 672 UnloopUpdater(Loop *UL, LoopInfo *LInfo) 673 : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {} 674 675 void updateBlockParents(); 676 677 void removeBlocksFromAncestors(); 678 679 void updateSubloopParents(); 680 681 protected: 682 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop); 683 }; 684 } // end anonymous namespace 685 686 /// Update the parent loop for all blocks that are directly contained within the 687 /// original "unloop". 688 void UnloopUpdater::updateBlockParents() { 689 if (Unloop.getNumBlocks()) { 690 // Perform a post order CFG traversal of all blocks within this loop, 691 // propagating the nearest loop from successors to predecessors. 692 LoopBlocksTraversal Traversal(DFS, LI); 693 for (BasicBlock *POI : Traversal) { 694 695 Loop *L = LI->getLoopFor(POI); 696 Loop *NL = getNearestLoop(POI, L); 697 698 if (NL != L) { 699 // For reducible loops, NL is now an ancestor of Unloop. 700 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) && 701 "uninitialized successor"); 702 LI->changeLoopFor(POI, NL); 703 } else { 704 // Or the current block is part of a subloop, in which case its parent 705 // is unchanged. 706 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor"); 707 } 708 } 709 } 710 // Each irreducible loop within the unloop induces a round of iteration using 711 // the DFS result cached by Traversal. 712 bool Changed = FoundIB; 713 for (unsigned NIters = 0; Changed; ++NIters) { 714 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm"); 715 716 // Iterate over the postorder list of blocks, propagating the nearest loop 717 // from successors to predecessors as before. 718 Changed = false; 719 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(), 720 POE = DFS.endPostorder(); 721 POI != POE; ++POI) { 722 723 Loop *L = LI->getLoopFor(*POI); 724 Loop *NL = getNearestLoop(*POI, L); 725 if (NL != L) { 726 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) && 727 "uninitialized successor"); 728 LI->changeLoopFor(*POI, NL); 729 Changed = true; 730 } 731 } 732 } 733 } 734 735 /// Remove unloop's blocks from all ancestors below their new parents. 736 void UnloopUpdater::removeBlocksFromAncestors() { 737 // Remove all unloop's blocks (including those in nested subloops) from 738 // ancestors below the new parent loop. 739 for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end(); 740 BI != BE; ++BI) { 741 Loop *OuterParent = LI->getLoopFor(*BI); 742 if (Unloop.contains(OuterParent)) { 743 while (OuterParent->getParentLoop() != &Unloop) 744 OuterParent = OuterParent->getParentLoop(); 745 OuterParent = SubloopParents[OuterParent]; 746 } 747 // Remove blocks from former Ancestors except Unloop itself which will be 748 // deleted. 749 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent; 750 OldParent = OldParent->getParentLoop()) { 751 assert(OldParent && "new loop is not an ancestor of the original"); 752 OldParent->removeBlockFromLoop(*BI); 753 } 754 } 755 } 756 757 /// Update the parent loop for all subloops directly nested within unloop. 758 void UnloopUpdater::updateSubloopParents() { 759 while (!Unloop.empty()) { 760 Loop *Subloop = *std::prev(Unloop.end()); 761 Unloop.removeChildLoop(std::prev(Unloop.end())); 762 763 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop"); 764 if (Loop *Parent = SubloopParents[Subloop]) 765 Parent->addChildLoop(Subloop); 766 else 767 LI->addTopLevelLoop(Subloop); 768 } 769 } 770 771 /// Return the nearest parent loop among this block's successors. If a successor 772 /// is a subloop header, consider its parent to be the nearest parent of the 773 /// subloop's exits. 774 /// 775 /// For subloop blocks, simply update SubloopParents and return NULL. 776 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) { 777 778 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and 779 // is considered uninitialized. 780 Loop *NearLoop = BBLoop; 781 782 Loop *Subloop = nullptr; 783 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) { 784 Subloop = NearLoop; 785 // Find the subloop ancestor that is directly contained within Unloop. 786 while (Subloop->getParentLoop() != &Unloop) { 787 Subloop = Subloop->getParentLoop(); 788 assert(Subloop && "subloop is not an ancestor of the original loop"); 789 } 790 // Get the current nearest parent of the Subloop exits, initially Unloop. 791 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second; 792 } 793 794 succ_iterator I = succ_begin(BB), E = succ_end(BB); 795 if (I == E) { 796 assert(!Subloop && "subloop blocks must have a successor"); 797 NearLoop = nullptr; // unloop blocks may now exit the function. 798 } 799 for (; I != E; ++I) { 800 if (*I == BB) 801 continue; // self loops are uninteresting 802 803 Loop *L = LI->getLoopFor(*I); 804 if (L == &Unloop) { 805 // This successor has not been processed. This path must lead to an 806 // irreducible backedge. 807 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB"); 808 FoundIB = true; 809 } 810 if (L != &Unloop && Unloop.contains(L)) { 811 // Successor is in a subloop. 812 if (Subloop) 813 continue; // Branching within subloops. Ignore it. 814 815 // BB branches from the original into a subloop header. 816 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops"); 817 818 // Get the current nearest parent of the Subloop's exits. 819 L = SubloopParents[L]; 820 // L could be Unloop if the only exit was an irreducible backedge. 821 } 822 if (L == &Unloop) { 823 continue; 824 } 825 // Handle critical edges from Unloop into a sibling loop. 826 if (L && !L->contains(&Unloop)) { 827 L = L->getParentLoop(); 828 } 829 // Remember the nearest parent loop among successors or subloop exits. 830 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L)) 831 NearLoop = L; 832 } 833 if (Subloop) { 834 SubloopParents[Subloop] = NearLoop; 835 return BBLoop; 836 } 837 return NearLoop; 838 } 839 840 LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); } 841 842 bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA, 843 FunctionAnalysisManager::Invalidator &) { 844 // Check whether the analysis, all analyses on functions, or the function's 845 // CFG have been preserved. 846 auto PAC = PA.getChecker<LoopAnalysis>(); 847 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() || 848 PAC.preservedSet<CFGAnalyses>()); 849 } 850 851 void LoopInfo::erase(Loop *Unloop) { 852 assert(!Unloop->isInvalid() && "Loop has already been erased!"); 853 854 auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); }); 855 856 // First handle the special case of no parent loop to simplify the algorithm. 857 if (!Unloop->getParentLoop()) { 858 // Since BBLoop had no parent, Unloop blocks are no longer in a loop. 859 for (Loop::block_iterator I = Unloop->block_begin(), 860 E = Unloop->block_end(); 861 I != E; ++I) { 862 863 // Don't reparent blocks in subloops. 864 if (getLoopFor(*I) != Unloop) 865 continue; 866 867 // Blocks no longer have a parent but are still referenced by Unloop until 868 // the Unloop object is deleted. 869 changeLoopFor(*I, nullptr); 870 } 871 872 // Remove the loop from the top-level LoopInfo object. 873 for (iterator I = begin();; ++I) { 874 assert(I != end() && "Couldn't find loop"); 875 if (*I == Unloop) { 876 removeLoop(I); 877 break; 878 } 879 } 880 881 // Move all of the subloops to the top-level. 882 while (!Unloop->empty()) 883 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end()))); 884 885 return; 886 } 887 888 // Update the parent loop for all blocks within the loop. Blocks within 889 // subloops will not change parents. 890 UnloopUpdater Updater(Unloop, this); 891 Updater.updateBlockParents(); 892 893 // Remove blocks from former ancestor loops. 894 Updater.removeBlocksFromAncestors(); 895 896 // Add direct subloops as children in their new parent loop. 897 Updater.updateSubloopParents(); 898 899 // Remove unloop from its parent loop. 900 Loop *ParentLoop = Unloop->getParentLoop(); 901 for (Loop::iterator I = ParentLoop->begin();; ++I) { 902 assert(I != ParentLoop->end() && "Couldn't find loop"); 903 if (*I == Unloop) { 904 ParentLoop->removeChildLoop(I); 905 break; 906 } 907 } 908 } 909 910 AnalysisKey LoopAnalysis::Key; 911 912 LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) { 913 // FIXME: Currently we create a LoopInfo from scratch for every function. 914 // This may prove to be too wasteful due to deallocating and re-allocating 915 // memory each time for the underlying map and vector datastructures. At some 916 // point it may prove worthwhile to use a freelist and recycle LoopInfo 917 // objects. I don't want to add that kind of complexity until the scope of 918 // the problem is better understood. 919 LoopInfo LI; 920 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F)); 921 return LI; 922 } 923 924 PreservedAnalyses LoopPrinterPass::run(Function &F, 925 FunctionAnalysisManager &AM) { 926 AM.getResult<LoopAnalysis>(F).print(OS); 927 return PreservedAnalyses::all(); 928 } 929 930 void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) { 931 932 if (forcePrintModuleIR()) { 933 // handling -print-module-scope 934 OS << Banner << " (loop: "; 935 L.getHeader()->printAsOperand(OS, false); 936 OS << ")\n"; 937 938 // printing whole module 939 OS << *L.getHeader()->getModule(); 940 return; 941 } 942 943 OS << Banner; 944 945 auto *PreHeader = L.getLoopPreheader(); 946 if (PreHeader) { 947 OS << "\n; Preheader:"; 948 PreHeader->print(OS); 949 OS << "\n; Loop:"; 950 } 951 952 for (auto *Block : L.blocks()) 953 if (Block) 954 Block->print(OS); 955 else 956 OS << "Printing <null> block"; 957 958 SmallVector<BasicBlock *, 8> ExitBlocks; 959 L.getExitBlocks(ExitBlocks); 960 if (!ExitBlocks.empty()) { 961 OS << "\n; Exit blocks"; 962 for (auto *Block : ExitBlocks) 963 if (Block) 964 Block->print(OS); 965 else 966 OS << "Printing <null> block"; 967 } 968 } 969 970 MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) { 971 // No loop metadata node, no loop properties. 972 if (!LoopID) 973 return nullptr; 974 975 // First operand should refer to the metadata node itself, for legacy reasons. 976 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 977 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 978 979 // Iterate over the metdata node operands and look for MDString metadata. 980 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 981 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 982 if (!MD || MD->getNumOperands() < 1) 983 continue; 984 MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 985 if (!S) 986 continue; 987 // Return the operand node if MDString holds expected metadata. 988 if (Name.equals(S->getString())) 989 return MD; 990 } 991 992 // Loop property not found. 993 return nullptr; 994 } 995 996 MDNode *llvm::findOptionMDForLoop(const Loop *TheLoop, StringRef Name) { 997 return findOptionMDForLoopID(TheLoop->getLoopID(), Name); 998 } 999 1000 bool llvm::isValidAsAccessGroup(MDNode *Node) { 1001 return Node->getNumOperands() == 0 && Node->isDistinct(); 1002 } 1003 1004 MDNode *llvm::makePostTransformationMetadata(LLVMContext &Context, 1005 MDNode *OrigLoopID, 1006 ArrayRef<StringRef> RemovePrefixes, 1007 ArrayRef<MDNode *> AddAttrs) { 1008 // First remove any existing loop metadata related to this transformation. 1009 SmallVector<Metadata *, 4> MDs; 1010 1011 // Reserve first location for self reference to the LoopID metadata node. 1012 TempMDTuple TempNode = MDNode::getTemporary(Context, None); 1013 MDs.push_back(TempNode.get()); 1014 1015 // Remove metadata for the transformation that has been applied or that became 1016 // outdated. 1017 if (OrigLoopID) { 1018 for (unsigned i = 1, ie = OrigLoopID->getNumOperands(); i < ie; ++i) { 1019 bool IsVectorMetadata = false; 1020 Metadata *Op = OrigLoopID->getOperand(i); 1021 if (MDNode *MD = dyn_cast<MDNode>(Op)) { 1022 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 1023 if (S) 1024 IsVectorMetadata = 1025 llvm::any_of(RemovePrefixes, [S](StringRef Prefix) -> bool { 1026 return S->getString().startswith(Prefix); 1027 }); 1028 } 1029 if (!IsVectorMetadata) 1030 MDs.push_back(Op); 1031 } 1032 } 1033 1034 // Add metadata to avoid reapplying a transformation, such as 1035 // llvm.loop.unroll.disable and llvm.loop.isvectorized. 1036 MDs.append(AddAttrs.begin(), AddAttrs.end()); 1037 1038 MDNode *NewLoopID = MDNode::getDistinct(Context, MDs); 1039 // Replace the temporary node with a self-reference. 1040 NewLoopID->replaceOperandWith(0, NewLoopID); 1041 return NewLoopID; 1042 } 1043 1044 //===----------------------------------------------------------------------===// 1045 // LoopInfo implementation 1046 // 1047 1048 char LoopInfoWrapperPass::ID = 0; 1049 INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information", 1050 true, true) 1051 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1052 INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information", 1053 true, true) 1054 1055 bool LoopInfoWrapperPass::runOnFunction(Function &) { 1056 releaseMemory(); 1057 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree()); 1058 return false; 1059 } 1060 1061 void LoopInfoWrapperPass::verifyAnalysis() const { 1062 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the 1063 // function each time verifyAnalysis is called is very expensive. The 1064 // -verify-loop-info option can enable this. In order to perform some 1065 // checking by default, LoopPass has been taught to call verifyLoop manually 1066 // during loop pass sequences. 1067 if (VerifyLoopInfo) { 1068 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1069 LI.verify(DT); 1070 } 1071 } 1072 1073 void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1074 AU.setPreservesAll(); 1075 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 1076 } 1077 1078 void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const { 1079 LI.print(OS); 1080 } 1081 1082 PreservedAnalyses LoopVerifierPass::run(Function &F, 1083 FunctionAnalysisManager &AM) { 1084 LoopInfo &LI = AM.getResult<LoopAnalysis>(F); 1085 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1086 LI.verify(DT); 1087 return PreservedAnalyses::all(); 1088 } 1089 1090 //===----------------------------------------------------------------------===// 1091 // LoopBlocksDFS implementation 1092 // 1093 1094 /// Traverse the loop blocks and store the DFS result. 1095 /// Useful for clients that just want the final DFS result and don't need to 1096 /// visit blocks during the initial traversal. 1097 void LoopBlocksDFS::perform(LoopInfo *LI) { 1098 LoopBlocksTraversal Traversal(*this, LI); 1099 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(), 1100 POE = Traversal.end(); 1101 POI != POE; ++POI) 1102 ; 1103 } 1104