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.  A natural loop
00012 // has exactly one entry-point, which is called the header. Note that natural
00013 // loops may actually be several loops that share the same header node.
00014 //
00015 // This analysis calculates the nesting structure of loops in a function.  For
00016 // each natural loop identified, this analysis identifies natural loops
00017 // contained entirely within the loop and the basic blocks the make up the loop.
00018 //
00019 // It can calculate on the fly various bits of information, for example:
00020 //
00021 //  * whether there is a preheader for the loop
00022 //  * the number of back edges to the header
00023 //  * whether or not a particular block branches out of the loop
00024 //  * the successor blocks of the loop
00025 //  * the loop depth
00026 //  * etc...
00027 //
00028 //===----------------------------------------------------------------------===//
00029 
00030 #ifndef LLVM_ANALYSIS_LOOPINFO_H
00031 #define LLVM_ANALYSIS_LOOPINFO_H
00032 
00033 #include "llvm/ADT/DenseMap.h"
00034 #include "llvm/ADT/DenseSet.h"
00035 #include "llvm/ADT/GraphTraits.h"
00036 #include "llvm/ADT/SmallPtrSet.h"
00037 #include "llvm/ADT/SmallVector.h"
00038 #include "llvm/IR/CFG.h"
00039 #include "llvm/IR/Instruction.h"
00040 #include "llvm/Pass.h"
00041 #include <algorithm>
00042 
00043 namespace llvm {
00044 
00045 template<typename T>
00046 inline void RemoveFromVector(std::vector<T*> &V, T *N) {
00047   typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
00048   assert(I != V.end() && "N is not in this list!");
00049   V.erase(I);
00050 }
00051 
00052 class DominatorTree;
00053 class LoopInfo;
00054 class Loop;
00055 class MDNode;
00056 class PHINode;
00057 class raw_ostream;
00058 template<class N> class DominatorTreeBase;
00059 template<class N, class M> class LoopInfoBase;
00060 template<class N, class M> class LoopBase;
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, class LoopT>
00067 class LoopBase {
00068   LoopT *ParentLoop;
00069   // SubLoops - Loops contained entirely within this one.
00070   std::vector<LoopT *> SubLoops;
00071 
00072   // Blocks - The list of blocks in this loop.  First entry is the header node.
00073   std::vector<BlockT*> Blocks;
00074 
00075   SmallPtrSet<const BlockT*, 8> DenseBlockSet;
00076 
00077   LoopBase(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
00078   const LoopBase<BlockT, LoopT>&
00079     operator=(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
00080 public:
00081   /// Loop ctor - This creates an empty loop.
00082   LoopBase() : ParentLoop(nullptr) {}
00083   ~LoopBase() {
00084     for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
00085       delete SubLoops[i];
00086   }
00087 
00088   /// getLoopDepth - Return the nesting level of this loop.  An outer-most
00089   /// loop has depth 1, for consistency with loop depth values used for basic
00090   /// blocks, where depth 0 is used for blocks not inside any loops.
00091   unsigned getLoopDepth() const {
00092     unsigned D = 1;
00093     for (const LoopT *CurLoop = ParentLoop; CurLoop;
00094          CurLoop = CurLoop->ParentLoop)
00095       ++D;
00096     return D;
00097   }
00098   BlockT *getHeader() const { return Blocks.front(); }
00099   LoopT *getParentLoop() const { return ParentLoop; }
00100 
00101   /// setParentLoop is a raw interface for bypassing addChildLoop.
00102   void setParentLoop(LoopT *L) { ParentLoop = L; }
00103 
00104   /// contains - Return true if the specified loop is contained within in
00105   /// this loop.
00106   ///
00107   bool contains(const LoopT *L) const {
00108     if (L == this) return true;
00109     if (!L)        return false;
00110     return contains(L->getParentLoop());
00111   }
00112 
00113   /// contains - Return true if the specified basic block is in this loop.
00114   ///
00115   bool contains(const BlockT *BB) const {
00116     return DenseBlockSet.count(BB);
00117   }
00118 
00119   /// contains - Return true if the specified instruction is in this loop.
00120   ///
00121   template<class InstT>
00122   bool contains(const InstT *Inst) const {
00123     return contains(Inst->getParent());
00124   }
00125 
00126   /// iterator/begin/end - Return the loops contained entirely within this loop.
00127   ///
00128   const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
00129   std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
00130   typedef typename std::vector<LoopT *>::const_iterator iterator;
00131   typedef typename std::vector<LoopT *>::const_reverse_iterator
00132     reverse_iterator;
00133   iterator begin() const { return SubLoops.begin(); }
00134   iterator end() const { return SubLoops.end(); }
00135   reverse_iterator rbegin() const { return SubLoops.rbegin(); }
00136   reverse_iterator rend() const { return SubLoops.rend(); }
00137   bool empty() const { return SubLoops.empty(); }
00138 
00139   /// getBlocks - Get a list of the basic blocks which make up this loop.
00140   ///
00141   const std::vector<BlockT*> &getBlocks() const { return Blocks; }
00142   typedef typename std::vector<BlockT*>::const_iterator block_iterator;
00143   block_iterator block_begin() const { return Blocks.begin(); }
00144   block_iterator block_end() const { return Blocks.end(); }
00145 
00146   /// getNumBlocks - Get the number of blocks in this loop in constant time.
00147   unsigned getNumBlocks() const {
00148     return Blocks.size();
00149   }
00150 
00151   /// isLoopExiting - True if terminator in the block can branch to another
00152   /// block that is outside of the current loop.
00153   ///
00154   bool isLoopExiting(const BlockT *BB) const {
00155     typedef GraphTraits<const BlockT*> BlockTraits;
00156     for (typename BlockTraits::ChildIteratorType SI =
00157          BlockTraits::child_begin(BB),
00158          SE = BlockTraits::child_end(BB); SI != SE; ++SI) {
00159       if (!contains(*SI))
00160         return true;
00161     }
00162     return false;
00163   }
00164 
00165   /// getNumBackEdges - Calculate the number of back edges to the loop header
00166   ///
00167   unsigned getNumBackEdges() const {
00168     unsigned NumBackEdges = 0;
00169     BlockT *H = getHeader();
00170 
00171     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00172     for (typename InvBlockTraits::ChildIteratorType I =
00173          InvBlockTraits::child_begin(H),
00174          E = InvBlockTraits::child_end(H); I != E; ++I)
00175       if (contains(*I))
00176         ++NumBackEdges;
00177 
00178     return NumBackEdges;
00179   }
00180 
00181   //===--------------------------------------------------------------------===//
00182   // APIs for simple analysis of the loop.
00183   //
00184   // Note that all of these methods can fail on general loops (ie, there may not
00185   // be a preheader, etc).  For best success, the loop simplification and
00186   // induction variable canonicalization pass should be used to normalize loops
00187   // for easy analysis.  These methods assume canonical loops.
00188 
00189   /// getExitingBlocks - Return all blocks inside the loop that have successors
00190   /// outside of the loop.  These are the blocks _inside of the current loop_
00191   /// which branch out.  The returned list is always unique.
00192   ///
00193   void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
00194 
00195   /// getExitingBlock - If getExitingBlocks would return exactly one block,
00196   /// return that block. Otherwise return null.
00197   BlockT *getExitingBlock() const;
00198 
00199   /// getExitBlocks - Return all of the successor blocks of this loop.  These
00200   /// are the blocks _outside of the current loop_ which are branched to.
00201   ///
00202   void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
00203 
00204   /// getExitBlock - If getExitBlocks would return exactly one block,
00205   /// return that block. Otherwise return null.
00206   BlockT *getExitBlock() const;
00207 
00208   /// Edge type.
00209   typedef std::pair<const BlockT*, const BlockT*> Edge;
00210 
00211   /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
00212   void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
00213 
00214   /// getLoopPreheader - If there is a preheader for this loop, return it.  A
00215   /// loop has a preheader if there is only one edge to the header of the loop
00216   /// from outside of the loop.  If this is the case, the block branching to the
00217   /// header of the loop is the preheader node.
00218   ///
00219   /// This method returns null if there is no preheader for the loop.
00220   ///
00221   BlockT *getLoopPreheader() const;
00222 
00223   /// getLoopPredecessor - If the given loop's header has exactly one unique
00224   /// predecessor outside the loop, return it. Otherwise return null.
00225   /// This is less strict that the loop "preheader" concept, which requires
00226   /// the predecessor to have exactly one successor.
00227   ///
00228   BlockT *getLoopPredecessor() const;
00229 
00230   /// getLoopLatch - If there is a single latch block for this loop, return it.
00231   /// A latch block is a block that contains a branch back to the header.
00232   BlockT *getLoopLatch() const;
00233 
00234   /// getLoopLatches - Return all loop latch blocks of this loop. A latch block
00235   /// is a block that contains a branch back to the header.
00236   void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
00237     BlockT *H = getHeader();
00238     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00239     for (typename InvBlockTraits::ChildIteratorType I =
00240          InvBlockTraits::child_begin(H),
00241          E = InvBlockTraits::child_end(H); I != E; ++I)
00242       if (contains(*I))
00243         LoopLatches.push_back(*I);
00244   }
00245 
00246   //===--------------------------------------------------------------------===//
00247   // APIs for updating loop information after changing the CFG
00248   //
00249 
00250   /// addBasicBlockToLoop - This method is used by other analyses to update loop
00251   /// information.  NewBB is set to be a new member of the current loop.
00252   /// Because of this, it is added as a member of all parent loops, and is added
00253   /// to the specified LoopInfo object as being in the current basic block.  It
00254   /// is not valid to replace the loop header with this method.
00255   ///
00256   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
00257 
00258   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
00259   /// the OldChild entry in our children list with NewChild, and updates the
00260   /// parent pointer of OldChild to be null and the NewChild to be this loop.
00261   /// This updates the loop depth of the new child.
00262   void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
00263 
00264   /// addChildLoop - Add the specified loop to be a child of this loop.  This
00265   /// updates the loop depth of the new child.
00266   ///
00267   void addChildLoop(LoopT *NewChild) {
00268     assert(!NewChild->ParentLoop && "NewChild already has a parent!");
00269     NewChild->ParentLoop = static_cast<LoopT *>(this);
00270     SubLoops.push_back(NewChild);
00271   }
00272 
00273   /// removeChildLoop - This removes the specified child from being a subloop of
00274   /// this loop.  The loop is not deleted, as it will presumably be inserted
00275   /// into another loop.
00276   LoopT *removeChildLoop(iterator I) {
00277     assert(I != SubLoops.end() && "Cannot remove end iterator!");
00278     LoopT *Child = *I;
00279     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
00280     SubLoops.erase(SubLoops.begin()+(I-begin()));
00281     Child->ParentLoop = nullptr;
00282     return Child;
00283   }
00284 
00285   /// addBlockEntry - This adds a basic block directly to the basic block list.
00286   /// This should only be used by transformations that create new loops.  Other
00287   /// transformations should use addBasicBlockToLoop.
00288   void addBlockEntry(BlockT *BB) {
00289     Blocks.push_back(BB);
00290     DenseBlockSet.insert(BB);
00291   }
00292 
00293   /// reverseBlocks - interface to reverse Blocks[from, end of loop] in this loop
00294   void reverseBlock(unsigned from) {
00295     std::reverse(Blocks.begin() + from, Blocks.end());
00296   }
00297 
00298   /// reserveBlocks- interface to do reserve() for Blocks
00299   void reserveBlocks(unsigned size) {
00300     Blocks.reserve(size);
00301   }
00302 
00303   /// moveToHeader - This method is used to move BB (which must be part of this
00304   /// loop) to be the loop header of the loop (the block that dominates all
00305   /// others).
00306   void moveToHeader(BlockT *BB) {
00307     if (Blocks[0] == BB) return;
00308     for (unsigned i = 0; ; ++i) {
00309       assert(i != Blocks.size() && "Loop does not contain BB!");
00310       if (Blocks[i] == BB) {
00311         Blocks[i] = Blocks[0];
00312         Blocks[0] = BB;
00313         return;
00314       }
00315     }
00316   }
00317 
00318   /// removeBlockFromLoop - This removes the specified basic block from the
00319   /// current loop, updating the Blocks as appropriate.  This does not update
00320   /// the mapping in the LoopInfo class.
00321   void removeBlockFromLoop(BlockT *BB) {
00322     RemoveFromVector(Blocks, BB);
00323     DenseBlockSet.erase(BB);
00324   }
00325 
00326   /// verifyLoop - Verify loop structure
00327   void verifyLoop() const;
00328 
00329   /// verifyLoop - Verify loop structure of this loop and all nested loops.
00330   void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
00331 
00332   void print(raw_ostream &OS, unsigned Depth = 0) const;
00333 
00334 protected:
00335   friend class LoopInfoBase<BlockT, LoopT>;
00336   explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
00337     Blocks.push_back(BB);
00338     DenseBlockSet.insert(BB);
00339   }
00340 };
00341 
00342 template<class BlockT, class LoopT>
00343 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
00344   Loop.print(OS);
00345   return OS;
00346 }
00347 
00348 // Implementation in LoopInfoImpl.h
00349 #ifdef __GNUC__
00350 __extension__ extern template class LoopBase<BasicBlock, Loop>;
00351 #endif
00352 
00353 class Loop : public LoopBase<BasicBlock, Loop> {
00354 public:
00355   Loop() {}
00356 
00357   /// isLoopInvariant - Return true if the specified value is loop invariant
00358   ///
00359   bool isLoopInvariant(Value *V) const;
00360 
00361   /// hasLoopInvariantOperands - Return true if all the operands of the
00362   /// specified instruction are loop invariant.
00363   bool hasLoopInvariantOperands(Instruction *I) const;
00364 
00365   /// makeLoopInvariant - If the given value is an instruction inside of the
00366   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
00367   /// Return true if the value after any hoisting is loop invariant. This
00368   /// function can be used as a slightly more aggressive replacement for
00369   /// isLoopInvariant.
00370   ///
00371   /// If InsertPt is specified, it is the point to hoist instructions to.
00372   /// If null, the terminator of the loop preheader is used.
00373   ///
00374   bool makeLoopInvariant(Value *V, bool &Changed,
00375                          Instruction *InsertPt = nullptr) const;
00376 
00377   /// makeLoopInvariant - If the given instruction is inside of the
00378   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
00379   /// Return true if the instruction after any hoisting is loop invariant. This
00380   /// function can be used as a slightly more aggressive replacement for
00381   /// isLoopInvariant.
00382   ///
00383   /// If InsertPt is specified, it is the point to hoist instructions to.
00384   /// If null, the terminator of the loop preheader is used.
00385   ///
00386   bool makeLoopInvariant(Instruction *I, bool &Changed,
00387                          Instruction *InsertPt = nullptr) const;
00388 
00389   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
00390   /// induction variable: an integer recurrence that starts at 0 and increments
00391   /// by one each time through the loop.  If so, return the phi node that
00392   /// corresponds to it.
00393   ///
00394   /// The IndVarSimplify pass transforms loops to have a canonical induction
00395   /// variable.
00396   ///
00397   PHINode *getCanonicalInductionVariable() const;
00398 
00399   /// isLCSSAForm - Return true if the Loop is in LCSSA form
00400   bool isLCSSAForm(DominatorTree &DT) const;
00401 
00402   /// isLoopSimplifyForm - Return true if the Loop is in the form that
00403   /// the LoopSimplify form transforms loops to, which is sometimes called
00404   /// normal form.
00405   bool isLoopSimplifyForm() const;
00406 
00407   /// isSafeToClone - Return true if the loop body is safe to clone in practice.
00408   bool isSafeToClone() const;
00409 
00410   /// Returns true if the loop is annotated parallel.
00411   ///
00412   /// A parallel loop can be assumed to not contain any dependencies between
00413   /// iterations by the compiler. That is, any loop-carried dependency checking
00414   /// can be skipped completely when parallelizing the loop on the target
00415   /// machine. Thus, if the parallel loop information originates from the
00416   /// programmer, e.g. via the OpenMP parallel for pragma, it is the
00417   /// programmer's responsibility to ensure there are no loop-carried
00418   /// dependencies. The final execution order of the instructions across
00419   /// iterations is not guaranteed, thus, the end result might or might not
00420   /// implement actual concurrent execution of instructions across multiple
00421   /// iterations.
00422   bool isAnnotatedParallel() const;
00423 
00424   /// Return the llvm.loop loop id metadata node for this loop if it is present.
00425   ///
00426   /// If this loop contains the same llvm.loop metadata on each branch to the
00427   /// header then the node is returned. If any latch instruction does not
00428   /// contain llvm.loop or or if multiple latches contain different nodes then
00429   /// 0 is returned.
00430   MDNode *getLoopID() const;
00431   /// Set the llvm.loop loop id metadata for this loop.
00432   ///
00433   /// The LoopID metadata node will be added to each terminator instruction in
00434   /// the loop that branches to the loop header.
00435   ///
00436   /// The LoopID metadata node should have one or more operands and the first
00437   /// operand should should be the node itself.
00438   void setLoopID(MDNode *LoopID) const;
00439 
00440   /// hasDedicatedExits - Return true if no exit block for the loop
00441   /// has a predecessor that is outside the loop.
00442   bool hasDedicatedExits() const;
00443 
00444   /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
00445   /// These are the blocks _outside of the current loop_ which are branched to.
00446   /// This assumes that loop exits are in canonical form.
00447   ///
00448   void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
00449 
00450   /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
00451   /// block, return that block. Otherwise return null.
00452   BasicBlock *getUniqueExitBlock() const;
00453 
00454   void dump() const;
00455 
00456   /// \brief Return the debug location of the start of this loop.
00457   /// This looks for a BB terminating instruction with a known debug
00458   /// location by looking at the preheader and header blocks. If it
00459   /// cannot find a terminating instruction with location information,
00460   /// it returns an unknown location.
00461   DebugLoc getStartLoc() const {
00462     DebugLoc StartLoc;
00463     BasicBlock *HeadBB;
00464 
00465     // Try the pre-header first.
00466     if ((HeadBB = getLoopPreheader()) != nullptr) {
00467       StartLoc = HeadBB->getTerminator()->getDebugLoc();
00468       if (!StartLoc.isUnknown())
00469         return StartLoc;
00470     }
00471 
00472     // If we have no pre-header or there are no instructions with debug
00473     // info in it, try the header.
00474     HeadBB = getHeader();
00475     if (HeadBB)
00476       StartLoc = HeadBB->getTerminator()->getDebugLoc();
00477 
00478     return StartLoc;
00479   }
00480 
00481 private:
00482   friend class LoopInfoBase<BasicBlock, Loop>;
00483   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
00484 };
00485 
00486 //===----------------------------------------------------------------------===//
00487 /// LoopInfo - This class builds and contains all of the top level loop
00488 /// structures in the specified function.
00489 ///
00490 
00491 template<class BlockT, class LoopT>
00492 class LoopInfoBase {
00493   // BBMap - Mapping of basic blocks to the inner most loop they occur in
00494   DenseMap<BlockT *, LoopT *> BBMap;
00495   std::vector<LoopT *> TopLevelLoops;
00496   friend class LoopBase<BlockT, LoopT>;
00497   friend class LoopInfo;
00498 
00499   void operator=(const LoopInfoBase &) LLVM_DELETED_FUNCTION;
00500   LoopInfoBase(const LoopInfo &) LLVM_DELETED_FUNCTION;
00501 public:
00502   LoopInfoBase() { }
00503   ~LoopInfoBase() { releaseMemory(); }
00504 
00505   void releaseMemory() {
00506     for (typename std::vector<LoopT *>::iterator I =
00507          TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
00508       delete *I;   // Delete all of the loops...
00509 
00510     BBMap.clear();                           // Reset internal state of analysis
00511     TopLevelLoops.clear();
00512   }
00513 
00514   /// iterator/begin/end - The interface to the top-level loops in the current
00515   /// function.
00516   ///
00517   typedef typename std::vector<LoopT *>::const_iterator iterator;
00518   typedef typename std::vector<LoopT *>::const_reverse_iterator
00519     reverse_iterator;
00520   iterator begin() const { return TopLevelLoops.begin(); }
00521   iterator end() const { return TopLevelLoops.end(); }
00522   reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
00523   reverse_iterator rend() const { return TopLevelLoops.rend(); }
00524   bool empty() const { return TopLevelLoops.empty(); }
00525 
00526   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
00527   /// block is in no loop (for example the entry node), null is returned.
00528   ///
00529   LoopT *getLoopFor(const BlockT *BB) const {
00530     return BBMap.lookup(const_cast<BlockT*>(BB));
00531   }
00532 
00533   /// operator[] - same as getLoopFor...
00534   ///
00535   const LoopT *operator[](const BlockT *BB) const {
00536     return getLoopFor(BB);
00537   }
00538 
00539   /// getLoopDepth - Return the loop nesting level of the specified block.  A
00540   /// depth of 0 means the block is not inside any loop.
00541   ///
00542   unsigned getLoopDepth(const BlockT *BB) const {
00543     const LoopT *L = getLoopFor(BB);
00544     return L ? L->getLoopDepth() : 0;
00545   }
00546 
00547   // isLoopHeader - True if the block is a loop header node
00548   bool isLoopHeader(BlockT *BB) const {
00549     const LoopT *L = getLoopFor(BB);
00550     return L && L->getHeader() == BB;
00551   }
00552 
00553   /// removeLoop - This removes the specified top-level loop from this loop info
00554   /// object.  The loop is not deleted, as it will presumably be inserted into
00555   /// another loop.
00556   LoopT *removeLoop(iterator I) {
00557     assert(I != end() && "Cannot remove end iterator!");
00558     LoopT *L = *I;
00559     assert(!L->getParentLoop() && "Not a top-level loop!");
00560     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
00561     return L;
00562   }
00563 
00564   /// changeLoopFor - Change the top-level loop that contains BB to the
00565   /// specified loop.  This should be used by transformations that restructure
00566   /// the loop hierarchy tree.
00567   void changeLoopFor(BlockT *BB, LoopT *L) {
00568     if (!L) {
00569       BBMap.erase(BB);
00570       return;
00571     }
00572     BBMap[BB] = L;
00573   }
00574 
00575   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
00576   /// list with the indicated loop.
00577   void changeTopLevelLoop(LoopT *OldLoop,
00578                           LoopT *NewLoop) {
00579     typename std::vector<LoopT *>::iterator I =
00580                  std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
00581     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
00582     *I = NewLoop;
00583     assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
00584            "Loops already embedded into a subloop!");
00585   }
00586 
00587   /// addTopLevelLoop - This adds the specified loop to the collection of
00588   /// top-level loops.
00589   void addTopLevelLoop(LoopT *New) {
00590     assert(!New->getParentLoop() && "Loop already in subloop!");
00591     TopLevelLoops.push_back(New);
00592   }
00593 
00594   /// removeBlock - This method completely removes BB from all data structures,
00595   /// including all of the Loop objects it is nested in and our mapping from
00596   /// BasicBlocks to loops.
00597   void removeBlock(BlockT *BB) {
00598     typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
00599     if (I != BBMap.end()) {
00600       for (LoopT *L = I->second; L; L = L->getParentLoop())
00601         L->removeBlockFromLoop(BB);
00602 
00603       BBMap.erase(I);
00604     }
00605   }
00606 
00607   // Internals
00608 
00609   static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
00610                                       const LoopT *ParentLoop) {
00611     if (!SubLoop) return true;
00612     if (SubLoop == ParentLoop) return false;
00613     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
00614   }
00615 
00616   /// Create the loop forest using a stable algorithm.
00617   void Analyze(DominatorTreeBase<BlockT> &DomTree);
00618 
00619   // Debugging
00620 
00621   void print(raw_ostream &OS) const;
00622 };
00623 
00624 // Implementation in LoopInfoImpl.h
00625 #ifdef __GNUC__
00626 __extension__ extern template class LoopInfoBase<BasicBlock, Loop>;
00627 #endif
00628 
00629 class LoopInfo : public FunctionPass {
00630   LoopInfoBase<BasicBlock, Loop> LI;
00631   friend class LoopBase<BasicBlock, Loop>;
00632 
00633   void operator=(const LoopInfo &) LLVM_DELETED_FUNCTION;
00634   LoopInfo(const LoopInfo &) LLVM_DELETED_FUNCTION;
00635 public:
00636   static char ID; // Pass identification, replacement for typeid
00637 
00638   LoopInfo() : FunctionPass(ID) {
00639     initializeLoopInfoPass(*PassRegistry::getPassRegistry());
00640   }
00641 
00642   LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
00643 
00644   /// iterator/begin/end - The interface to the top-level loops in the current
00645   /// function.
00646   ///
00647   typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
00648   typedef LoopInfoBase<BasicBlock, Loop>::reverse_iterator reverse_iterator;
00649   inline iterator begin() const { return LI.begin(); }
00650   inline iterator end() const { return LI.end(); }
00651   inline reverse_iterator rbegin() const { return LI.rbegin(); }
00652   inline reverse_iterator rend() const { return LI.rend(); }
00653   bool empty() const { return LI.empty(); }
00654 
00655   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
00656   /// block is in no loop (for example the entry node), null is returned.
00657   ///
00658   inline Loop *getLoopFor(const BasicBlock *BB) const {
00659     return LI.getLoopFor(BB);
00660   }
00661 
00662   /// operator[] - same as getLoopFor...
00663   ///
00664   inline const Loop *operator[](const BasicBlock *BB) const {
00665     return LI.getLoopFor(BB);
00666   }
00667 
00668   /// getLoopDepth - Return the loop nesting level of the specified block.  A
00669   /// depth of 0 means the block is not inside any loop.
00670   ///
00671   inline unsigned getLoopDepth(const BasicBlock *BB) const {
00672     return LI.getLoopDepth(BB);
00673   }
00674 
00675   // isLoopHeader - True if the block is a loop header node
00676   inline bool isLoopHeader(BasicBlock *BB) const {
00677     return LI.isLoopHeader(BB);
00678   }
00679 
00680   /// runOnFunction - Calculate the natural loop information.
00681   ///
00682   bool runOnFunction(Function &F) override;
00683 
00684   void verifyAnalysis() const override;
00685 
00686   void releaseMemory() override { LI.releaseMemory(); }
00687 
00688   void print(raw_ostream &O, const Module* M = nullptr) const override;
00689 
00690   void getAnalysisUsage(AnalysisUsage &AU) const override;
00691 
00692   /// removeLoop - This removes the specified top-level loop from this loop info
00693   /// object.  The loop is not deleted, as it will presumably be inserted into
00694   /// another loop.
00695   inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
00696 
00697   /// changeLoopFor - Change the top-level loop that contains BB to the
00698   /// specified loop.  This should be used by transformations that restructure
00699   /// the loop hierarchy tree.
00700   inline void changeLoopFor(BasicBlock *BB, Loop *L) {
00701     LI.changeLoopFor(BB, L);
00702   }
00703 
00704   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
00705   /// list with the indicated loop.
00706   inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
00707     LI.changeTopLevelLoop(OldLoop, NewLoop);
00708   }
00709 
00710   /// addTopLevelLoop - This adds the specified loop to the collection of
00711   /// top-level loops.
00712   inline void addTopLevelLoop(Loop *New) {
00713     LI.addTopLevelLoop(New);
00714   }
00715 
00716   /// removeBlock - This method completely removes BB from all data structures,
00717   /// including all of the Loop objects it is nested in and our mapping from
00718   /// BasicBlocks to loops.
00719   void removeBlock(BasicBlock *BB) {
00720     LI.removeBlock(BB);
00721   }
00722 
00723   /// updateUnloop - Update LoopInfo after removing the last backedge from a
00724   /// loop--now the "unloop". This updates the loop forest and parent loops for
00725   /// each block so that Unloop is no longer referenced, but the caller must
00726   /// actually delete the Unloop object.
00727   void updateUnloop(Loop *Unloop);
00728 
00729   /// replacementPreservesLCSSAForm - Returns true if replacing From with To
00730   /// everywhere is guaranteed to preserve LCSSA form.
00731   bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
00732     // Preserving LCSSA form is only problematic if the replacing value is an
00733     // instruction.
00734     Instruction *I = dyn_cast<Instruction>(To);
00735     if (!I) return true;
00736     // If both instructions are defined in the same basic block then replacement
00737     // cannot break LCSSA form.
00738     if (I->getParent() == From->getParent())
00739       return true;
00740     // If the instruction is not defined in a loop then it can safely replace
00741     // anything.
00742     Loop *ToLoop = getLoopFor(I->getParent());
00743     if (!ToLoop) return true;
00744     // If the replacing instruction is defined in the same loop as the original
00745     // instruction, or in a loop that contains it as an inner loop, then using
00746     // it as a replacement will not break LCSSA form.
00747     return ToLoop->contains(getLoopFor(From->getParent()));
00748   }
00749 };
00750 
00751 
00752 // Allow clients to walk the list of nested loops...
00753 template <> struct GraphTraits<const Loop*> {
00754   typedef const Loop NodeType;
00755   typedef LoopInfo::iterator ChildIteratorType;
00756 
00757   static NodeType *getEntryNode(const Loop *L) { return L; }
00758   static inline ChildIteratorType child_begin(NodeType *N) {
00759     return N->begin();
00760   }
00761   static inline ChildIteratorType child_end(NodeType *N) {
00762     return N->end();
00763   }
00764 };
00765 
00766 template <> struct GraphTraits<Loop*> {
00767   typedef Loop NodeType;
00768   typedef LoopInfo::iterator ChildIteratorType;
00769 
00770   static NodeType *getEntryNode(Loop *L) { return L; }
00771   static inline ChildIteratorType child_begin(NodeType *N) {
00772     return N->begin();
00773   }
00774   static inline ChildIteratorType child_end(NodeType *N) {
00775     return N->end();
00776   }
00777 };
00778 
00779 } // End llvm namespace
00780 
00781 #endif