1 //===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the LoopInfo class that is used to identify natural loops 11 // and determine the loop depth of various nodes of the CFG. Note that the 12 // loops identified may actually be several natural loops that share the same 13 // header node... not just a single natural loop. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Analysis/LoopInfo.h" 18 #include "llvm/ADT/DepthFirstIterator.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/Analysis/LoopInfoImpl.h" 21 #include "llvm/Analysis/LoopIterator.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/CFG.h" 24 #include "llvm/IR/Constants.h" 25 #include "llvm/IR/Dominators.h" 26 #include "llvm/IR/Instructions.h" 27 #include "llvm/IR/LLVMContext.h" 28 #include "llvm/IR/Metadata.h" 29 #include "llvm/IR/PassManager.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <algorithm> 34 using namespace llvm; 35 36 // Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops. 37 template class llvm::LoopBase<BasicBlock, Loop>; 38 template class llvm::LoopInfoBase<BasicBlock, Loop>; 39 40 // Always verify loopinfo if expensive checking is enabled. 41 #ifdef EXPENSIVE_CHECKS 42 static bool VerifyLoopInfo = true; 43 #else 44 static bool VerifyLoopInfo = false; 45 #endif 46 static cl::opt<bool,true> 47 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), 48 cl::desc("Verify loop info (time consuming)")); 49 50 //===----------------------------------------------------------------------===// 51 // Loop implementation 52 // 53 54 bool Loop::isLoopInvariant(const Value *V) const { 55 if (const Instruction *I = dyn_cast<Instruction>(V)) 56 return !contains(I); 57 return true; // All non-instructions are loop invariant 58 } 59 60 bool Loop::hasLoopInvariantOperands(const Instruction *I) const { 61 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); }); 62 } 63 64 bool Loop::makeLoopInvariant(Value *V, bool &Changed, 65 Instruction *InsertPt) const { 66 if (Instruction *I = dyn_cast<Instruction>(V)) 67 return makeLoopInvariant(I, Changed, InsertPt); 68 return true; // All non-instructions are loop-invariant. 69 } 70 71 bool Loop::makeLoopInvariant(Instruction *I, bool &Changed, 72 Instruction *InsertPt) const { 73 // Test if the value is already loop-invariant. 74 if (isLoopInvariant(I)) 75 return true; 76 if (!isSafeToSpeculativelyExecute(I)) 77 return false; 78 if (I->mayReadFromMemory()) 79 return false; 80 // EH block instructions are immobile. 81 if (I->isEHPad()) 82 return false; 83 // Determine the insertion point, unless one was given. 84 if (!InsertPt) { 85 BasicBlock *Preheader = getLoopPreheader(); 86 // Without a preheader, hoisting is not feasible. 87 if (!Preheader) 88 return false; 89 InsertPt = Preheader->getTerminator(); 90 } 91 // Don't hoist instructions with loop-variant operands. 92 for (Value *Operand : I->operands()) 93 if (!makeLoopInvariant(Operand, Changed, InsertPt)) 94 return false; 95 96 // Hoist. 97 I->moveBefore(InsertPt); 98 99 // There is possibility of hoisting this instruction above some arbitrary 100 // condition. Any metadata defined on it can be control dependent on this 101 // condition. Conservatively strip it here so that we don't give any wrong 102 // information to the optimizer. 103 I->dropUnknownNonDebugMetadata(); 104 105 Changed = true; 106 return true; 107 } 108 109 PHINode *Loop::getCanonicalInductionVariable() const { 110 BasicBlock *H = getHeader(); 111 112 BasicBlock *Incoming = nullptr, *Backedge = nullptr; 113 pred_iterator PI = pred_begin(H); 114 assert(PI != pred_end(H) && 115 "Loop must have at least one backedge!"); 116 Backedge = *PI++; 117 if (PI == pred_end(H)) return nullptr; // dead loop 118 Incoming = *PI++; 119 if (PI != pred_end(H)) return nullptr; // multiple backedges? 120 121 if (contains(Incoming)) { 122 if (contains(Backedge)) 123 return nullptr; 124 std::swap(Incoming, Backedge); 125 } else if (!contains(Backedge)) 126 return nullptr; 127 128 // Loop over all of the PHI nodes, looking for a canonical indvar. 129 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) { 130 PHINode *PN = cast<PHINode>(I); 131 if (ConstantInt *CI = 132 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming))) 133 if (CI->isNullValue()) 134 if (Instruction *Inc = 135 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge))) 136 if (Inc->getOpcode() == Instruction::Add && 137 Inc->getOperand(0) == PN) 138 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1))) 139 if (CI->equalsInt(1)) 140 return PN; 141 } 142 return nullptr; 143 } 144 145 bool Loop::isLCSSAForm(DominatorTree &DT) const { 146 for (BasicBlock *BB : this->blocks()) { 147 for (Instruction &I : *BB) { 148 // Tokens can't be used in PHI nodes and live-out tokens prevent loop 149 // optimizations, so for the purposes of considered LCSSA form, we 150 // can ignore them. 151 if (I.getType()->isTokenTy()) 152 continue; 153 154 for (Use &U : I.uses()) { 155 Instruction *UI = cast<Instruction>(U.getUser()); 156 BasicBlock *UserBB = UI->getParent(); 157 if (PHINode *P = dyn_cast<PHINode>(UI)) 158 UserBB = P->getIncomingBlock(U); 159 160 // Check the current block, as a fast-path, before checking whether 161 // the use is anywhere in the loop. Most values are used in the same 162 // block they are defined in. Also, blocks not reachable from the 163 // entry are special; uses in them don't need to go through PHIs. 164 if (UserBB != BB && 165 !contains(UserBB) && 166 DT.isReachableFromEntry(UserBB)) 167 return false; 168 } 169 } 170 } 171 172 return true; 173 } 174 175 bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT) const { 176 if (!isLCSSAForm(DT)) 177 return false; 178 179 return std::all_of(begin(), end(), [&](const Loop *L) { 180 return L->isRecursivelyLCSSAForm(DT); 181 }); 182 } 183 184 bool Loop::isLoopSimplifyForm() const { 185 // Normal-form loops have a preheader, a single backedge, and all of their 186 // exits have all their predecessors inside the loop. 187 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits(); 188 } 189 190 // Routines that reform the loop CFG and split edges often fail on indirectbr. 191 bool Loop::isSafeToClone() const { 192 // Return false if any loop blocks contain indirectbrs, or there are any calls 193 // to noduplicate functions. 194 for (BasicBlock *BB : this->blocks()) { 195 if (isa<IndirectBrInst>(BB->getTerminator())) 196 return false; 197 198 for (Instruction &I : *BB) 199 if (auto CS = CallSite(&I)) 200 if (CS.cannotDuplicate()) 201 return false; 202 } 203 return true; 204 } 205 206 MDNode *Loop::getLoopID() const { 207 MDNode *LoopID = nullptr; 208 if (isLoopSimplifyForm()) { 209 LoopID = getLoopLatch()->getTerminator()->getMetadata(LLVMContext::MD_loop); 210 } else { 211 // Go through each predecessor of the loop header and check the 212 // terminator for the metadata. 213 BasicBlock *H = getHeader(); 214 for (BasicBlock *BB : this->blocks()) { 215 TerminatorInst *TI = BB->getTerminator(); 216 MDNode *MD = nullptr; 217 218 // Check if this terminator branches to the loop header. 219 for (BasicBlock *Successor : TI->successors()) { 220 if (Successor == H) { 221 MD = TI->getMetadata(LLVMContext::MD_loop); 222 break; 223 } 224 } 225 if (!MD) 226 return nullptr; 227 228 if (!LoopID) 229 LoopID = MD; 230 else if (MD != LoopID) 231 return nullptr; 232 } 233 } 234 if (!LoopID || LoopID->getNumOperands() == 0 || 235 LoopID->getOperand(0) != LoopID) 236 return nullptr; 237 return LoopID; 238 } 239 240 void Loop::setLoopID(MDNode *LoopID) const { 241 assert(LoopID && "Loop ID should not be null"); 242 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand"); 243 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself"); 244 245 if (isLoopSimplifyForm()) { 246 getLoopLatch()->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID); 247 return; 248 } 249 250 BasicBlock *H = getHeader(); 251 for (BasicBlock *BB : this->blocks()) { 252 TerminatorInst *TI = BB->getTerminator(); 253 for (BasicBlock *Successor : TI->successors()) { 254 if (Successor == H) 255 TI->setMetadata(LLVMContext::MD_loop, LoopID); 256 } 257 } 258 } 259 260 bool Loop::isAnnotatedParallel() const { 261 MDNode *DesiredLoopIdMetadata = getLoopID(); 262 263 if (!DesiredLoopIdMetadata) 264 return false; 265 266 // The loop branch contains the parallel loop metadata. In order to ensure 267 // that any parallel-loop-unaware optimization pass hasn't added loop-carried 268 // dependencies (thus converted the loop back to a sequential loop), check 269 // that all the memory instructions in the loop contain parallelism metadata 270 // that point to the same unique "loop id metadata" the loop branch does. 271 for (BasicBlock *BB : this->blocks()) { 272 for (Instruction &I : *BB) { 273 if (!I.mayReadOrWriteMemory()) 274 continue; 275 276 // The memory instruction can refer to the loop identifier metadata 277 // directly or indirectly through another list metadata (in case of 278 // nested parallel loops). The loop identifier metadata refers to 279 // itself so we can check both cases with the same routine. 280 MDNode *LoopIdMD = 281 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access); 282 283 if (!LoopIdMD) 284 return false; 285 286 bool LoopIdMDFound = false; 287 for (const MDOperand &MDOp : LoopIdMD->operands()) { 288 if (MDOp == DesiredLoopIdMetadata) { 289 LoopIdMDFound = true; 290 break; 291 } 292 } 293 294 if (!LoopIdMDFound) 295 return false; 296 } 297 } 298 return true; 299 } 300 301 bool Loop::hasDedicatedExits() const { 302 // Each predecessor of each exit block of a normal loop is contained 303 // within the loop. 304 SmallVector<BasicBlock *, 4> ExitBlocks; 305 getExitBlocks(ExitBlocks); 306 for (BasicBlock *BB : ExitBlocks) 307 for (BasicBlock *Predecessor : predecessors(BB)) 308 if (!contains(Predecessor)) 309 return false; 310 // All the requirements are met. 311 return true; 312 } 313 314 void 315 Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const { 316 assert(hasDedicatedExits() && 317 "getUniqueExitBlocks assumes the loop has canonical form exits!"); 318 319 SmallVector<BasicBlock *, 32> SwitchExitBlocks; 320 for (BasicBlock *BB : this->blocks()) { 321 SwitchExitBlocks.clear(); 322 for (BasicBlock *Successor : successors(BB)) { 323 // If block is inside the loop then it is not an exit block. 324 if (contains(Successor)) 325 continue; 326 327 pred_iterator PI = pred_begin(Successor); 328 BasicBlock *FirstPred = *PI; 329 330 // If current basic block is this exit block's first predecessor 331 // then only insert exit block in to the output ExitBlocks vector. 332 // This ensures that same exit block is not inserted twice into 333 // ExitBlocks vector. 334 if (BB != FirstPred) 335 continue; 336 337 // If a terminator has more then two successors, for example SwitchInst, 338 // then it is possible that there are multiple edges from current block 339 // to one exit block. 340 if (std::distance(succ_begin(BB), succ_end(BB)) <= 2) { 341 ExitBlocks.push_back(Successor); 342 continue; 343 } 344 345 // In case of multiple edges from current block to exit block, collect 346 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of 347 // duplicate edges. 348 if (std::find(SwitchExitBlocks.begin(), SwitchExitBlocks.end(), Successor) 349 == SwitchExitBlocks.end()) { 350 SwitchExitBlocks.push_back(Successor); 351 ExitBlocks.push_back(Successor); 352 } 353 } 354 } 355 } 356 357 BasicBlock *Loop::getUniqueExitBlock() const { 358 SmallVector<BasicBlock *, 8> UniqueExitBlocks; 359 getUniqueExitBlocks(UniqueExitBlocks); 360 if (UniqueExitBlocks.size() == 1) 361 return UniqueExitBlocks[0]; 362 return nullptr; 363 } 364 365 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 366 LLVM_DUMP_METHOD void Loop::dump() const { 367 print(dbgs()); 368 } 369 #endif 370 371 //===----------------------------------------------------------------------===// 372 // UnloopUpdater implementation 373 // 374 375 namespace { 376 /// Find the new parent loop for all blocks within the "unloop" whose last 377 /// backedges has just been removed. 378 class UnloopUpdater { 379 Loop *Unloop; 380 LoopInfo *LI; 381 382 LoopBlocksDFS DFS; 383 384 // Map unloop's immediate subloops to their nearest reachable parents. Nested 385 // loops within these subloops will not change parents. However, an immediate 386 // subloop's new parent will be the nearest loop reachable from either its own 387 // exits *or* any of its nested loop's exits. 388 DenseMap<Loop*, Loop*> SubloopParents; 389 390 // Flag the presence of an irreducible backedge whose destination is a block 391 // directly contained by the original unloop. 392 bool FoundIB; 393 394 public: 395 UnloopUpdater(Loop *UL, LoopInfo *LInfo) : 396 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {} 397 398 void updateBlockParents(); 399 400 void removeBlocksFromAncestors(); 401 402 void updateSubloopParents(); 403 404 protected: 405 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop); 406 }; 407 } // end anonymous namespace 408 409 /// Update the parent loop for all blocks that are directly contained within the 410 /// original "unloop". 411 void UnloopUpdater::updateBlockParents() { 412 if (Unloop->getNumBlocks()) { 413 // Perform a post order CFG traversal of all blocks within this loop, 414 // propagating the nearest loop from sucessors to predecessors. 415 LoopBlocksTraversal Traversal(DFS, LI); 416 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(), 417 POE = Traversal.end(); POI != POE; ++POI) { 418 419 Loop *L = LI->getLoopFor(*POI); 420 Loop *NL = getNearestLoop(*POI, L); 421 422 if (NL != L) { 423 // For reducible loops, NL is now an ancestor of Unloop. 424 assert((NL != Unloop && (!NL || NL->contains(Unloop))) && 425 "uninitialized successor"); 426 LI->changeLoopFor(*POI, NL); 427 } 428 else { 429 // Or the current block is part of a subloop, in which case its parent 430 // is unchanged. 431 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor"); 432 } 433 } 434 } 435 // Each irreducible loop within the unloop induces a round of iteration using 436 // the DFS result cached by Traversal. 437 bool Changed = FoundIB; 438 for (unsigned NIters = 0; Changed; ++NIters) { 439 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm"); 440 441 // Iterate over the postorder list of blocks, propagating the nearest loop 442 // from successors to predecessors as before. 443 Changed = false; 444 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(), 445 POE = DFS.endPostorder(); POI != POE; ++POI) { 446 447 Loop *L = LI->getLoopFor(*POI); 448 Loop *NL = getNearestLoop(*POI, L); 449 if (NL != L) { 450 assert(NL != Unloop && (!NL || NL->contains(Unloop)) && 451 "uninitialized successor"); 452 LI->changeLoopFor(*POI, NL); 453 Changed = true; 454 } 455 } 456 } 457 } 458 459 /// Remove unloop's blocks from all ancestors below their new parents. 460 void UnloopUpdater::removeBlocksFromAncestors() { 461 // Remove all unloop's blocks (including those in nested subloops) from 462 // ancestors below the new parent loop. 463 for (Loop::block_iterator BI = Unloop->block_begin(), 464 BE = Unloop->block_end(); BI != BE; ++BI) { 465 Loop *OuterParent = LI->getLoopFor(*BI); 466 if (Unloop->contains(OuterParent)) { 467 while (OuterParent->getParentLoop() != Unloop) 468 OuterParent = OuterParent->getParentLoop(); 469 OuterParent = SubloopParents[OuterParent]; 470 } 471 // Remove blocks from former Ancestors except Unloop itself which will be 472 // deleted. 473 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent; 474 OldParent = OldParent->getParentLoop()) { 475 assert(OldParent && "new loop is not an ancestor of the original"); 476 OldParent->removeBlockFromLoop(*BI); 477 } 478 } 479 } 480 481 /// Update the parent loop for all subloops directly nested within unloop. 482 void UnloopUpdater::updateSubloopParents() { 483 while (!Unloop->empty()) { 484 Loop *Subloop = *std::prev(Unloop->end()); 485 Unloop->removeChildLoop(std::prev(Unloop->end())); 486 487 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop"); 488 if (Loop *Parent = SubloopParents[Subloop]) 489 Parent->addChildLoop(Subloop); 490 else 491 LI->addTopLevelLoop(Subloop); 492 } 493 } 494 495 /// Return the nearest parent loop among this block's successors. If a successor 496 /// is a subloop header, consider its parent to be the nearest parent of the 497 /// subloop's exits. 498 /// 499 /// For subloop blocks, simply update SubloopParents and return NULL. 500 Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) { 501 502 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and 503 // is considered uninitialized. 504 Loop *NearLoop = BBLoop; 505 506 Loop *Subloop = nullptr; 507 if (NearLoop != Unloop && Unloop->contains(NearLoop)) { 508 Subloop = NearLoop; 509 // Find the subloop ancestor that is directly contained within Unloop. 510 while (Subloop->getParentLoop() != Unloop) { 511 Subloop = Subloop->getParentLoop(); 512 assert(Subloop && "subloop is not an ancestor of the original loop"); 513 } 514 // Get the current nearest parent of the Subloop exits, initially Unloop. 515 NearLoop = 516 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second; 517 } 518 519 succ_iterator I = succ_begin(BB), E = succ_end(BB); 520 if (I == E) { 521 assert(!Subloop && "subloop blocks must have a successor"); 522 NearLoop = nullptr; // unloop blocks may now exit the function. 523 } 524 for (; I != E; ++I) { 525 if (*I == BB) 526 continue; // self loops are uninteresting 527 528 Loop *L = LI->getLoopFor(*I); 529 if (L == Unloop) { 530 // This successor has not been processed. This path must lead to an 531 // irreducible backedge. 532 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB"); 533 FoundIB = true; 534 } 535 if (L != Unloop && Unloop->contains(L)) { 536 // Successor is in a subloop. 537 if (Subloop) 538 continue; // Branching within subloops. Ignore it. 539 540 // BB branches from the original into a subloop header. 541 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops"); 542 543 // Get the current nearest parent of the Subloop's exits. 544 L = SubloopParents[L]; 545 // L could be Unloop if the only exit was an irreducible backedge. 546 } 547 if (L == Unloop) { 548 continue; 549 } 550 // Handle critical edges from Unloop into a sibling loop. 551 if (L && !L->contains(Unloop)) { 552 L = L->getParentLoop(); 553 } 554 // Remember the nearest parent loop among successors or subloop exits. 555 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L)) 556 NearLoop = L; 557 } 558 if (Subloop) { 559 SubloopParents[Subloop] = NearLoop; 560 return BBLoop; 561 } 562 return NearLoop; 563 } 564 565 LoopInfo::LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree) { 566 analyze(DomTree); 567 } 568 569 void LoopInfo::markAsRemoved(Loop *Unloop) { 570 assert(!Unloop->isInvalid() && "Loop has already been removed"); 571 Unloop->invalidate(); 572 RemovedLoops.push_back(Unloop); 573 574 // First handle the special case of no parent loop to simplify the algorithm. 575 if (!Unloop->getParentLoop()) { 576 // Since BBLoop had no parent, Unloop blocks are no longer in a loop. 577 for (Loop::block_iterator I = Unloop->block_begin(), 578 E = Unloop->block_end(); 579 I != E; ++I) { 580 581 // Don't reparent blocks in subloops. 582 if (getLoopFor(*I) != Unloop) 583 continue; 584 585 // Blocks no longer have a parent but are still referenced by Unloop until 586 // the Unloop object is deleted. 587 changeLoopFor(*I, nullptr); 588 } 589 590 // Remove the loop from the top-level LoopInfo object. 591 for (iterator I = begin();; ++I) { 592 assert(I != end() && "Couldn't find loop"); 593 if (*I == Unloop) { 594 removeLoop(I); 595 break; 596 } 597 } 598 599 // Move all of the subloops to the top-level. 600 while (!Unloop->empty()) 601 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end()))); 602 603 return; 604 } 605 606 // Update the parent loop for all blocks within the loop. Blocks within 607 // subloops will not change parents. 608 UnloopUpdater Updater(Unloop, this); 609 Updater.updateBlockParents(); 610 611 // Remove blocks from former ancestor loops. 612 Updater.removeBlocksFromAncestors(); 613 614 // Add direct subloops as children in their new parent loop. 615 Updater.updateSubloopParents(); 616 617 // Remove unloop from its parent loop. 618 Loop *ParentLoop = Unloop->getParentLoop(); 619 for (Loop::iterator I = ParentLoop->begin();; ++I) { 620 assert(I != ParentLoop->end() && "Couldn't find loop"); 621 if (*I == Unloop) { 622 ParentLoop->removeChildLoop(I); 623 break; 624 } 625 } 626 } 627 628 char LoopAnalysis::PassID; 629 630 LoopInfo LoopAnalysis::run(Function &F, AnalysisManager<Function> &AM) { 631 // FIXME: Currently we create a LoopInfo from scratch for every function. 632 // This may prove to be too wasteful due to deallocating and re-allocating 633 // memory each time for the underlying map and vector datastructures. At some 634 // point it may prove worthwhile to use a freelist and recycle LoopInfo 635 // objects. I don't want to add that kind of complexity until the scope of 636 // the problem is better understood. 637 LoopInfo LI; 638 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F)); 639 return LI; 640 } 641 642 PreservedAnalyses LoopPrinterPass::run(Function &F, 643 AnalysisManager<Function> &AM) { 644 AM.getResult<LoopAnalysis>(F).print(OS); 645 return PreservedAnalyses::all(); 646 } 647 648 PrintLoopPass::PrintLoopPass() : OS(dbgs()) {} 649 PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner) 650 : OS(OS), Banner(Banner) {} 651 652 PreservedAnalyses PrintLoopPass::run(Loop &L) { 653 OS << Banner; 654 for (auto *Block : L.blocks()) 655 if (Block) 656 Block->print(OS); 657 else 658 OS << "Printing <null> block"; 659 return PreservedAnalyses::all(); 660 } 661 662 //===----------------------------------------------------------------------===// 663 // LoopInfo implementation 664 // 665 666 char LoopInfoWrapperPass::ID = 0; 667 INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information", 668 true, true) 669 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 670 INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information", 671 true, true) 672 673 bool LoopInfoWrapperPass::runOnFunction(Function &) { 674 releaseMemory(); 675 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree()); 676 return false; 677 } 678 679 void LoopInfoWrapperPass::verifyAnalysis() const { 680 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the 681 // function each time verifyAnalysis is called is very expensive. The 682 // -verify-loop-info option can enable this. In order to perform some 683 // checking by default, LoopPass has been taught to call verifyLoop manually 684 // during loop pass sequences. 685 if (VerifyLoopInfo) 686 LI.verify(); 687 } 688 689 void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 690 AU.setPreservesAll(); 691 AU.addRequired<DominatorTreeWrapperPass>(); 692 } 693 694 void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const { 695 LI.print(OS); 696 } 697 698 //===----------------------------------------------------------------------===// 699 // LoopBlocksDFS implementation 700 // 701 702 /// Traverse the loop blocks and store the DFS result. 703 /// Useful for clients that just want the final DFS result and don't need to 704 /// visit blocks during the initial traversal. 705 void LoopBlocksDFS::perform(LoopInfo *LI) { 706 LoopBlocksTraversal Traversal(*this, LI); 707 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(), 708 POE = Traversal.end(); POI != POE; ++POI) ; 709 } 710