LLVM API Documentation

LoopInfo.h

Go to the documentation of this file.
00001 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the LoopInfo class that is used to identify natural loops
00011 // and determine the loop depth of various nodes of the CFG.  Note that natural
00012 // loops may actually be several loops that share the same header node.
00013 //
00014 // This analysis calculates the nesting structure of loops in a function.  For
00015 // each natural loop identified, this analysis identifies natural loops
00016 // contained entirely within the loop and the basic blocks the make up the loop.
00017 //
00018 // It can calculate on the fly various bits of information, for example:
00019 //
00020 //  * whether there is a preheader for the loop
00021 //  * the number of back edges to the header
00022 //  * whether or not a particular block branches out of the loop
00023 //  * the successor blocks of the loop
00024 //  * the loop depth
00025 //  * the trip count
00026 //  * etc...
00027 //
00028 //===----------------------------------------------------------------------===//
00029 
00030 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
00031 #define LLVM_ANALYSIS_LOOP_INFO_H
00032 
00033 #include "llvm/Pass.h"
00034 #include "llvm/Constants.h"
00035 #include "llvm/Instructions.h"
00036 #include "llvm/ADT/DepthFirstIterator.h"
00037 #include "llvm/ADT/GraphTraits.h"
00038 #include "llvm/ADT/SmallPtrSet.h"
00039 #include "llvm/ADT/SmallVector.h"
00040 #include "llvm/Analysis/Dominators.h"
00041 #include "llvm/Support/CFG.h"
00042 #include "llvm/Support/Streams.h"
00043 #include <algorithm>
00044 #include <ostream>
00045 
00046 namespace llvm {
00047 
00048 template<typename T>
00049 static void RemoveFromVector(std::vector<T*> &V, T *N) {
00050   typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
00051   assert(I != V.end() && "N is not in this list!");
00052   V.erase(I);
00053 }
00054 
00055 class DominatorTree;
00056 class LoopInfo;
00057 template<class N> class LoopInfoBase;
00058 template<class N> class LoopBase;
00059 
00060 typedef LoopBase<BasicBlock> Loop;
00061 
00062 //===----------------------------------------------------------------------===//
00063 /// LoopBase class - Instances of this class are used to represent loops that
00064 /// are detected in the flow graph
00065 ///
00066 template<class BlockT>
00067 class LoopBase {
00068   LoopBase<BlockT> *ParentLoop;
00069   // SubLoops - Loops contained entirely within this one.
00070   std::vector<LoopBase<BlockT>*> SubLoops;
00071 
00072   // Blocks - The list of blocks in this loop.  First entry is the header node.
00073   std::vector<BlockT*> Blocks;
00074 
00075   LoopBase(const LoopBase<BlockT> &);                  // DO NOT IMPLEMENT
00076   const LoopBase<BlockT>&operator=(const LoopBase<BlockT> &);// DO NOT IMPLEMENT
00077 public:
00078   /// Loop ctor - This creates an empty loop.
00079   LoopBase() : ParentLoop(0) {}
00080   ~LoopBase() {
00081     for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
00082       delete SubLoops[i];
00083   }
00084 
00085   /// getLoopDepth - Return the nesting level of this loop.  An outer-most
00086   /// loop has depth 1, for consistency with loop depth values used for basic
00087   /// blocks, where depth 0 is used for blocks not inside any loops.
00088   unsigned getLoopDepth() const {
00089     unsigned D = 1;
00090     for (const LoopBase<BlockT> *CurLoop = ParentLoop; CurLoop;
00091          CurLoop = CurLoop->ParentLoop)
00092       ++D;
00093     return D;
00094   }
00095   BlockT *getHeader() const { return Blocks.front(); }
00096   LoopBase<BlockT> *getParentLoop() const { return ParentLoop; }
00097 
00098   /// contains - Return true if the specified basic block is in this loop
00099   ///
00100   bool contains(const BlockT *BB) const {
00101     return std::find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
00102   }
00103 
00104   /// iterator/begin/end - Return the loops contained entirely within this loop.
00105   ///
00106   const std::vector<LoopBase<BlockT>*> &getSubLoops() const { return SubLoops; }
00107   typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
00108   iterator begin() const { return SubLoops.begin(); }
00109   iterator end() const { return SubLoops.end(); }
00110   bool empty() const { return SubLoops.empty(); }
00111 
00112   /// getBlocks - Get a list of the basic blocks which make up this loop.
00113   ///
00114   const std::vector<BlockT*> &getBlocks() const { return Blocks; }
00115   typedef typename std::vector<BlockT*>::const_iterator block_iterator;
00116   block_iterator block_begin() const { return Blocks.begin(); }
00117   block_iterator block_end() const { return Blocks.end(); }
00118 
00119   /// isLoopExit - True if terminator in the block can branch to another block
00120   /// that is outside of the current loop.
00121   ///
00122   bool isLoopExit(const BlockT *BB) const {
00123     typedef GraphTraits<BlockT*> BlockTraits;
00124     for (typename BlockTraits::ChildIteratorType SI =
00125          BlockTraits::child_begin(const_cast<BlockT*>(BB)),
00126          SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
00127       if (!contains(*SI))
00128         return true;
00129     }
00130     return false;
00131   }
00132 
00133   /// getNumBackEdges - Calculate the number of back edges to the loop header
00134   ///
00135   unsigned getNumBackEdges() const {
00136     unsigned NumBackEdges = 0;
00137     BlockT *H = getHeader();
00138 
00139     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00140     for (typename InvBlockTraits::ChildIteratorType I =
00141          InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
00142          E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
00143       if (contains(*I))
00144         ++NumBackEdges;
00145 
00146     return NumBackEdges;
00147   }
00148 
00149   /// isLoopInvariant - Return true if the specified value is loop invariant
00150   ///
00151   inline bool isLoopInvariant(Value *V) const {
00152     if (Instruction *I = dyn_cast<Instruction>(V))
00153       return !contains(I->getParent());
00154     return true;  // All non-instructions are loop invariant
00155   }
00156 
00157   //===--------------------------------------------------------------------===//
00158   // APIs for simple analysis of the loop.
00159   //
00160   // Note that all of these methods can fail on general loops (ie, there may not
00161   // be a preheader, etc).  For best success, the loop simplification and
00162   // induction variable canonicalization pass should be used to normalize loops
00163   // for easy analysis.  These methods assume canonical loops.
00164 
00165   /// getExitingBlocks - Return all blocks inside the loop that have successors
00166   /// outside of the loop.  These are the blocks _inside of the current loop_
00167   /// which branch out.  The returned list is always unique.
00168   ///
00169   void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
00170     // Sort the blocks vector so that we can use binary search to do quick
00171     // lookups.
00172     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
00173     std::sort(LoopBBs.begin(), LoopBBs.end());
00174 
00175     typedef GraphTraits<BlockT*> BlockTraits;
00176     for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
00177          BE = Blocks.end(); BI != BE; ++BI)
00178       for (typename BlockTraits::ChildIteratorType I =
00179           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
00180           I != E; ++I)
00181         if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
00182           // Not in current loop? It must be an exit block.
00183           ExitingBlocks.push_back(*BI);
00184           break;
00185         }
00186   }
00187 
00188   /// getExitBlocks - Return all of the successor blocks of this loop.  These
00189   /// are the blocks _outside of the current loop_ which are branched to.
00190   ///
00191   void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
00192     // Sort the blocks vector so that we can use binary search to do quick
00193     // lookups.
00194     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
00195     std::sort(LoopBBs.begin(), LoopBBs.end());
00196 
00197     typedef GraphTraits<BlockT*> BlockTraits;
00198     for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
00199          BE = Blocks.end(); BI != BE; ++BI)
00200       for (typename BlockTraits::ChildIteratorType I =
00201            BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
00202            I != E; ++I)
00203         if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
00204           // Not in current loop? It must be an exit block.
00205           ExitBlocks.push_back(*I);
00206   }
00207 
00208   /// getUniqueExitBlocks - Return all unique successor blocks of this loop. 
00209   /// These are the blocks _outside of the current loop_ which are branched to.
00210   /// This assumes that loop is in canonical form.
00211   ///
00212   void getUniqueExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
00213     // Sort the blocks vector so that we can use binary search to do quick
00214     // lookups.
00215     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
00216     std::sort(LoopBBs.begin(), LoopBBs.end());
00217 
00218     std::vector<BlockT*> switchExitBlocks;  
00219 
00220     for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
00221          BE = Blocks.end(); BI != BE; ++BI) {
00222 
00223       BlockT *current = *BI;
00224       switchExitBlocks.clear();
00225 
00226       typedef GraphTraits<BlockT*> BlockTraits;
00227       typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00228       for (typename BlockTraits::ChildIteratorType I =
00229            BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
00230            I != E; ++I) {
00231         if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
00232       // If block is inside the loop then it is not a exit block.
00233           continue;
00234       
00235         typename InvBlockTraits::ChildIteratorType PI =
00236                                                 InvBlockTraits::child_begin(*I);
00237         BlockT *firstPred = *PI;
00238 
00239         // If current basic block is this exit block's first predecessor
00240         // then only insert exit block in to the output ExitBlocks vector.
00241         // This ensures that same exit block is not inserted twice into
00242         // ExitBlocks vector.
00243         if (current != firstPred) 
00244           continue;
00245 
00246         // If a terminator has more then two successors, for example SwitchInst,
00247         // then it is possible that there are multiple edges from current block 
00248         // to one exit block. 
00249         if (std::distance(BlockTraits::child_begin(current),
00250                           BlockTraits::child_end(current)) <= 2) {
00251           ExitBlocks.push_back(*I);
00252           continue;
00253         }
00254 
00255         // In case of multiple edges from current block to exit block, collect
00256         // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
00257         // duplicate edges.
00258         if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I) 
00259             == switchExitBlocks.end()) {
00260           switchExitBlocks.push_back(*I);
00261           ExitBlocks.push_back(*I);
00262         }
00263       }
00264     }
00265   }
00266 
00267   /// getLoopPreheader - If there is a preheader for this loop, return it.  A
00268   /// loop has a preheader if there is only one edge to the header of the loop
00269   /// from outside of the loop.  If this is the case, the block branching to the
00270   /// header of the loop is the preheader node.
00271   ///
00272   /// This method returns null if there is no preheader for the loop.
00273   ///
00274   BlockT *getLoopPreheader() const {
00275     // Keep track of nodes outside the loop branching to the header...
00276     BlockT *Out = 0;
00277 
00278     // Loop over the predecessors of the header node...
00279     BlockT *Header = getHeader();
00280     typedef GraphTraits<BlockT*> BlockTraits;
00281     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00282     for (typename InvBlockTraits::ChildIteratorType PI =
00283          InvBlockTraits::child_begin(Header),
00284          PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
00285       if (!contains(*PI)) {     // If the block is not in the loop...
00286         if (Out && Out != *PI)
00287           return 0;             // Multiple predecessors outside the loop
00288         Out = *PI;
00289       }
00290 
00291     // Make sure there is only one exit out of the preheader.
00292     assert(Out && "Header of loop has no predecessors from outside loop?");
00293     typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
00294     ++SI;
00295     if (SI != BlockTraits::child_end(Out))
00296       return 0;  // Multiple exits from the block, must not be a preheader.
00297 
00298     // If there is exactly one preheader, return it.  If there was zero, then
00299     // Out is still null.
00300     return Out;
00301   }
00302 
00303   /// getLoopLatch - If there is a latch block for this loop, return it.  A
00304   /// latch block is the canonical backedge for a loop.  A loop header in normal
00305   /// form has two edges into it: one from a preheader and one from a latch
00306   /// block.
00307   BlockT *getLoopLatch() const {
00308     BlockT *Header = getHeader();
00309     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00310     typename InvBlockTraits::ChildIteratorType PI =
00311                                             InvBlockTraits::child_begin(Header);
00312     typename InvBlockTraits::ChildIteratorType PE =
00313                                               InvBlockTraits::child_end(Header);
00314     if (PI == PE) return 0;  // no preds?
00315 
00316     BlockT *Latch = 0;
00317     if (contains(*PI))
00318       Latch = *PI;
00319     ++PI;
00320     if (PI == PE) return 0;  // only one pred?
00321 
00322     if (contains(*PI)) {
00323       if (Latch) return 0;  // multiple backedges
00324       Latch = *PI;
00325     }
00326     ++PI;
00327     if (PI != PE) return 0;  // more than two preds
00328 
00329     return Latch;
00330   }
00331   
00332   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
00333   /// induction variable: an integer recurrence that starts at 0 and increments
00334   /// by one each time through the loop.  If so, return the phi node that
00335   /// corresponds to it.
00336   ///
00337   inline PHINode *getCanonicalInductionVariable() const {
00338     BlockT *H = getHeader();
00339 
00340     BlockT *Incoming = 0, *Backedge = 0;
00341     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00342     typename InvBlockTraits::ChildIteratorType PI =
00343                                                  InvBlockTraits::child_begin(H);
00344     assert(PI != InvBlockTraits::child_end(H) &&
00345            "Loop must have at least one backedge!");
00346     Backedge = *PI++;
00347     if (PI == InvBlockTraits::child_end(H)) return 0;  // dead loop
00348     Incoming = *PI++;
00349     if (PI != InvBlockTraits::child_end(H)) return 0;  // multiple backedges?
00350 
00351     if (contains(Incoming)) {
00352       if (contains(Backedge))
00353         return 0;
00354       std::swap(Incoming, Backedge);
00355     } else if (!contains(Backedge))
00356       return 0;
00357 
00358     // Loop over all of the PHI nodes, looking for a canonical indvar.
00359     for (typename BlockT::iterator I = H->begin(); isa<PHINode>(I); ++I) {
00360       PHINode *PN = cast<PHINode>(I);
00361       if (ConstantInt *CI =
00362           dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
00363         if (CI->isNullValue())
00364           if (Instruction *Inc =
00365               dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
00366             if (Inc->getOpcode() == Instruction::Add &&
00367                 Inc->getOperand(0) == PN)
00368               if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
00369                 if (CI->equalsInt(1))
00370                   return PN;
00371     }
00372     return 0;
00373   }
00374 
00375   /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
00376   /// the canonical induction variable value for the "next" iteration of the
00377   /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
00378   ///
00379   inline Instruction *getCanonicalInductionVariableIncrement() const {
00380     if (PHINode *PN = getCanonicalInductionVariable()) {
00381       bool P1InLoop = contains(PN->getIncomingBlock(1));
00382       return cast<Instruction>(PN->getIncomingValue(P1InLoop));
00383     }
00384     return 0;
00385   }
00386 
00387   /// getTripCount - Return a loop-invariant LLVM value indicating the number of
00388   /// times the loop will be executed.  Note that this means that the backedge
00389   /// of the loop executes N-1 times.  If the trip-count cannot be determined,
00390   /// this returns null.
00391   ///
00392   inline Value *getTripCount() const {
00393     // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
00394     // canonical induction variable and V is the trip count of the loop.
00395     Instruction *Inc = getCanonicalInductionVariableIncrement();
00396     if (Inc == 0) return 0;
00397     PHINode *IV = cast<PHINode>(Inc->getOperand(0));
00398 
00399     BlockT *BackedgeBlock =
00400             IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
00401 
00402     if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
00403       if (BI->isConditional()) {
00404         if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
00405           if (ICI->getOperand(0) == Inc) {
00406             if (BI->getSuccessor(0) == getHeader()) {
00407               if (ICI->getPredicate() == ICmpInst::ICMP_NE)
00408                 return ICI->getOperand(1);
00409             } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
00410               return ICI->getOperand(1);
00411             }
00412           }
00413         }
00414       }
00415 
00416     return 0;
00417   }
00418   
00419   /// getSmallConstantTripCount - Returns the trip count of this loop as a
00420   /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
00421   /// of not constant. Will also return 0 if the trip count is very large 
00422   /// (>= 2^32)
00423   inline unsigned getSmallConstantTripCount() const {
00424     Value* TripCount = this->getTripCount();
00425     if (TripCount) {
00426       if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCount)) {
00427         // Guard against huge trip counts.
00428         if (TripCountC->getValue().getActiveBits() <= 32) {
00429           return (unsigned)TripCountC->getZExtValue();
00430         }
00431       }
00432     }
00433     return 0;
00434   }
00435 
00436   /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
00437   /// trip count of this loop as a normal unsigned value, if possible. This
00438   /// means that the actual trip count is always a multiple of the returned
00439   /// value (don't forget the trip count could very well be zero as well!).
00440   ///
00441   /// Returns 1 if the trip count is unknown or not guaranteed to be the
00442   /// multiple of a constant (which is also the case if the trip count is simply
00443   /// constant, use getSmallConstantTripCount for that case), Will also return 1
00444   /// if the trip count is very large (>= 2^32).
00445   inline unsigned getSmallConstantTripMultiple() const {
00446     Value* TripCount = this->getTripCount();
00447     // This will hold the ConstantInt result, if any
00448     ConstantInt *Result = NULL;
00449     if (TripCount) {
00450       // See if the trip count is constant itself
00451       Result = dyn_cast<ConstantInt>(TripCount);
00452       // if not, see if it is a multiplication
00453       if (!Result)
00454         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCount)) {
00455           switch (BO->getOpcode()) {
00456           case BinaryOperator::Mul:
00457             Result = dyn_cast<ConstantInt>(BO->getOperand(1));
00458             break;
00459           default: 
00460             break;
00461           }
00462         }
00463     }
00464     // Guard against huge trip counts.
00465     if (Result && Result->getValue().getActiveBits() <= 32) {
00466       return (unsigned)Result->getZExtValue();
00467     } else {
00468       return 1;
00469     }
00470   }
00471   
00472   /// isLCSSAForm - Return true if the Loop is in LCSSA form
00473   inline bool isLCSSAForm() const {
00474     // Sort the blocks vector so that we can use binary search to do quick
00475     // lookups.
00476     SmallPtrSet<BlockT*, 16> LoopBBs(block_begin(), block_end());
00477 
00478     for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
00479       BlockT *BB = *BI;
00480       for (typename BlockT::iterator I = BB->begin(), E = BB->end(); I != E;++I)
00481         for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
00482              ++UI) {
00483           BlockT *UserBB = cast<Instruction>(*UI)->getParent();
00484           if (PHINode *P = dyn_cast<PHINode>(*UI)) {
00485             UserBB = P->getIncomingBlock(UI);
00486           }
00487 
00488           // Check the current block, as a fast-path.  Most values are used in
00489           // the same block they are defined in.
00490           if (UserBB != BB && !LoopBBs.count(UserBB))
00491             return false;
00492         }
00493     }
00494 
00495     return true;
00496   }
00497 
00498   //===--------------------------------------------------------------------===//
00499   // APIs for updating loop information after changing the CFG
00500   //
00501 
00502   /// addBasicBlockToLoop - This method is used by other analyses to update loop
00503   /// information.  NewBB is set to be a new member of the current loop.
00504   /// Because of this, it is added as a member of all parent loops, and is added
00505   /// to the specified LoopInfo object as being in the current basic block.  It
00506   /// is not valid to replace the loop header with this method.
00507   ///
00508   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT> &LI);
00509 
00510   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
00511   /// the OldChild entry in our children list with NewChild, and updates the
00512   /// parent pointer of OldChild to be null and the NewChild to be this loop.
00513   /// This updates the loop depth of the new child.
00514   void replaceChildLoopWith(LoopBase<BlockT> *OldChild,
00515                             LoopBase<BlockT> *NewChild) {
00516     assert(OldChild->ParentLoop == this && "This loop is already broken!");
00517     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
00518     typename std::vector<LoopBase<BlockT>*>::iterator I =
00519                           std::find(SubLoops.begin(), SubLoops.end(), OldChild);
00520     assert(I != SubLoops.end() && "OldChild not in loop!");
00521     *I = NewChild;
00522     OldChild->ParentLoop = 0;
00523     NewChild->ParentLoop = this;
00524   }
00525 
00526   /// addChildLoop - Add the specified loop to be a child of this loop.  This
00527   /// updates the loop depth of the new child.
00528   ///
00529   void addChildLoop(LoopBase<BlockT> *NewChild) {
00530     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
00531     NewChild->ParentLoop = this;
00532     SubLoops.push_back(NewChild);
00533   }
00534 
00535   /// removeChildLoop - This removes the specified child from being a subloop of
00536   /// this loop.  The loop is not deleted, as it will presumably be inserted
00537   /// into another loop.
00538   LoopBase<BlockT> *removeChildLoop(iterator I) {
00539     assert(I != SubLoops.end() && "Cannot remove end iterator!");
00540     LoopBase<BlockT> *Child = *I;
00541     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
00542     SubLoops.erase(SubLoops.begin()+(I-begin()));
00543     Child->ParentLoop = 0;
00544     return Child;
00545   }
00546 
00547   /// addBlockEntry - This adds a basic block directly to the basic block list.
00548   /// This should only be used by transformations that create new loops.  Other
00549   /// transformations should use addBasicBlockToLoop.
00550   void addBlockEntry(BlockT *BB) {
00551     Blocks.push_back(BB);
00552   }
00553 
00554   /// moveToHeader - This method is used to move BB (which must be part of this
00555   /// loop) to be the loop header of the loop (the block that dominates all
00556   /// others).
00557   void moveToHeader(BlockT *BB) {
00558     if (Blocks[0] == BB) return;
00559     for (unsigned i = 0; ; ++i) {
00560       assert(i != Blocks.size() && "Loop does not contain BB!");
00561       if (Blocks[i] == BB) {
00562         Blocks[i] = Blocks[0];
00563         Blocks[0] = BB;
00564         return;
00565       }
00566     }
00567   }
00568 
00569   /// removeBlockFromLoop - This removes the specified basic block from the
00570   /// current loop, updating the Blocks as appropriate.  This does not update
00571   /// the mapping in the LoopInfo class.
00572   void removeBlockFromLoop(BlockT *BB) {
00573     RemoveFromVector(Blocks, BB);
00574   }
00575 
00576   /// verifyLoop - Verify loop structure
00577   void verifyLoop() const {
00578 #ifndef NDEBUG
00579     assert (getHeader() && "Loop header is missing");
00580     assert (getLoopPreheader() && "Loop preheader is missing");
00581     assert (getLoopLatch() && "Loop latch is missing");
00582     for (typename std::vector<LoopBase<BlockT>*>::const_iterator I =
00583          SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
00584       (*I)->verifyLoop();
00585 #endif
00586   }
00587 
00588   void print(std::ostream &OS, unsigned Depth = 0) const {
00589     OS << std::string(Depth*2, ' ') << "Loop Containing: ";
00590 
00591     for (unsigned i = 0; i < getBlocks().size(); ++i) {
00592       if (i) OS << ",";
00593       WriteAsOperand(OS, getBlocks()[i], false);
00594     }
00595     OS << "\n";
00596 
00597     for (iterator I = begin(), E = end(); I != E; ++I)
00598       (*I)->print(OS, Depth+2);
00599   }
00600   
00601   void print(std::ostream *O, unsigned Depth = 0) const {
00602     if (O) print(*O, Depth);
00603   }
00604   
00605   void dump() const {
00606     print(cerr);
00607   }
00608   
00609 private:
00610   friend class LoopInfoBase<BlockT>;
00611   explicit LoopBase(BlockT *BB) : ParentLoop(0) {
00612     Blocks.push_back(BB);
00613   }
00614 };
00615 
00616 
00617 //===----------------------------------------------------------------------===//
00618 /// LoopInfo - This class builds and contains all of the top level loop
00619 /// structures in the specified function.
00620 ///
00621 
00622 template<class BlockT>
00623 class LoopInfoBase {
00624   // BBMap - Mapping of basic blocks to the inner most loop they occur in
00625   std::map<BlockT*, LoopBase<BlockT>*> BBMap;
00626   std::vector<LoopBase<BlockT>*> TopLevelLoops;
00627   friend class LoopBase<BlockT>;
00628   
00629 public:
00630   LoopInfoBase() { }
00631   ~LoopInfoBase() { releaseMemory(); }
00632   
00633   void releaseMemory() {
00634     for (typename std::vector<LoopBase<BlockT>* >::iterator I =
00635          TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
00636       delete *I;   // Delete all of the loops...
00637 
00638     BBMap.clear();                           // Reset internal state of analysis
00639     TopLevelLoops.clear();
00640   }
00641   
00642   /// iterator/begin/end - The interface to the top-level loops in the current
00643   /// function.
00644   ///
00645   typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
00646   iterator begin() const { return TopLevelLoops.begin(); }
00647   iterator end() const { return TopLevelLoops.end(); }
00648   bool empty() const { return TopLevelLoops.empty(); }
00649   
00650   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
00651   /// block is in no loop (for example the entry node), null is returned.
00652   ///
00653   LoopBase<BlockT> *getLoopFor(const BlockT *BB) const {
00654     typename std::map<BlockT *, LoopBase<BlockT>*>::const_iterator I=
00655       BBMap.find(const_cast<BlockT*>(BB));
00656     return I != BBMap.end() ? I->second : 0;
00657   }
00658   
00659   /// operator[] - same as getLoopFor...
00660   ///
00661   const LoopBase<BlockT> *operator[](const BlockT *BB) const {
00662     return getLoopFor(BB);
00663   }
00664   
00665   /// getLoopDepth - Return the loop nesting level of the specified block.  A
00666   /// depth of 0 means the block is not inside any loop.
00667   ///
00668   unsigned getLoopDepth(const BlockT *BB) const {
00669     const LoopBase<BlockT> *L = getLoopFor(BB);
00670     return L ? L->getLoopDepth() : 0;
00671   }
00672 
00673   // isLoopHeader - True if the block is a loop header node
00674   bool isLoopHeader(BlockT *BB) const {
00675     const LoopBase<BlockT> *L = getLoopFor(BB);
00676     return L && L->getHeader() == BB;
00677   }
00678   
00679   /// removeLoop - This removes the specified top-level loop from this loop info
00680   /// object.  The loop is not deleted, as it will presumably be inserted into
00681   /// another loop.
00682   LoopBase<BlockT> *removeLoop(iterator I) {
00683     assert(I != end() && "Cannot remove end iterator!");
00684     LoopBase<BlockT> *L = *I;
00685     assert(L->getParentLoop() == 0 && "Not a top-level loop!");
00686     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
00687     return L;
00688   }
00689   
00690   /// changeLoopFor - Change the top-level loop that contains BB to the
00691   /// specified loop.  This should be used by transformations that restructure
00692   /// the loop hierarchy tree.
00693   void changeLoopFor(BlockT *BB, LoopBase<BlockT> *L) {
00694     LoopBase<BlockT> *&OldLoop = BBMap[BB];
00695     assert(OldLoop && "Block not in a loop yet!");
00696     OldLoop = L;
00697   }
00698   
00699   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
00700   /// list with the indicated loop.
00701   void changeTopLevelLoop(LoopBase<BlockT> *OldLoop,
00702                           LoopBase<BlockT> *NewLoop) {
00703     typename std::vector<LoopBase<BlockT>*>::iterator I =
00704                  std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
00705     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
00706     *I = NewLoop;
00707     assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
00708            "Loops already embedded into a subloop!");
00709   }
00710   
00711   /// addTopLevelLoop - This adds the specified loop to the collection of
00712   /// top-level loops.
00713   void addTopLevelLoop(LoopBase<BlockT> *New) {
00714     assert(New->getParentLoop() == 0 && "Loop already in subloop!");
00715     TopLevelLoops.push_back(New);
00716   }
00717   
00718   /// removeBlock - This method completely removes BB from all data structures,
00719   /// including all of the Loop objects it is nested in and our mapping from
00720   /// BasicBlocks to loops.
00721   void removeBlock(BlockT *BB) {
00722     typename std::map<BlockT *, LoopBase<BlockT>*>::iterator I = BBMap.find(BB);
00723     if (I != BBMap.end()) {
00724       for (LoopBase<BlockT> *L = I->second; L; L = L->getParentLoop())
00725         L->removeBlockFromLoop(BB);
00726 
00727       BBMap.erase(I);
00728     }
00729   }
00730   
00731   // Internals
00732   
00733   static bool isNotAlreadyContainedIn(const LoopBase<BlockT> *SubLoop,
00734                                       const LoopBase<BlockT> *ParentLoop) {
00735     if (SubLoop == 0) return true;
00736     if (SubLoop == ParentLoop) return false;
00737     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
00738   }
00739   
00740   void Calculate(DominatorTreeBase<BlockT> &DT) {
00741     BlockT *RootNode = DT.getRootNode()->getBlock();
00742 
00743     for (df_iterator<BlockT*> NI = df_begin(RootNode),
00744            NE = df_end(RootNode); NI != NE; ++NI)
00745       if (LoopBase<BlockT> *L = ConsiderForLoop(*NI, DT))
00746         TopLevelLoops.push_back(L);
00747   }
00748   
00749   LoopBase<BlockT> *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
00750     if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
00751 
00752     std::vector<BlockT *> TodoStack;
00753 
00754     // Scan the predecessors of BB, checking to see if BB dominates any of
00755     // them.  This identifies backedges which target this node...
00756     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00757     for (typename InvBlockTraits::ChildIteratorType I =
00758          InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
00759          I != E; ++I)
00760       if (DT.dominates(BB, *I))   // If BB dominates it's predecessor...
00761         TodoStack.push_back(*I);
00762 
00763     if (TodoStack.empty()) return 0;  // No backedges to this block...
00764 
00765     // Create a new loop to represent this basic block...
00766     LoopBase<BlockT> *L = new LoopBase<BlockT>(BB);
00767     BBMap[BB] = L;
00768 
00769     BlockT *EntryBlock = BB->getParent()->begin();
00770 
00771     while (!TodoStack.empty()) {  // Process all the nodes in the loop
00772       BlockT *X = TodoStack.back();
00773       TodoStack.pop_back();
00774 
00775       if (!L->contains(X) &&         // As of yet unprocessed??
00776           DT.dominates(EntryBlock, X)) {   // X is reachable from entry block?
00777         // Check to see if this block already belongs to a loop.  If this occurs
00778         // then we have a case where a loop that is supposed to be a child of
00779         // the current loop was processed before the current loop.  When this
00780         // occurs, this child loop gets added to a part of the current loop,
00781         // making it a sibling to the current loop.  We have to reparent this
00782         // loop.
00783         if (LoopBase<BlockT> *SubLoop =
00784             const_cast<LoopBase<BlockT>*>(getLoopFor(X)))
00785           if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
00786             // Remove the subloop from it's current parent...
00787             assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
00788             LoopBase<BlockT> *SLP = SubLoop->ParentLoop;  // SubLoopParent
00789             typename std::vector<LoopBase<BlockT>*>::iterator I =
00790               std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
00791             assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
00792             SLP->SubLoops.erase(I);   // Remove from parent...
00793 
00794             // Add the subloop to THIS loop...
00795             SubLoop->ParentLoop = L;
00796             L->SubLoops.push_back(SubLoop);
00797           }
00798 
00799         // Normal case, add the block to our loop...
00800         L->Blocks.push_back(X);
00801         
00802         typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00803         
00804         // Add all of the predecessors of X to the end of the work stack...
00805         TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
00806                          InvBlockTraits::child_end(X));
00807       }
00808     }
00809 
00810     // If there are any loops nested within this loop, create them now!
00811     for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
00812          E = L->Blocks.end(); I != E; ++I)
00813       if (LoopBase<BlockT> *NewLoop = ConsiderForLoop(*I, DT)) {
00814         L->SubLoops.push_back(NewLoop);
00815         NewLoop->ParentLoop = L;
00816       }
00817 
00818     // Add the basic blocks that comprise this loop to the BBMap so that this
00819     // loop can be found for them.
00820     //
00821     for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
00822            E = L->Blocks.end(); I != E; ++I) {
00823       typename std::map<BlockT*, LoopBase<BlockT>*>::iterator BBMI =
00824                                                           BBMap.find(*I);
00825       if (BBMI == BBMap.end())                       // Not in map yet...
00826         BBMap.insert(BBMI, std::make_pair(*I, L));   // Must be at this level
00827     }
00828 
00829     // Now that we have a list of all of the child loops of this loop, check to
00830     // see if any of them should actually be nested inside of each other.  We
00831     // can accidentally pull loops our of their parents, so we must make sure to
00832     // organize the loop nests correctly now.
00833     {
00834       std::map<BlockT*, LoopBase<BlockT>*> ContainingLoops;
00835       for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
00836         LoopBase<BlockT> *Child = L->SubLoops[i];
00837         assert(Child->getParentLoop() == L && "Not proper child loop?");
00838 
00839         if (LoopBase<BlockT> *ContainingLoop =
00840                                           ContainingLoops[Child->getHeader()]) {
00841           // If there is already a loop which contains this loop, move this loop
00842           // into the containing loop.
00843           MoveSiblingLoopInto(Child, ContainingLoop);
00844           --i;  // The loop got removed from the SubLoops list.
00845         } else {
00846           // This is currently considered to be a top-level loop.  Check to see
00847           // if any of the contained blocks are loop headers for subloops we
00848           // have already processed.
00849           for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
00850             LoopBase<BlockT> *&BlockLoop = ContainingLoops[Child->Blocks[b]];
00851             if (BlockLoop == 0) {   // Child block not processed yet...
00852               BlockLoop = Child;
00853             } else if (BlockLoop != Child) {
00854               LoopBase<BlockT> *SubLoop = BlockLoop;
00855               // Reparent all of the blocks which used to belong to BlockLoops
00856               for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
00857                 ContainingLoops[SubLoop->Blocks[j]] = Child;
00858 
00859               // There is already a loop which contains this block, that means
00860               // that we should reparent the loop which the block is currently
00861               // considered to belong to to be a child of this loop.
00862               MoveSiblingLoopInto(SubLoop, Child);
00863               --i;  // We just shrunk the SubLoops list.
00864             }
00865           }
00866         }
00867       }
00868     }
00869 
00870     return L;
00871   }
00872   
00873   /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
00874   /// of the NewParent Loop, instead of being a sibling of it.
00875   void MoveSiblingLoopInto(LoopBase<BlockT> *NewChild,
00876                            LoopBase<BlockT> *NewParent) {
00877     LoopBase<BlockT> *OldParent = NewChild->getParentLoop();
00878     assert(OldParent && OldParent == NewParent->getParentLoop() &&
00879            NewChild != NewParent && "Not sibling loops!");
00880 
00881     // Remove NewChild from being a child of OldParent
00882     typename std::vector<LoopBase<BlockT>*>::iterator I =
00883       std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
00884                 NewChild);
00885     assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
00886     OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
00887     NewChild->ParentLoop = 0;
00888 
00889     InsertLoopInto(NewChild, NewParent);
00890   }
00891   
00892   /// InsertLoopInto - This inserts loop L into the specified parent loop.  If
00893   /// the parent loop contains a loop which should contain L, the loop gets
00894   /// inserted into L instead.
00895   void InsertLoopInto(LoopBase<BlockT> *L, LoopBase<BlockT> *Parent) {
00896     BlockT *LHeader = L->getHeader();
00897     assert(Parent->contains(LHeader) &&
00898            "This loop should not be inserted here!");
00899 
00900     // Check to see if it belongs in a child loop...
00901     for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
00902          i != e; ++i)
00903       if (Parent->SubLoops[i]->contains(LHeader)) {
00904         InsertLoopInto(L, Parent->SubLoops[i]);
00905         return;
00906       }
00907 
00908     // If not, insert it here!
00909     Parent->SubLoops.push_back(L);
00910     L->ParentLoop = Parent;
00911   }
00912   
00913   // Debugging
00914   
00915   void print(std::ostream &OS, const Module* ) const {
00916     for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
00917       TopLevelLoops[i]->print(OS);
00918   #if 0
00919     for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
00920            E = BBMap.end(); I != E; ++I)
00921       OS << "BB '" << I->first->getName() << "' level = "
00922          << I->second->getLoopDepth() << "\n";
00923   #endif
00924   }
00925 };
00926 
00927 class LoopInfo : public FunctionPass {
00928   LoopInfoBase<BasicBlock>* LI;
00929   friend class LoopBase<BasicBlock>;
00930   
00931 public:
00932   static char ID; // Pass identification, replacement for typeid
00933 
00934   LoopInfo() : FunctionPass(intptr_t(&ID)) {
00935     LI = new LoopInfoBase<BasicBlock>();
00936   }
00937   
00938   ~LoopInfo() { delete LI; }
00939 
00940   LoopInfoBase<BasicBlock>& getBase() { return *LI; }
00941 
00942   /// iterator/begin/end - The interface to the top-level loops in the current
00943   /// function.
00944   ///
00945   typedef std::vector<Loop*>::const_iterator iterator;
00946   inline iterator begin() const { return LI->begin(); }
00947   inline iterator end() const { return LI->end(); }
00948   bool empty() const { return LI->empty(); }
00949 
00950   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
00951   /// block is in no loop (for example the entry node), null is returned.
00952   ///
00953   inline Loop *getLoopFor(const BasicBlock *BB) const {
00954     return LI->getLoopFor(BB);
00955   }
00956 
00957   /// operator[] - same as getLoopFor...
00958   ///
00959   inline const Loop *operator[](const BasicBlock *BB) const {
00960     return LI->getLoopFor(BB);
00961   }
00962 
00963   /// getLoopDepth - Return the loop nesting level of the specified block.  A
00964   /// depth of 0 means the block is not inside any loop.
00965   ///
00966   inline unsigned getLoopDepth(const BasicBlock *BB) const {
00967     return LI->getLoopDepth(BB);
00968   }
00969 
00970   // isLoopHeader - True if the block is a loop header node
00971   inline bool isLoopHeader(BasicBlock *BB) const {
00972     return LI->isLoopHeader(BB);
00973   }
00974 
00975   /// runOnFunction - Calculate the natural loop information.
00976   ///
00977   virtual bool runOnFunction(Function &F);
00978 
00979   virtual void releaseMemory() { LI->releaseMemory(); }
00980 
00981   virtual void print(std::ostream &O, const Module* M = 0) const {
00982     if (O) LI->print(O, M);
00983   }
00984 
00985   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
00986 
00987   /// removeLoop - This removes the specified top-level loop from this loop info
00988   /// object.  The loop is not deleted, as it will presumably be inserted into
00989   /// another loop.
00990   inline Loop *removeLoop(iterator I) { return LI->removeLoop(I); }
00991 
00992   /// changeLoopFor - Change the top-level loop that contains BB to the
00993   /// specified loop.  This should be used by transformations that restructure
00994   /// the loop hierarchy tree.
00995   inline void changeLoopFor(BasicBlock *BB, Loop *L) {
00996     LI->changeLoopFor(BB, L);
00997   }
00998 
00999   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
01000   /// list with the indicated loop.
01001   inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
01002     LI->changeTopLevelLoop(OldLoop, NewLoop);
01003   }
01004 
01005   /// addTopLevelLoop - This adds the specified loop to the collection of
01006   /// top-level loops.
01007   inline void addTopLevelLoop(Loop *New) {
01008     LI->addTopLevelLoop(New);
01009   }
01010 
01011   /// removeBlock - This method completely removes BB from all data structures,
01012   /// including all of the Loop objects it is nested in and our mapping from
01013   /// BasicBlocks to loops.
01014   void removeBlock(BasicBlock *BB) {
01015     LI->removeBlock(BB);
01016   }
01017 };
01018 
01019 
01020 // Allow clients to walk the list of nested loops...
01021 template <> struct GraphTraits<const Loop*> {
01022   typedef const Loop NodeType;
01023   typedef std::vector<Loop*>::const_iterator ChildIteratorType;
01024 
01025   static NodeType *getEntryNode(const Loop *L) { return L; }
01026   static inline ChildIteratorType child_begin(NodeType *N) {
01027     return N->begin();
01028   }
01029   static inline ChildIteratorType child_end(NodeType *N) {
01030     return N->end();
01031   }
01032 };
01033 
01034 template <> struct GraphTraits<Loop*> {
01035   typedef Loop NodeType;
01036   typedef std::vector<Loop*>::const_iterator ChildIteratorType;
01037 
01038   static NodeType *getEntryNode(Loop *L) { return L; }
01039   static inline ChildIteratorType child_begin(NodeType *N) {
01040     return N->begin();
01041   }
01042   static inline ChildIteratorType child_end(NodeType *N) {
01043     return N->end();
01044   }
01045 };
01046 
01047 template<class BlockT>
01048 void LoopBase<BlockT>::addBasicBlockToLoop(BlockT *NewBB,
01049                                            LoopInfoBase<BlockT> &LIB) {
01050   assert((Blocks.empty() || LIB[getHeader()] == this) &&
01051          "Incorrect LI specified for this loop!");
01052   assert(NewBB && "Cannot add a null basic block to the loop!");
01053   assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
01054 
01055   // Add the loop mapping to the LoopInfo object...
01056   LIB.BBMap[NewBB] = this;
01057 
01058   // Add the basic block to this loop and all parent loops...
01059   LoopBase<BlockT> *L = this;
01060   while (L) {
01061     L->Blocks.push_back(NewBB);
01062     L = L->getParentLoop();
01063   }
01064 }
01065 
01066 } // End llvm namespace
01067 
01068 #endif