LCOV - code coverage report
Current view: top level - lib/Analysis - LoopInfo.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 245 274 89.4 %
Date: 2018-02-20 16:54:40 Functions: 35 40 87.5 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13