LCOV - code coverage report
Current view: top level - include/llvm/Analysis - LoopInfo.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 147 213 69.0 %
Date: 2017-09-14 15:23:50 Functions: 28 119 23.5 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
       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.  A natural loop
      12             : // has exactly one entry-point, which is called the header. Note that natural
      13             : // loops may actually be several loops that share the same header node.
      14             : //
      15             : // This analysis calculates the nesting structure of loops in a function.  For
      16             : // each natural loop identified, this analysis identifies natural loops
      17             : // contained entirely within the loop and the basic blocks the make up the loop.
      18             : //
      19             : // It can calculate on the fly various bits of information, for example:
      20             : //
      21             : //  * whether there is a preheader for the loop
      22             : //  * the number of back edges to the header
      23             : //  * whether or not a particular block branches out of the loop
      24             : //  * the successor blocks of the loop
      25             : //  * the loop depth
      26             : //  * etc...
      27             : //
      28             : // Note that this analysis specifically identifies *Loops* not cycles or SCCs
      29             : // in the CFG.  There can be strongly connected components in the CFG which
      30             : // this analysis will not recognize and that will not be represented by a Loop
      31             : // instance.  In particular, a Loop might be inside such a non-loop SCC, or a
      32             : // non-loop SCC might contain a sub-SCC which is a Loop. 
      33             : //
      34             : //===----------------------------------------------------------------------===//
      35             : 
      36             : #ifndef LLVM_ANALYSIS_LOOPINFO_H
      37             : #define LLVM_ANALYSIS_LOOPINFO_H
      38             : 
      39             : #include "llvm/ADT/DenseMap.h"
      40             : #include "llvm/ADT/DenseSet.h"
      41             : #include "llvm/ADT/GraphTraits.h"
      42             : #include "llvm/ADT/SmallPtrSet.h"
      43             : #include "llvm/ADT/SmallVector.h"
      44             : #include "llvm/IR/CFG.h"
      45             : #include "llvm/IR/Instruction.h"
      46             : #include "llvm/IR/Instructions.h"
      47             : #include "llvm/IR/PassManager.h"
      48             : #include "llvm/Pass.h"
      49             : #include <algorithm>
      50             : 
      51             : namespace llvm {
      52             : 
      53             : class DominatorTree;
      54             : class LoopInfo;
      55             : class Loop;
      56             : class MDNode;
      57             : class PHINode;
      58             : class raw_ostream;
      59             : template <class N, bool IsPostDom>
      60             : class DominatorTreeBase;
      61             : template<class N, class M> class LoopInfoBase;
      62             : template<class N, class M> class LoopBase;
      63             : 
      64             : //===----------------------------------------------------------------------===//
      65             : /// Instances of this class are used to represent loops that are detected in the
      66             : /// flow graph.
      67             : ///
      68             : template<class BlockT, class LoopT>
      69             : class LoopBase {
      70             :   LoopT *ParentLoop;
      71             :   // Loops contained entirely within this one.
      72             :   std::vector<LoopT *> SubLoops;
      73             : 
      74             :   // The list of blocks in this loop. First entry is the header node.
      75             :   std::vector<BlockT*> Blocks;
      76             : 
      77             :   SmallPtrSet<const BlockT*, 8> DenseBlockSet;
      78             : 
      79             :   /// Indicator that this loop is no longer a valid loop.
      80             :   bool IsInvalid = false;
      81             : 
      82             :   LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
      83             :   const LoopBase<BlockT, LoopT>&
      84             :     operator=(const LoopBase<BlockT, LoopT> &) = delete;
      85             : public:
      86             :   /// This creates an empty loop.
      87        6148 :   LoopBase() : ParentLoop(nullptr) {}
      88      111054 :   ~LoopBase() {
      89      238634 :     for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
      90       33052 :       delete SubLoops[i];
      91      444216 :   }
      92             : 
      93             :   /// Return the nesting level of this loop.  An outer-most loop has depth 1,
      94             :   /// for consistency with loop depth values used for basic blocks, where depth
      95             :   /// 0 is used for blocks not inside any loops.
      96           0 :   unsigned getLoopDepth() const {
      97       85631 :     unsigned D = 1;
      98      104177 :     for (const LoopT *CurLoop = ParentLoop; CurLoop;
      99             :          CurLoop = CurLoop->ParentLoop)
     100       18546 :       ++D;
     101           0 :     return D;
     102             :   }
     103     8428732 :   BlockT *getHeader() const { return Blocks.front(); }
     104      878813 :   LoopT *getParentLoop() const { return ParentLoop; }
     105             : 
     106             :   /// This is a raw interface for bypassing addChildLoop.
     107       16513 :   void setParentLoop(LoopT *L) { ParentLoop = L; }
     108             : 
     109             :   /// Return true if the specified loop is contained within in this loop.
     110           0 :   bool contains(const LoopT *L) const {
     111      780854 :     if (L == this) return true;
     112      612663 :     if (!L)        return false;
     113      346215 :     return contains(L->getParentLoop());
     114             :   }
     115             : 
     116             :   /// Return true if the specified basic block is in this loop.
     117           0 :   bool contains(const BlockT *BB) const {
     118    11170593 :     return DenseBlockSet.count(BB);
     119             :   }
     120             : 
     121             :   /// Return true if the specified instruction is in this loop.
     122             :   template<class InstT>
     123             :   bool contains(const InstT *Inst) const {
     124     2743990 :     return contains(Inst->getParent());
     125             :   }
     126             : 
     127             :   /// Return the loops contained entirely within this loop.
     128          55 :   const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
     129      126976 :   std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
     130             :   typedef typename std::vector<LoopT *>::const_iterator iterator;
     131             :   typedef typename std::vector<LoopT *>::const_reverse_iterator
     132             :     reverse_iterator;
     133      132261 :   iterator begin() const { return SubLoops.begin(); }
     134      133200 :   iterator end() const { return SubLoops.end(); }
     135       52876 :   reverse_iterator rbegin() const { return SubLoops.rbegin(); }
     136       52876 :   reverse_iterator rend() const { return SubLoops.rend(); }
     137       58654 :   bool empty() const { return SubLoops.empty(); }
     138             : 
     139             :   /// Get a list of the basic blocks which make up this loop.
     140        7785 :   const std::vector<BlockT*> &getBlocks() const { return Blocks; }
     141             :   typedef typename std::vector<BlockT*>::const_iterator block_iterator;
     142      791450 :   block_iterator block_begin() const { return Blocks.begin(); }
     143      791038 :   block_iterator block_end() const { return Blocks.end(); }
     144           0 :   inline iterator_range<block_iterator> blocks() const {
     145     2193507 :     return make_range(block_begin(), block_end());
     146             :   }
     147             : 
     148             :   /// Get the number of blocks in this loop in constant time.
     149           0 :   unsigned getNumBlocks() const {
     150       38688 :     return Blocks.size();
     151             :   }
     152             : 
     153             :   /// Invalidate the loop, indicating that it is no longer a loop.
     154         426 :   void invalidate() { IsInvalid = true; }
     155             : 
     156             :   /// Return true if this loop is no longer valid.
     157           0 :   bool isInvalid() { return IsInvalid; }
     158             : 
     159             :   /// True if terminator in the block can branch to another block that is
     160             :   /// outside of the current loop.
     161        1071 :   bool isLoopExiting(const BlockT *BB) const {
     162      851825 :     for (const auto &Succ : children<const BlockT*>(BB)) {
     163      690534 :       if (!contains(Succ))
     164         586 :         return true;
     165             :     }
     166         485 :     return false;
     167             :   }
     168             : 
     169             :   /// Returns true if \p BB is a loop-latch.
     170             :   /// A latch block is a block that contains a branch back to the header.
     171             :   /// This function is useful when there are multiple latches in a loop
     172             :   /// because \fn getLoopLatch will return nullptr in that case.
     173        1071 :   bool isLoopLatch(const BlockT *BB) const {
     174             :     assert(contains(BB) && "block does not belong to the loop");
     175             : 
     176        1071 :     BlockT *Header = getHeader();
     177        1071 :     auto PredBegin = GraphTraits<Inverse<BlockT*> >::child_begin(Header);
     178        1071 :     auto PredEnd = GraphTraits<Inverse<BlockT*> >::child_end(Header);
     179        2142 :     return std::find(PredBegin, PredEnd, BB) != PredEnd;
     180             :   }
     181             : 
     182             :   /// Calculate the number of back edges to the loop header.
     183           0 :   unsigned getNumBackEdges() const {
     184           0 :     unsigned NumBackEdges = 0;
     185           0 :     BlockT *H = getHeader();
     186             : 
     187           0 :     for (const auto Pred : children<Inverse<BlockT*> >(H))
     188           0 :       if (contains(Pred))
     189           0 :         ++NumBackEdges;
     190             : 
     191           0 :     return NumBackEdges;
     192             :   }
     193             : 
     194             :   //===--------------------------------------------------------------------===//
     195             :   // APIs for simple analysis of the loop.
     196             :   //
     197             :   // Note that all of these methods can fail on general loops (ie, there may not
     198             :   // be a preheader, etc).  For best success, the loop simplification and
     199             :   // induction variable canonicalization pass should be used to normalize loops
     200             :   // for easy analysis.  These methods assume canonical loops.
     201             : 
     202             :   /// Return all blocks inside the loop that have successors outside of the
     203             :   /// loop. These are the blocks _inside of the current loop_ which branch out.
     204             :   /// The returned list is always unique.
     205             :   void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
     206             : 
     207             :   /// If getExitingBlocks would return exactly one block, return that block.
     208             :   /// Otherwise return null.
     209             :   BlockT *getExitingBlock() const;
     210             : 
     211             :   /// Return all of the successor blocks of this loop. These are the blocks
     212             :   /// _outside of the current loop_ which are branched to.
     213             :   void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
     214             : 
     215             :   /// If getExitBlocks would return exactly one block, return that block.
     216             :   /// Otherwise return null.
     217             :   BlockT *getExitBlock() const;
     218             : 
     219             :   /// Edge type.
     220             :   typedef std::pair<const BlockT*, const BlockT*> Edge;
     221             : 
     222             :   /// Return all pairs of (_inside_block_,_outside_block_).
     223             :   void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
     224             : 
     225             :   /// If there is a preheader for this loop, return it. A loop has a preheader
     226             :   /// if there is only one edge to the header of the loop from outside of the
     227             :   /// loop. If this is the case, the block branching to the header of the loop
     228             :   /// is the preheader node.
     229             :   ///
     230             :   /// This method returns null if there is no preheader for the loop.
     231             :   BlockT *getLoopPreheader() const;
     232             : 
     233             :   /// If the given loop's header has exactly one unique predecessor outside the
     234             :   /// loop, return it. Otherwise return null.
     235             :   ///  This is less strict that the loop "preheader" concept, which requires
     236             :   /// the predecessor to have exactly one successor.
     237             :   BlockT *getLoopPredecessor() const;
     238             : 
     239             :   /// If there is a single latch block for this loop, return it.
     240             :   /// A latch block is a block that contains a branch back to the header.
     241             :   BlockT *getLoopLatch() const;
     242             : 
     243             :   /// Return all loop latch blocks of this loop. A latch block is a block that
     244             :   /// contains a branch back to the header.
     245        2371 :   void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
     246        2371 :     BlockT *H = getHeader();
     247       16601 :     for (const auto Pred : children<Inverse<BlockT*>>(H))
     248        9488 :       if (contains(Pred))
     249        2373 :         LoopLatches.push_back(Pred);
     250        2371 :   }
     251             : 
     252             :   //===--------------------------------------------------------------------===//
     253             :   // APIs for updating loop information after changing the CFG
     254             :   //
     255             : 
     256             :   /// This method is used by other analyses to update loop information.
     257             :   /// NewBB is set to be a new member of the current loop.
     258             :   /// Because of this, it is added as a member of all parent loops, and is added
     259             :   /// to the specified LoopInfo object as being in the current basic block.  It
     260             :   /// is not valid to replace the loop header with this method.
     261             :   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
     262             : 
     263             :   /// This is used when splitting loops up. It replaces the OldChild entry in
     264             :   /// our children list with NewChild, and updates the parent pointer of
     265             :   /// OldChild to be null and the NewChild to be this loop.
     266             :   /// This updates the loop depth of the new child.
     267             :   void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
     268             : 
     269             :   /// Add the specified loop to be a child of this loop.
     270             :   /// This updates the loop depth of the new child.
     271           0 :   void addChildLoop(LoopT *NewChild) {
     272             :     assert(!NewChild->ParentLoop && "NewChild already has a parent!");
     273         301 :     NewChild->ParentLoop = static_cast<LoopT *>(this);
     274         301 :     SubLoops.push_back(NewChild);
     275           0 :   }
     276             : 
     277             :   /// This removes the specified child from being a subloop of this loop. The
     278             :   /// loop is not deleted, as it will presumably be inserted into another loop.
     279           0 :   LoopT *removeChildLoop(iterator I) {
     280             :     assert(I != SubLoops.end() && "Cannot remove end iterator!");
     281         167 :     LoopT *Child = *I;
     282             :     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
     283        1169 :     SubLoops.erase(SubLoops.begin()+(I-begin()));
     284         157 :     Child->ParentLoop = nullptr;
     285           0 :     return Child;
     286             :   }
     287             : 
     288             :   /// This adds a basic block directly to the basic block list.
     289             :   /// This should only be used by transformations that create new loops.  Other
     290             :   /// transformations should use addBasicBlockToLoop.
     291      516290 :   void addBlockEntry(BlockT *BB) {
     292      516290 :     Blocks.push_back(BB);
     293      516290 :     DenseBlockSet.insert(BB);
     294      516290 :   }
     295             : 
     296             :   /// interface to reverse Blocks[from, end of loop] in this loop
     297           0 :   void reverseBlock(unsigned from) {
     298      551565 :     std::reverse(Blocks.begin() + from, Blocks.end());
     299           0 :   }
     300             : 
     301             :   /// interface to do reserve() for Blocks
     302           0 :   void reserveBlocks(unsigned size) {
     303      110313 :     Blocks.reserve(size);
     304           0 :   }
     305             : 
     306             :   /// This method is used to move BB (which must be part of this loop) to be the
     307             :   /// loop header of the loop (the block that dominates all others).
     308           0 :   void moveToHeader(BlockT *BB) {
     309        1900 :     if (Blocks[0] == BB) return;
     310        2267 :     for (unsigned i = 0; ; ++i) {
     311           0 :       assert(i != Blocks.size() && "Loop does not contain BB!");
     312        8334 :       if (Blocks[i] == BB) {
     313        1900 :         Blocks[i] = Blocks[0];
     314        1900 :         Blocks[0] = BB;
     315           0 :         return;
     316             :       }
     317             :     }
     318             :   }
     319             : 
     320             :   /// This removes the specified basic block from the current loop, updating the
     321             :   /// Blocks as appropriate. This does not update the mapping in the LoopInfo
     322             :   /// class.
     323         169 :   void removeBlockFromLoop(BlockT *BB) {
     324         338 :     auto I = find(Blocks, BB);
     325             :     assert(I != Blocks.end() && "N is not in this list!");
     326         507 :     Blocks.erase(I);
     327             : 
     328         338 :     DenseBlockSet.erase(BB);
     329         169 :   }
     330             : 
     331             :   /// Verify loop structure
     332             :   void verifyLoop() const;
     333             : 
     334             :   /// Verify loop structure of this loop and all nested loops.
     335             :   void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
     336             : 
     337             :   /// Print loop with all the BBs inside it.
     338             :   void print(raw_ostream &OS, unsigned Depth = 0, bool Verbose = false) const;
     339             : 
     340             : protected:
     341             :   friend class LoopInfoBase<BlockT, LoopT>;
     342      441252 :   explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
     343      110313 :     Blocks.push_back(BB);
     344      110313 :     DenseBlockSet.insert(BB);
     345      110313 :   }
     346             : };
     347             : 
     348             : template<class BlockT, class LoopT>
     349             : raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
     350         356 :   Loop.print(OS);
     351             :   return OS;
     352             : }
     353             : 
     354             : // Implementation in LoopInfoImpl.h
     355             : extern template class LoopBase<BasicBlock, Loop>;
     356             : 
     357             : 
     358             : /// Represents a single loop in the control flow graph.  Note that not all SCCs
     359             : /// in the CFG are necessarily loops.
     360       66841 : class Loop : public LoopBase<BasicBlock, Loop> {
     361             : public:
     362             :   /// \brief A range representing the start and end location of a loop.
     363       24645 :   class LocRange {
     364             :     DebugLoc Start;
     365             :     DebugLoc End;
     366             : 
     367             :   public:
     368           0 :     LocRange() {}
     369        8457 :     LocRange(DebugLoc Start) : Start(std::move(Start)), End(std::move(Start)) {}
     370       10792 :     LocRange(DebugLoc Start, DebugLoc End) : Start(std::move(Start)),
     371       16188 :                                              End(std::move(End)) {}
     372             : 
     373             :     const DebugLoc &getStart() const { return Start; }
     374             :     const DebugLoc &getEnd() const { return End; }
     375             : 
     376             :     /// \brief Check for null.
     377             :     ///
     378             :     explicit operator bool() const {
     379             :       return Start && End;
     380             :     }
     381             :   };
     382             : 
     383        3074 :   Loop() {}
     384             : 
     385             :   /// Return true if the specified value is loop invariant.
     386             :   bool isLoopInvariant(const Value *V) const;
     387             : 
     388             :   /// Return true if all the operands of the specified instruction are loop
     389             :   /// invariant.
     390             :   bool hasLoopInvariantOperands(const Instruction *I) const;
     391             : 
     392             :   /// If the given value is an instruction inside of the loop and it can be
     393             :   /// hoisted, do so to make it trivially loop-invariant.
     394             :   /// Return true if the value after any hoisting is loop invariant. This
     395             :   /// function can be used as a slightly more aggressive replacement for
     396             :   /// isLoopInvariant.
     397             :   ///
     398             :   /// If InsertPt is specified, it is the point to hoist instructions to.
     399             :   /// If null, the terminator of the loop preheader is used.
     400             :   bool makeLoopInvariant(Value *V, bool &Changed,
     401             :                          Instruction *InsertPt = nullptr) const;
     402             : 
     403             :   /// If the given instruction is inside of the loop and it can be hoisted, do
     404             :   /// so to make it trivially loop-invariant.
     405             :   /// Return true if the instruction after any hoisting is loop invariant. This
     406             :   /// function can be used as a slightly more aggressive replacement for
     407             :   /// isLoopInvariant.
     408             :   ///
     409             :   /// If InsertPt is specified, it is the point to hoist instructions to.
     410             :   /// If null, the terminator of the loop preheader is used.
     411             :   ///
     412             :   bool makeLoopInvariant(Instruction *I, bool &Changed,
     413             :                          Instruction *InsertPt = nullptr) const;
     414             : 
     415             :   /// Check to see if the loop has a canonical induction variable: an integer
     416             :   /// recurrence that starts at 0 and increments by one each time through the
     417             :   /// loop. If so, return the phi node that corresponds to it.
     418             :   ///
     419             :   /// The IndVarSimplify pass transforms loops to have a canonical induction
     420             :   /// variable.
     421             :   ///
     422             :   PHINode *getCanonicalInductionVariable() const;
     423             : 
     424             :   /// Return true if the Loop is in LCSSA form.
     425             :   bool isLCSSAForm(DominatorTree &DT) const;
     426             : 
     427             :   /// Return true if this Loop and all inner subloops are in LCSSA form.
     428             :   bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const;
     429             : 
     430             :   /// Return true if the Loop is in the form that the LoopSimplify form
     431             :   /// transforms loops to, which is sometimes called normal form.
     432             :   bool isLoopSimplifyForm() const;
     433             : 
     434             :   /// Return true if the loop body is safe to clone in practice.
     435             :   bool isSafeToClone() const;
     436             : 
     437             :   /// Returns true if the loop is annotated parallel.
     438             :   ///
     439             :   /// A parallel loop can be assumed to not contain any dependencies between
     440             :   /// iterations by the compiler. That is, any loop-carried dependency checking
     441             :   /// can be skipped completely when parallelizing the loop on the target
     442             :   /// machine. Thus, if the parallel loop information originates from the
     443             :   /// programmer, e.g. via the OpenMP parallel for pragma, it is the
     444             :   /// programmer's responsibility to ensure there are no loop-carried
     445             :   /// dependencies. The final execution order of the instructions across
     446             :   /// iterations is not guaranteed, thus, the end result might or might not
     447             :   /// implement actual concurrent execution of instructions across multiple
     448             :   /// iterations.
     449             :   bool isAnnotatedParallel() const;
     450             : 
     451             :   /// Return the llvm.loop loop id metadata node for this loop if it is present.
     452             :   ///
     453             :   /// If this loop contains the same llvm.loop metadata on each branch to the
     454             :   /// header then the node is returned. If any latch instruction does not
     455             :   /// contain llvm.loop or or if multiple latches contain different nodes then
     456             :   /// 0 is returned.
     457             :   MDNode *getLoopID() const;
     458             :   /// Set the llvm.loop loop id metadata for this loop.
     459             :   ///
     460             :   /// The LoopID metadata node will be added to each terminator instruction in
     461             :   /// the loop that branches to the loop header.
     462             :   ///
     463             :   /// The LoopID metadata node should have one or more operands and the first
     464             :   /// operand should be the node itself.
     465             :   void setLoopID(MDNode *LoopID) const;
     466             : 
     467             :   /// Return true if no exit block for the loop has a predecessor that is
     468             :   /// outside the loop.
     469             :   bool hasDedicatedExits() const;
     470             : 
     471             :   /// Return all unique successor blocks of this loop.
     472             :   /// These are the blocks _outside of the current loop_ which are branched to.
     473             :   /// This assumes that loop exits are in canonical form, i.e. all exits are
     474             :   /// dedicated exits.
     475             :   void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
     476             : 
     477             :   /// If getUniqueExitBlocks would return exactly one block, return that block.
     478             :   /// Otherwise return null.
     479             :   BasicBlock *getUniqueExitBlock() const;
     480             : 
     481             :   void dump() const;
     482             :   void dumpVerbose() const;
     483             : 
     484             :   /// Return the debug location of the start of this loop.
     485             :   /// This looks for a BB terminating instruction with a known debug
     486             :   /// location by looking at the preheader and header blocks. If it
     487             :   /// cannot find a terminating instruction with location information,
     488             :   /// it returns an unknown location.
     489             :   DebugLoc getStartLoc() const;
     490             : 
     491             :   /// Return the source code span of the loop.
     492             :   LocRange getLocRange() const;
     493             : 
     494         686 :   StringRef getName() const {
     495        1372 :     if (BasicBlock *Header = getHeader())
     496        1372 :       if (Header->hasName())
     497         686 :         return Header->getName();
     498           0 :     return "<unnamed loop>";
     499             :   }
     500             : 
     501             : private:
     502             :   friend class LoopInfoBase<BasicBlock, Loop>;
     503       66115 :   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
     504             : };
     505             : 
     506             : //===----------------------------------------------------------------------===//
     507             : /// This class builds and contains all of the top-level loop
     508             : /// structures in the specified function.
     509             : ///
     510             : 
     511             : template<class BlockT, class LoopT>
     512             : class LoopInfoBase {
     513             :   // BBMap - Mapping of basic blocks to the inner most loop they occur in
     514             :   DenseMap<const BlockT *, LoopT *> BBMap;
     515             :   std::vector<LoopT *> TopLevelLoops;
     516             :   std::vector<LoopT *> RemovedLoops;
     517             : 
     518             :   friend class LoopBase<BlockT, LoopT>;
     519             :   friend class LoopInfo;
     520             : 
     521             :   void operator=(const LoopInfoBase &) = delete;
     522             :   LoopInfoBase(const LoopInfoBase &) = delete;
     523             : public:
     524      779324 :   LoopInfoBase() { }
     525      767349 :   ~LoopInfoBase() { releaseMemory(); }
     526             : 
     527           0 :   LoopInfoBase(LoopInfoBase &&Arg)
     528           0 :       : BBMap(std::move(Arg.BBMap)),
     529           0 :         TopLevelLoops(std::move(Arg.TopLevelLoops)) {
     530             :     // We have to clear the arguments top level loops as we've taken ownership.
     531           0 :     Arg.TopLevelLoops.clear();
     532           0 :   }
     533           0 :   LoopInfoBase &operator=(LoopInfoBase &&RHS) {
     534           0 :     BBMap = std::move(RHS.BBMap);
     535             : 
     536           0 :     for (auto *L : TopLevelLoops)
     537           0 :       delete L;
     538           0 :     TopLevelLoops = std::move(RHS.TopLevelLoops);
     539           0 :     RHS.TopLevelLoops.clear();
     540           0 :     return *this;
     541             :   }
     542             : 
     543     3892038 :   void releaseMemory() {
     544     3892038 :     BBMap.clear();
     545             : 
     546    15662169 :     for (auto *L : TopLevelLoops)
     547      188042 :       delete L;
     548     7784074 :     TopLevelLoops.clear();
     549    15568533 :     for (auto *L : RemovedLoops)
     550         770 :       delete L;
     551     7784074 :     RemovedLoops.clear();
     552     3892037 :   }
     553             : 
     554             :   /// iterator/begin/end - The interface to the top-level loops in the current
     555             :   /// function.
     556             :   ///
     557             :   typedef typename std::vector<LoopT *>::const_iterator iterator;
     558             :   typedef typename std::vector<LoopT *>::const_reverse_iterator
     559             :     reverse_iterator;
     560     1196705 :   iterator begin() const { return TopLevelLoops.begin(); }
     561     1195999 :   iterator end() const { return TopLevelLoops.end(); }
     562      577118 :   reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
     563      577118 :   reverse_iterator rend() const { return TopLevelLoops.rend(); }
     564     1552640 :   bool empty() const { return TopLevelLoops.empty(); }
     565             : 
     566             :   /// Return all of the loops in the function in preorder across the loop
     567             :   /// nests, with siblings in forward program order.
     568             :   ///
     569             :   /// Note that because loops form a forest of trees, preorder is equivalent to
     570             :   /// reverse postorder.
     571             :   SmallVector<LoopT *, 4> getLoopsInPreorder();
     572             : 
     573             :   /// Return all of the loops in the function in preorder across the loop
     574             :   /// nests, with siblings in *reverse* program order.
     575             :   ///
     576             :   /// Note that because loops form a forest of trees, preorder is equivalent to
     577             :   /// reverse postorder.
     578             :   ///
     579             :   /// Also note that this is *not* a reverse preorder. Only the siblings are in
     580             :   /// reverse program order.
     581             :   SmallVector<LoopT *, 4> getLoopsInReverseSiblingPreorder();
     582             : 
     583             :   /// Return the inner most loop that BB lives in. If a basic block is in no
     584             :   /// loop (for example the entry node), null is returned.
     585    22707184 :   LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
     586             : 
     587             :   /// Same as getLoopFor.
     588           0 :   const LoopT *operator[](const BlockT *BB) const {
     589       30300 :     return getLoopFor(BB);
     590             :   }
     591             : 
     592             :   /// Return the loop nesting level of the specified block. A depth of 0 means
     593             :   /// the block is not inside any loop.
     594        4964 :   unsigned getLoopDepth(const BlockT *BB) const {
     595        4964 :     const LoopT *L = getLoopFor(BB);
     596        9506 :     return L ? L->getLoopDepth() : 0;
     597             :   }
     598             : 
     599             :   // True if the block is a loop header node
     600           0 :   bool isLoopHeader(const BlockT *BB) const {
     601           0 :     const LoopT *L = getLoopFor(BB);
     602           0 :     return L && L->getHeader() == BB;
     603             :   }
     604             : 
     605             :   /// This removes the specified top-level loop from this loop info object.
     606             :   /// The loop is not deleted, as it will presumably be inserted into
     607             :   /// another loop.
     608           0 :   LoopT *removeLoop(iterator I) {
     609             :     assert(I != end() && "Cannot remove end iterator!");
     610         352 :     LoopT *L = *I;
     611             :     assert(!L->getParentLoop() && "Not a top-level loop!");
     612        2464 :     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
     613           0 :     return L;
     614             :   }
     615             : 
     616             :   /// Change the top-level loop that contains BB to the specified loop.
     617             :   /// This should be used by transformations that restructure the loop hierarchy
     618             :   /// tree.
     619      511369 :   void changeLoopFor(BlockT *BB, LoopT *L) {
     620      511369 :     if (!L) {
     621        1526 :       BBMap.erase(BB);
     622          20 :       return;
     623             :     }
     624     1022698 :     BBMap[BB] = L;
     625             :   }
     626             : 
     627             :   /// Replace the specified loop in the top-level loops list with the indicated
     628             :   /// loop.
     629           0 :   void changeTopLevelLoop(LoopT *OldLoop,
     630             :                           LoopT *NewLoop) {
     631          72 :     auto I = find(TopLevelLoops, OldLoop);
     632             :     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
     633          36 :     *I = NewLoop;
     634             :     assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
     635             :            "Loops already embedded into a subloop!");
     636           0 :   }
     637             : 
     638             :   /// This adds the specified loop to the collection of top-level loops.
     639           0 :   void addTopLevelLoop(LoopT *New) {
     640             :     assert(!New->getParentLoop() && "Loop already in subloop!");
     641       95123 :     TopLevelLoops.push_back(New);
     642           0 :   }
     643             : 
     644             :   /// This method completely removes BB from all data structures,
     645             :   /// including all of the Loop objects it is nested in and our mapping from
     646             :   /// BasicBlocks to loops.
     647          85 :   void removeBlock(BlockT *BB) {
     648          85 :     auto I = BBMap.find(BB);
     649         255 :     if (I != BBMap.end()) {
     650         345 :       for (LoopT *L = I->second; L; L = L->getParentLoop())
     651         130 :         L->removeBlockFromLoop(BB);
     652             : 
     653          85 :       BBMap.erase(I);
     654             :     }
     655          85 :   }
     656             : 
     657             :   // Internals
     658             : 
     659           0 :   static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
     660             :                                       const LoopT *ParentLoop) {
     661           0 :     if (!SubLoop) return true;
     662           0 :     if (SubLoop == ParentLoop) return false;
     663           0 :     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
     664             :   }
     665             : 
     666             :   /// Create the loop forest using a stable algorithm.
     667             :   void analyze(const DominatorTreeBase<BlockT, false> &DomTree);
     668             : 
     669             :   // Debugging
     670             :   void print(raw_ostream &OS) const;
     671             : 
     672             :   void verify(const DominatorTreeBase<BlockT, false> &DomTree) const;
     673             : };
     674             : 
     675             : // Implementation in LoopInfoImpl.h
     676             : extern template class LoopInfoBase<BasicBlock, Loop>;
     677             : 
     678       91822 : class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
     679             :   typedef LoopInfoBase<BasicBlock, Loop> BaseT;
     680             : 
     681             :   friend class LoopBase<BasicBlock, Loop>;
     682             : 
     683             :   void operator=(const LoopInfo &) = delete;
     684             :   LoopInfo(const LoopInfo &) = delete;
     685             : public:
     686      177205 :   LoopInfo() {}
     687             :   explicit LoopInfo(const DominatorTreeBase<BasicBlock, false> &DomTree);
     688             : 
     689        2662 :   LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
     690             :   LoopInfo &operator=(LoopInfo &&RHS) {
     691             :     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
     692             :     return *this;
     693             :   }
     694             : 
     695             :   /// Handle invalidation explicitly.
     696             :   bool invalidate(Function &F, const PreservedAnalyses &PA,
     697             :                   FunctionAnalysisManager::Invalidator &);
     698             : 
     699             :   // Most of the public interface is provided via LoopInfoBase.
     700             : 
     701             :   /// Update LoopInfo after removing the last backedge from a loop. This updates
     702             :   /// the loop forest and parent loops for each block so that \c L is no longer
     703             :   /// referenced, but does not actually delete \c L immediately. The pointer
     704             :   /// will remain valid until this LoopInfo's memory is released.
     705             :   void markAsRemoved(Loop *L);
     706             : 
     707             :   /// Returns true if replacing From with To everywhere is guaranteed to
     708             :   /// preserve LCSSA form.
     709       31882 :   bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
     710             :     // Preserving LCSSA form is only problematic if the replacing value is an
     711             :     // instruction.
     712        2256 :     Instruction *I = dyn_cast<Instruction>(To);
     713             :     if (!I) return true;
     714             :     // If both instructions are defined in the same basic block then replacement
     715             :     // cannot break LCSSA form.
     716        2256 :     if (I->getParent() == From->getParent())
     717             :       return true;
     718             :     // If the instruction is not defined in a loop then it can safely replace
     719             :     // anything.
     720        4258 :     Loop *ToLoop = getLoopFor(I->getParent());
     721        1857 :     if (!ToLoop) return true;
     722             :     // If the replacing instruction is defined in the same loop as the original
     723             :     // instruction, or in a loop that contains it as an inner loop, then using
     724             :     // it as a replacement will not break LCSSA form.
     725        3714 :     return ToLoop->contains(getLoopFor(From->getParent()));
     726             :   }
     727             : 
     728             :   /// Checks if moving a specific instruction can break LCSSA in any loop.
     729             :   ///
     730             :   /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
     731             :   /// assuming that the function containing \p Inst and \p NewLoc is currently
     732             :   /// in LCSSA form.
     733         227 :   bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
     734             :     assert(Inst->getFunction() == NewLoc->getFunction() &&
     735             :            "Can't reason about IPO!");
     736             : 
     737         227 :     auto *OldBB = Inst->getParent();
     738         227 :     auto *NewBB = NewLoc->getParent();
     739             : 
     740             :     // Movement within the same loop does not break LCSSA (the equality check is
     741             :     // to avoid doing a hashtable lookup in case of intra-block movement).
     742         227 :     if (OldBB == NewBB)
     743             :       return true;
     744             : 
     745          38 :     auto *OldLoop = getLoopFor(OldBB);
     746          38 :     auto *NewLoop = getLoopFor(NewBB);
     747             : 
     748          19 :     if (OldLoop == NewLoop)
     749             :       return true;
     750             : 
     751             :     // Check if Outer contains Inner; with the null loop counting as the
     752             :     // "outermost" loop.
     753             :     auto Contains = [](const Loop *Outer, const Loop *Inner) {
     754           0 :       return !Outer || Outer->contains(Inner);
     755             :     };
     756             : 
     757             :     // To check that the movement of Inst to before NewLoc does not break LCSSA,
     758             :     // we need to check two sets of uses for possible LCSSA violations at
     759             :     // NewLoc: the users of NewInst, and the operands of NewInst.
     760             : 
     761             :     // If we know we're hoisting Inst out of an inner loop to an outer loop,
     762             :     // then the uses *of* Inst don't need to be checked.
     763             : 
     764           0 :     if (!Contains(NewLoop, OldLoop)) {
     765           0 :       for (Use &U : Inst->uses()) {
     766           0 :         auto *UI = cast<Instruction>(U.getUser());
     767           0 :         auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
     768           0 :                                      : UI->getParent();
     769           0 :         if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
     770             :           return false;
     771             :       }
     772             :     }
     773             : 
     774             :     // If we know we're sinking Inst from an outer loop into an inner loop, then
     775             :     // the *operands* of Inst don't need to be checked.
     776             : 
     777           0 :     if (!Contains(OldLoop, NewLoop)) {
     778             :       // See below on why we can't handle phi nodes here.
     779           0 :       if (isa<PHINode>(Inst))
     780             :         return false;
     781             : 
     782           0 :       for (Use &U : Inst->operands()) {
     783           0 :         auto *DefI = dyn_cast<Instruction>(U.get());
     784             :         if (!DefI)
     785             :           return false;
     786             : 
     787             :         // This would need adjustment if we allow Inst to be a phi node -- the
     788             :         // new use block won't simply be NewBB.
     789             : 
     790           0 :         auto *DefBlock = DefI->getParent();
     791           0 :         if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
     792             :           return false;
     793             :       }
     794             :     }
     795             : 
     796             :     return true;
     797             :   }
     798             : };
     799             : 
     800             : // Allow clients to walk the list of nested loops...
     801             : template <> struct GraphTraits<const Loop*> {
     802             :   typedef const Loop *NodeRef;
     803             :   typedef LoopInfo::iterator ChildIteratorType;
     804             : 
     805             :   static NodeRef getEntryNode(const Loop *L) { return L; }
     806        3122 :   static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
     807        3212 :   static ChildIteratorType child_end(NodeRef N) { return N->end(); }
     808             : };
     809             : 
     810             : template <> struct GraphTraits<Loop*> {
     811             :   typedef Loop *NodeRef;
     812             :   typedef LoopInfo::iterator ChildIteratorType;
     813             : 
     814             :   static NodeRef getEntryNode(Loop *L) { return L; }
     815       10884 :   static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
     816       12966 :   static ChildIteratorType child_end(NodeRef N) { return N->end(); }
     817             : };
     818             : 
     819             : /// \brief Analysis pass that exposes the \c LoopInfo for a function.
     820             : class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> {
     821             :   friend AnalysisInfoMixin<LoopAnalysis>;
     822             :   static AnalysisKey Key;
     823             : 
     824             : public:
     825             :   typedef LoopInfo Result;
     826             : 
     827             :   LoopInfo run(Function &F, FunctionAnalysisManager &AM);
     828             : };
     829             : 
     830             : /// \brief Printer pass for the \c LoopAnalysis results.
     831             : class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> {
     832             :   raw_ostream &OS;
     833             : 
     834             : public:
     835           1 :   explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
     836             :   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
     837             : };
     838             : 
     839             : /// \brief Verifier pass for the \c LoopAnalysis results.
     840             : struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> {
     841             :   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
     842             : };
     843             : 
     844             : /// \brief The legacy pass manager's analysis pass to compute loop information.
     845      261763 : class LoopInfoWrapperPass : public FunctionPass {
     846             :   LoopInfo LI;
     847             : 
     848             : public:
     849             :   static char ID; // Pass identification, replacement for typeid
     850             : 
     851      263232 :   LoopInfoWrapperPass() : FunctionPass(ID) {
     852       87744 :     initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
     853       87744 :   }
     854             : 
     855     3302261 :   LoopInfo &getLoopInfo() { return LI; }
     856             :   const LoopInfo &getLoopInfo() const { return LI; }
     857             : 
     858             :   /// \brief Calculate the natural loop information for a given function.
     859             :   bool runOnFunction(Function &F) override;
     860             : 
     861             :   void verifyAnalysis() const override;
     862             : 
     863     1943737 :   void releaseMemory() override { LI.releaseMemory(); }
     864             : 
     865             :   void print(raw_ostream &O, const Module *M = nullptr) const override;
     866             : 
     867             :   void getAnalysisUsage(AnalysisUsage &AU) const override;
     868             : };
     869             : 
     870             : /// Function to print a loop's contents as LLVM's text IR assembly.
     871             : void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner = "");
     872             : 
     873             : } // End llvm namespace
     874             : 
     875             : #endif

Generated by: LCOV version 1.13