1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
19 // It can calculate on the fly various bits of information, for example:
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
28 //===----------------------------------------------------------------------===//
30 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
31 #define LLVM_ANALYSIS_LOOP_INFO_H
33 #include "llvm/Pass.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/DenseSet.h"
36 #include "llvm/ADT/DepthFirstIterator.h"
37 #include "llvm/ADT/GraphTraits.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Support/CFG.h"
42 #include "llvm/Support/raw_ostream.h"
49 static void RemoveFromVector(std::vector<T*> &V, T *N) {
50 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
51 assert(I != V.end() && "N is not in this list!");
59 template<class N, class M> class LoopInfoBase;
60 template<class N, class M> class LoopBase;
62 //===----------------------------------------------------------------------===//
63 /// LoopBase class - Instances of this class are used to represent loops that
64 /// are detected in the flow graph
66 template<class BlockT, class LoopT>
69 // SubLoops - Loops contained entirely within this one.
70 std::vector<LoopT *> SubLoops;
72 // Blocks - The list of blocks in this loop. First entry is the header node.
73 std::vector<BlockT*> Blocks;
76 LoopBase(const LoopBase<BlockT, LoopT> &);
78 const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
80 /// Loop ctor - This creates an empty loop.
81 LoopBase() : ParentLoop(0) {}
83 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
87 /// getLoopDepth - Return the nesting level of this loop. An outer-most
88 /// loop has depth 1, for consistency with loop depth values used for basic
89 /// blocks, where depth 0 is used for blocks not inside any loops.
90 unsigned getLoopDepth() const {
92 for (const LoopT *CurLoop = ParentLoop; CurLoop;
93 CurLoop = CurLoop->ParentLoop)
97 BlockT *getHeader() const { return Blocks.front(); }
98 LoopT *getParentLoop() const { return ParentLoop; }
100 /// contains - Return true if the specified loop is contained within in
103 bool contains(const LoopT *L) const {
104 if (L == this) return true;
105 if (L == 0) return false;
106 return contains(L->getParentLoop());
109 /// contains - Return true if the specified basic block is in this loop.
111 bool contains(const BlockT *BB) const {
112 return std::find(block_begin(), block_end(), BB) != block_end();
115 /// contains - Return true if the specified instruction is in this loop.
117 template<class InstT>
118 bool contains(const InstT *Inst) const {
119 return contains(Inst->getParent());
122 /// iterator/begin/end - Return the loops contained entirely within this loop.
124 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
125 typedef typename std::vector<LoopT *>::const_iterator iterator;
126 iterator begin() const { return SubLoops.begin(); }
127 iterator end() const { return SubLoops.end(); }
128 bool empty() const { return SubLoops.empty(); }
130 /// getBlocks - Get a list of the basic blocks which make up this loop.
132 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
133 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
134 block_iterator block_begin() const { return Blocks.begin(); }
135 block_iterator block_end() const { return Blocks.end(); }
137 /// getNumBlocks - Get the number of blocks in this loop in constant time.
138 unsigned getNumBlocks() const {
139 return Blocks.size();
142 /// isLoopExiting - True if terminator in the block can branch to another
143 /// block that is outside of the current loop.
145 bool isLoopExiting(const BlockT *BB) const {
146 typedef GraphTraits<BlockT*> BlockTraits;
147 for (typename BlockTraits::ChildIteratorType SI =
148 BlockTraits::child_begin(const_cast<BlockT*>(BB)),
149 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
156 /// getNumBackEdges - Calculate the number of back edges to the loop header
158 unsigned getNumBackEdges() const {
159 unsigned NumBackEdges = 0;
160 BlockT *H = getHeader();
162 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
163 for (typename InvBlockTraits::ChildIteratorType I =
164 InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
165 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
172 //===--------------------------------------------------------------------===//
173 // APIs for simple analysis of the loop.
175 // Note that all of these methods can fail on general loops (ie, there may not
176 // be a preheader, etc). For best success, the loop simplification and
177 // induction variable canonicalization pass should be used to normalize loops
178 // for easy analysis. These methods assume canonical loops.
180 /// getExitingBlocks - Return all blocks inside the loop that have successors
181 /// outside of the loop. These are the blocks _inside of the current loop_
182 /// which branch out. The returned list is always unique.
184 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
186 /// getExitingBlock - If getExitingBlocks would return exactly one block,
187 /// return that block. Otherwise return null.
188 BlockT *getExitingBlock() const;
190 /// getExitBlocks - Return all of the successor blocks of this loop. These
191 /// are the blocks _outside of the current loop_ which are branched to.
193 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
195 /// getExitBlock - If getExitBlocks would return exactly one block,
196 /// return that block. Otherwise return null.
197 BlockT *getExitBlock() const;
200 typedef std::pair<const BlockT*, const BlockT*> Edge;
202 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
203 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
205 /// getLoopPreheader - If there is a preheader for this loop, return it. A
206 /// loop has a preheader if there is only one edge to the header of the loop
207 /// from outside of the loop. If this is the case, the block branching to the
208 /// header of the loop is the preheader node.
210 /// This method returns null if there is no preheader for the loop.
212 BlockT *getLoopPreheader() const;
214 /// getLoopPredecessor - If the given loop's header has exactly one unique
215 /// predecessor outside the loop, return it. Otherwise return null.
216 /// This is less strict that the loop "preheader" concept, which requires
217 /// the predecessor to have exactly one successor.
219 BlockT *getLoopPredecessor() const;
221 /// getLoopLatch - If there is a single latch block for this loop, return it.
222 /// A latch block is a block that contains a branch back to the header.
223 BlockT *getLoopLatch() const;
225 //===--------------------------------------------------------------------===//
226 // APIs for updating loop information after changing the CFG
229 /// addBasicBlockToLoop - This method is used by other analyses to update loop
230 /// information. NewBB is set to be a new member of the current loop.
231 /// Because of this, it is added as a member of all parent loops, and is added
232 /// to the specified LoopInfo object as being in the current basic block. It
233 /// is not valid to replace the loop header with this method.
235 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
237 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
238 /// the OldChild entry in our children list with NewChild, and updates the
239 /// parent pointer of OldChild to be null and the NewChild to be this loop.
240 /// This updates the loop depth of the new child.
241 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
243 /// addChildLoop - Add the specified loop to be a child of this loop. This
244 /// updates the loop depth of the new child.
246 void addChildLoop(LoopT *NewChild) {
247 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
248 NewChild->ParentLoop = static_cast<LoopT *>(this);
249 SubLoops.push_back(NewChild);
252 /// removeChildLoop - This removes the specified child from being a subloop of
253 /// this loop. The loop is not deleted, as it will presumably be inserted
254 /// into another loop.
255 LoopT *removeChildLoop(iterator I) {
256 assert(I != SubLoops.end() && "Cannot remove end iterator!");
258 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
259 SubLoops.erase(SubLoops.begin()+(I-begin()));
260 Child->ParentLoop = 0;
264 /// addBlockEntry - This adds a basic block directly to the basic block list.
265 /// This should only be used by transformations that create new loops. Other
266 /// transformations should use addBasicBlockToLoop.
267 void addBlockEntry(BlockT *BB) {
268 Blocks.push_back(BB);
271 /// moveToHeader - This method is used to move BB (which must be part of this
272 /// loop) to be the loop header of the loop (the block that dominates all
274 void moveToHeader(BlockT *BB) {
275 if (Blocks[0] == BB) return;
276 for (unsigned i = 0; ; ++i) {
277 assert(i != Blocks.size() && "Loop does not contain BB!");
278 if (Blocks[i] == BB) {
279 Blocks[i] = Blocks[0];
286 /// removeBlockFromLoop - This removes the specified basic block from the
287 /// current loop, updating the Blocks as appropriate. This does not update
288 /// the mapping in the LoopInfo class.
289 void removeBlockFromLoop(BlockT *BB) {
290 RemoveFromVector(Blocks, BB);
293 /// verifyLoop - Verify loop structure
294 void verifyLoop() const;
296 /// verifyLoop - Verify loop structure of this loop and all nested loops.
297 void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
299 void print(raw_ostream &OS, unsigned Depth = 0) const;
302 friend class LoopInfoBase<BlockT, LoopT>;
303 explicit LoopBase(BlockT *BB) : ParentLoop(0) {
304 Blocks.push_back(BB);
308 template<class BlockT, class LoopT>
309 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
314 class Loop : public LoopBase<BasicBlock, Loop> {
318 /// isLoopInvariant - Return true if the specified value is loop invariant
320 bool isLoopInvariant(Value *V) const;
322 /// hasLoopInvariantOperands - Return true if all the operands of the
323 /// specified instruction are loop invariant.
324 bool hasLoopInvariantOperands(Instruction *I) const;
326 /// makeLoopInvariant - If the given value is an instruction inside of the
327 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
328 /// Return true if the value after any hoisting is loop invariant. This
329 /// function can be used as a slightly more aggressive replacement for
332 /// If InsertPt is specified, it is the point to hoist instructions to.
333 /// If null, the terminator of the loop preheader is used.
335 bool makeLoopInvariant(Value *V, bool &Changed,
336 Instruction *InsertPt = 0) const;
338 /// makeLoopInvariant - If the given instruction is inside of the
339 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
340 /// Return true if the instruction after any hoisting is loop invariant. This
341 /// function can be used as a slightly more aggressive replacement for
344 /// If InsertPt is specified, it is the point to hoist instructions to.
345 /// If null, the terminator of the loop preheader is used.
347 bool makeLoopInvariant(Instruction *I, bool &Changed,
348 Instruction *InsertPt = 0) const;
350 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
351 /// induction variable: an integer recurrence that starts at 0 and increments
352 /// by one each time through the loop. If so, return the phi node that
353 /// corresponds to it.
355 /// The IndVarSimplify pass transforms loops to have a canonical induction
358 PHINode *getCanonicalInductionVariable() const;
360 /// isLCSSAForm - Return true if the Loop is in LCSSA form
361 bool isLCSSAForm(DominatorTree &DT) const;
363 /// isLoopSimplifyForm - Return true if the Loop is in the form that
364 /// the LoopSimplify form transforms loops to, which is sometimes called
366 bool isLoopSimplifyForm() const;
368 /// isSafeToClone - Return true if the loop body is safe to clone in practice.
369 bool isSafeToClone() const;
371 /// hasDedicatedExits - Return true if no exit block for the loop
372 /// has a predecessor that is outside the loop.
373 bool hasDedicatedExits() const;
375 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
376 /// These are the blocks _outside of the current loop_ which are branched to.
377 /// This assumes that loop exits are in canonical form.
379 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
381 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
382 /// block, return that block. Otherwise return null.
383 BasicBlock *getUniqueExitBlock() const;
388 friend class LoopInfoBase<BasicBlock, Loop>;
389 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
392 //===----------------------------------------------------------------------===//
393 /// LoopInfo - This class builds and contains all of the top level loop
394 /// structures in the specified function.
397 template<class BlockT, class LoopT>
399 // BBMap - Mapping of basic blocks to the inner most loop they occur in
400 DenseMap<BlockT *, LoopT *> BBMap;
401 std::vector<LoopT *> TopLevelLoops;
402 friend class LoopBase<BlockT, LoopT>;
403 friend class LoopInfo;
405 void operator=(const LoopInfoBase &); // do not implement
406 LoopInfoBase(const LoopInfo &); // do not implement
409 ~LoopInfoBase() { releaseMemory(); }
411 void releaseMemory() {
412 for (typename std::vector<LoopT *>::iterator I =
413 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
414 delete *I; // Delete all of the loops...
416 BBMap.clear(); // Reset internal state of analysis
417 TopLevelLoops.clear();
420 /// iterator/begin/end - The interface to the top-level loops in the current
423 typedef typename std::vector<LoopT *>::const_iterator iterator;
424 iterator begin() const { return TopLevelLoops.begin(); }
425 iterator end() const { return TopLevelLoops.end(); }
426 bool empty() const { return TopLevelLoops.empty(); }
428 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
429 /// block is in no loop (for example the entry node), null is returned.
431 LoopT *getLoopFor(const BlockT *BB) const {
432 return BBMap.lookup(const_cast<BlockT*>(BB));
435 /// operator[] - same as getLoopFor...
437 const LoopT *operator[](const BlockT *BB) const {
438 return getLoopFor(BB);
441 /// getLoopDepth - Return the loop nesting level of the specified block. A
442 /// depth of 0 means the block is not inside any loop.
444 unsigned getLoopDepth(const BlockT *BB) const {
445 const LoopT *L = getLoopFor(BB);
446 return L ? L->getLoopDepth() : 0;
449 // isLoopHeader - True if the block is a loop header node
450 bool isLoopHeader(BlockT *BB) const {
451 const LoopT *L = getLoopFor(BB);
452 return L && L->getHeader() == BB;
455 /// removeLoop - This removes the specified top-level loop from this loop info
456 /// object. The loop is not deleted, as it will presumably be inserted into
458 LoopT *removeLoop(iterator I) {
459 assert(I != end() && "Cannot remove end iterator!");
461 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
462 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
466 /// changeLoopFor - Change the top-level loop that contains BB to the
467 /// specified loop. This should be used by transformations that restructure
468 /// the loop hierarchy tree.
469 void changeLoopFor(BlockT *BB, LoopT *L) {
477 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
478 /// list with the indicated loop.
479 void changeTopLevelLoop(LoopT *OldLoop,
481 typename std::vector<LoopT *>::iterator I =
482 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
483 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
485 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
486 "Loops already embedded into a subloop!");
489 /// addTopLevelLoop - This adds the specified loop to the collection of
491 void addTopLevelLoop(LoopT *New) {
492 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
493 TopLevelLoops.push_back(New);
496 /// removeBlock - This method completely removes BB from all data structures,
497 /// including all of the Loop objects it is nested in and our mapping from
498 /// BasicBlocks to loops.
499 void removeBlock(BlockT *BB) {
500 typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
501 if (I != BBMap.end()) {
502 for (LoopT *L = I->second; L; L = L->getParentLoop())
503 L->removeBlockFromLoop(BB);
511 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
512 const LoopT *ParentLoop) {
513 if (SubLoop == 0) return true;
514 if (SubLoop == ParentLoop) return false;
515 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
518 void Calculate(DominatorTreeBase<BlockT> &DT);
520 LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT);
522 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
523 /// of the NewParent Loop, instead of being a sibling of it.
524 void MoveSiblingLoopInto(LoopT *NewChild, LoopT *NewParent);
526 /// InsertLoopInto - This inserts loop L into the specified parent loop. If
527 /// the parent loop contains a loop which should contain L, the loop gets
528 /// inserted into L instead.
529 void InsertLoopInto(LoopT *L, LoopT *Parent);
533 void print(raw_ostream &OS) const;
536 class LoopInfo : public FunctionPass {
537 LoopInfoBase<BasicBlock, Loop> LI;
538 friend class LoopBase<BasicBlock, Loop>;
540 void operator=(const LoopInfo &); // do not implement
541 LoopInfo(const LoopInfo &); // do not implement
543 static char ID; // Pass identification, replacement for typeid
545 LoopInfo() : FunctionPass(ID) {
546 initializeLoopInfoPass(*PassRegistry::getPassRegistry());
549 LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
551 /// iterator/begin/end - The interface to the top-level loops in the current
554 typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
555 inline iterator begin() const { return LI.begin(); }
556 inline iterator end() const { return LI.end(); }
557 bool empty() const { return LI.empty(); }
559 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
560 /// block is in no loop (for example the entry node), null is returned.
562 inline Loop *getLoopFor(const BasicBlock *BB) const {
563 return LI.getLoopFor(BB);
566 /// operator[] - same as getLoopFor...
568 inline const Loop *operator[](const BasicBlock *BB) const {
569 return LI.getLoopFor(BB);
572 /// getLoopDepth - Return the loop nesting level of the specified block. A
573 /// depth of 0 means the block is not inside any loop.
575 inline unsigned getLoopDepth(const BasicBlock *BB) const {
576 return LI.getLoopDepth(BB);
579 // isLoopHeader - True if the block is a loop header node
580 inline bool isLoopHeader(BasicBlock *BB) const {
581 return LI.isLoopHeader(BB);
584 /// runOnFunction - Calculate the natural loop information.
586 virtual bool runOnFunction(Function &F);
588 virtual void verifyAnalysis() const;
590 virtual void releaseMemory() { LI.releaseMemory(); }
592 virtual void print(raw_ostream &O, const Module* M = 0) const;
594 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
596 /// removeLoop - This removes the specified top-level loop from this loop info
597 /// object. The loop is not deleted, as it will presumably be inserted into
599 inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
601 /// changeLoopFor - Change the top-level loop that contains BB to the
602 /// specified loop. This should be used by transformations that restructure
603 /// the loop hierarchy tree.
604 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
605 LI.changeLoopFor(BB, L);
608 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
609 /// list with the indicated loop.
610 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
611 LI.changeTopLevelLoop(OldLoop, NewLoop);
614 /// addTopLevelLoop - This adds the specified loop to the collection of
616 inline void addTopLevelLoop(Loop *New) {
617 LI.addTopLevelLoop(New);
620 /// removeBlock - This method completely removes BB from all data structures,
621 /// including all of the Loop objects it is nested in and our mapping from
622 /// BasicBlocks to loops.
623 void removeBlock(BasicBlock *BB) {
627 /// updateUnloop - Update LoopInfo after removing the last backedge from a
628 /// loop--now the "unloop". This updates the loop forest and parent loops for
629 /// each block so that Unloop is no longer referenced, but the caller must
630 /// actually delete the Unloop object.
631 void updateUnloop(Loop *Unloop);
633 /// replacementPreservesLCSSAForm - Returns true if replacing From with To
634 /// everywhere is guaranteed to preserve LCSSA form.
635 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
636 // Preserving LCSSA form is only problematic if the replacing value is an
638 Instruction *I = dyn_cast<Instruction>(To);
640 // If both instructions are defined in the same basic block then replacement
641 // cannot break LCSSA form.
642 if (I->getParent() == From->getParent())
644 // If the instruction is not defined in a loop then it can safely replace
646 Loop *ToLoop = getLoopFor(I->getParent());
647 if (!ToLoop) return true;
648 // If the replacing instruction is defined in the same loop as the original
649 // instruction, or in a loop that contains it as an inner loop, then using
650 // it as a replacement will not break LCSSA form.
651 return ToLoop->contains(getLoopFor(From->getParent()));
656 // Allow clients to walk the list of nested loops...
657 template <> struct GraphTraits<const Loop*> {
658 typedef const Loop NodeType;
659 typedef LoopInfo::iterator ChildIteratorType;
661 static NodeType *getEntryNode(const Loop *L) { return L; }
662 static inline ChildIteratorType child_begin(NodeType *N) {
665 static inline ChildIteratorType child_end(NodeType *N) {
670 template <> struct GraphTraits<Loop*> {
671 typedef Loop NodeType;
672 typedef LoopInfo::iterator ChildIteratorType;
674 static NodeType *getEntryNode(Loop *L) { return L; }
675 static inline ChildIteratorType child_begin(NodeType *N) {
678 static inline ChildIteratorType child_end(NodeType *N) {
683 } // End llvm namespace