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