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
29 //===----------------------------------------------------------------------===//
31 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
32 #define LLVM_ANALYSIS_LOOP_INFO_H
34 #include "llvm/Pass.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/DenseSet.h"
37 #include "llvm/ADT/DepthFirstIterator.h"
38 #include "llvm/ADT/GraphTraits.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/Analysis/Dominators.h"
42 #include "llvm/Support/CFG.h"
43 #include "llvm/Support/raw_ostream.h"
50 static void RemoveFromVector(std::vector<T*> &V, T *N) {
51 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
52 assert(I != V.end() && "N is not in this list!");
60 template<class N, class M> class LoopInfoBase;
61 template<class N, class M> class LoopBase;
63 //===----------------------------------------------------------------------===//
64 /// LoopBase class - Instances of this class are used to represent loops that
65 /// are detected in the flow graph
67 template<class BlockT, class LoopT>
70 // SubLoops - Loops contained entirely within this one.
71 std::vector<LoopT *> SubLoops;
73 // Blocks - The list of blocks in this loop. First entry is the header node.
74 std::vector<BlockT*> Blocks;
77 LoopBase(const LoopBase<BlockT, LoopT> &);
79 const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
81 /// Loop ctor - This creates an empty loop.
82 LoopBase() : ParentLoop(0) {}
84 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
88 /// getLoopDepth - Return the nesting level of this loop. An outer-most
89 /// loop has depth 1, for consistency with loop depth values used for basic
90 /// blocks, where depth 0 is used for blocks not inside any loops.
91 unsigned getLoopDepth() const {
93 for (const LoopT *CurLoop = ParentLoop; CurLoop;
94 CurLoop = CurLoop->ParentLoop)
98 BlockT *getHeader() const { return Blocks.front(); }
99 LoopT *getParentLoop() const { return ParentLoop; }
101 /// contains - Return true if the specified loop is contained within in
104 bool contains(const LoopT *L) const {
105 if (L == this) return true;
106 if (L == 0) return false;
107 return contains(L->getParentLoop());
110 /// contains - Return true if the specified basic block is in this loop.
112 bool contains(const BlockT *BB) const {
113 return std::find(block_begin(), block_end(), BB) != block_end();
116 /// contains - Return true if the specified instruction is in this loop.
118 template<class InstT>
119 bool contains(const InstT *Inst) const {
120 return contains(Inst->getParent());
123 /// iterator/begin/end - Return the loops contained entirely within this loop.
125 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
126 typedef typename std::vector<LoopT *>::const_iterator iterator;
127 iterator begin() const { return SubLoops.begin(); }
128 iterator end() const { return SubLoops.end(); }
129 bool empty() const { return SubLoops.empty(); }
131 /// getBlocks - Get a list of the basic blocks which make up this loop.
133 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
134 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
135 block_iterator block_begin() const { return Blocks.begin(); }
136 block_iterator block_end() const { return Blocks.end(); }
138 /// getNumBlocks - Get the number of blocks in this loop in constant time.
139 unsigned getNumBlocks() const {
140 return Blocks.size();
143 /// isLoopExiting - True if terminator in the block can branch to another
144 /// block that is outside of the current loop.
146 bool isLoopExiting(const BlockT *BB) const {
147 typedef GraphTraits<BlockT*> BlockTraits;
148 for (typename BlockTraits::ChildIteratorType SI =
149 BlockTraits::child_begin(const_cast<BlockT*>(BB)),
150 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
157 /// getNumBackEdges - Calculate the number of back edges to the loop header
159 unsigned getNumBackEdges() const {
160 unsigned NumBackEdges = 0;
161 BlockT *H = getHeader();
163 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
164 for (typename InvBlockTraits::ChildIteratorType I =
165 InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
166 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
173 //===--------------------------------------------------------------------===//
174 // APIs for simple analysis of the loop.
176 // Note that all of these methods can fail on general loops (ie, there may not
177 // be a preheader, etc). For best success, the loop simplification and
178 // induction variable canonicalization pass should be used to normalize loops
179 // for easy analysis. These methods assume canonical loops.
181 /// getExitingBlocks - Return all blocks inside the loop that have successors
182 /// outside of the loop. These are the blocks _inside of the current loop_
183 /// which branch out. The returned list is always unique.
185 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
186 // Sort the blocks vector so that we can use binary search to do quick
188 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
189 std::sort(LoopBBs.begin(), LoopBBs.end());
191 typedef GraphTraits<BlockT*> BlockTraits;
192 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
193 for (typename BlockTraits::ChildIteratorType I =
194 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
196 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
197 // Not in current loop? It must be an exit block.
198 ExitingBlocks.push_back(*BI);
203 /// getExitingBlock - If getExitingBlocks would return exactly one block,
204 /// return that block. Otherwise return null.
205 BlockT *getExitingBlock() const {
206 SmallVector<BlockT*, 8> ExitingBlocks;
207 getExitingBlocks(ExitingBlocks);
208 if (ExitingBlocks.size() == 1)
209 return ExitingBlocks[0];
213 /// getExitBlocks - Return all of the successor blocks of this loop. These
214 /// are the blocks _outside of the current loop_ which are branched to.
216 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
217 // Sort the blocks vector so that we can use binary search to do quick
219 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
220 std::sort(LoopBBs.begin(), LoopBBs.end());
222 typedef GraphTraits<BlockT*> BlockTraits;
223 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
224 for (typename BlockTraits::ChildIteratorType I =
225 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
227 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
228 // Not in current loop? It must be an exit block.
229 ExitBlocks.push_back(*I);
232 /// getExitBlock - If getExitBlocks would return exactly one block,
233 /// return that block. Otherwise return null.
234 BlockT *getExitBlock() const {
235 SmallVector<BlockT*, 8> ExitBlocks;
236 getExitBlocks(ExitBlocks);
237 if (ExitBlocks.size() == 1)
238 return ExitBlocks[0];
243 typedef std::pair<BlockT*, BlockT*> Edge;
245 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
246 template <typename EdgeT>
247 void getExitEdges(SmallVectorImpl<EdgeT> &ExitEdges) const {
248 // Sort the blocks vector so that we can use binary search to do quick
250 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
251 array_pod_sort(LoopBBs.begin(), LoopBBs.end());
253 typedef GraphTraits<BlockT*> BlockTraits;
254 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
255 for (typename BlockTraits::ChildIteratorType I =
256 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
258 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
259 // Not in current loop? It must be an exit block.
260 ExitEdges.push_back(EdgeT(*BI, *I));
263 /// getLoopPreheader - If there is a preheader for this loop, return it. A
264 /// loop has a preheader if there is only one edge to the header of the loop
265 /// from outside of the loop. If this is the case, the block branching to the
266 /// header of the loop is the preheader node.
268 /// This method returns null if there is no preheader for the loop.
270 BlockT *getLoopPreheader() const {
271 // Keep track of nodes outside the loop branching to the header...
272 BlockT *Out = getLoopPredecessor();
275 // Make sure there is only one exit out of the preheader.
276 typedef GraphTraits<BlockT*> BlockTraits;
277 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
279 if (SI != BlockTraits::child_end(Out))
280 return 0; // Multiple exits from the block, must not be a preheader.
282 // The predecessor has exactly one successor, so it is a preheader.
286 /// getLoopPredecessor - If the given loop's header has exactly one unique
287 /// predecessor outside the loop, return it. Otherwise return null.
288 /// This is less strict that the loop "preheader" concept, which requires
289 /// the predecessor to have exactly one successor.
291 BlockT *getLoopPredecessor() const {
292 // Keep track of nodes outside the loop branching to the header...
295 // Loop over the predecessors of the header node...
296 BlockT *Header = getHeader();
297 typedef GraphTraits<BlockT*> BlockTraits;
298 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
299 for (typename InvBlockTraits::ChildIteratorType PI =
300 InvBlockTraits::child_begin(Header),
301 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
302 typename InvBlockTraits::NodeType *N = *PI;
303 if (!contains(N)) { // If the block is not in the loop...
305 return 0; // Multiple predecessors outside the loop
310 // Make sure there is only one exit out of the preheader.
311 assert(Out && "Header of loop has no predecessors from outside loop?");
315 /// getLoopLatch - If there is a single latch block for this loop, return it.
316 /// A latch block is a block that contains a branch back to the header.
317 BlockT *getLoopLatch() const {
318 BlockT *Header = getHeader();
319 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
320 typename InvBlockTraits::ChildIteratorType PI =
321 InvBlockTraits::child_begin(Header);
322 typename InvBlockTraits::ChildIteratorType PE =
323 InvBlockTraits::child_end(Header);
325 for (; PI != PE; ++PI) {
326 typename InvBlockTraits::NodeType *N = *PI;
336 //===--------------------------------------------------------------------===//
337 // APIs for updating loop information after changing the CFG
340 /// addBasicBlockToLoop - This method is used by other analyses to update loop
341 /// information. NewBB is set to be a new member of the current loop.
342 /// Because of this, it is added as a member of all parent loops, and is added
343 /// to the specified LoopInfo object as being in the current basic block. It
344 /// is not valid to replace the loop header with this method.
346 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
348 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
349 /// the OldChild entry in our children list with NewChild, and updates the
350 /// parent pointer of OldChild to be null and the NewChild to be this loop.
351 /// This updates the loop depth of the new child.
352 void replaceChildLoopWith(LoopT *OldChild,
354 assert(OldChild->ParentLoop == this && "This loop is already broken!");
355 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
356 typename std::vector<LoopT *>::iterator I =
357 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
358 assert(I != SubLoops.end() && "OldChild not in loop!");
360 OldChild->ParentLoop = 0;
361 NewChild->ParentLoop = static_cast<LoopT *>(this);
364 /// addChildLoop - Add the specified loop to be a child of this loop. This
365 /// updates the loop depth of the new child.
367 void addChildLoop(LoopT *NewChild) {
368 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
369 NewChild->ParentLoop = static_cast<LoopT *>(this);
370 SubLoops.push_back(NewChild);
373 /// removeChildLoop - This removes the specified child from being a subloop of
374 /// this loop. The loop is not deleted, as it will presumably be inserted
375 /// into another loop.
376 LoopT *removeChildLoop(iterator I) {
377 assert(I != SubLoops.end() && "Cannot remove end iterator!");
379 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
380 SubLoops.erase(SubLoops.begin()+(I-begin()));
381 Child->ParentLoop = 0;
385 /// addBlockEntry - This adds a basic block directly to the basic block list.
386 /// This should only be used by transformations that create new loops. Other
387 /// transformations should use addBasicBlockToLoop.
388 void addBlockEntry(BlockT *BB) {
389 Blocks.push_back(BB);
392 /// moveToHeader - This method is used to move BB (which must be part of this
393 /// loop) to be the loop header of the loop (the block that dominates all
395 void moveToHeader(BlockT *BB) {
396 if (Blocks[0] == BB) return;
397 for (unsigned i = 0; ; ++i) {
398 assert(i != Blocks.size() && "Loop does not contain BB!");
399 if (Blocks[i] == BB) {
400 Blocks[i] = Blocks[0];
407 /// removeBlockFromLoop - This removes the specified basic block from the
408 /// current loop, updating the Blocks as appropriate. This does not update
409 /// the mapping in the LoopInfo class.
410 void removeBlockFromLoop(BlockT *BB) {
411 RemoveFromVector(Blocks, BB);
414 /// verifyLoop - Verify loop structure
415 void verifyLoop() const {
417 assert(!Blocks.empty() && "Loop header is missing");
419 // Setup for using a depth-first iterator to visit every block in the loop.
420 SmallVector<BlockT*, 8> ExitBBs;
421 getExitBlocks(ExitBBs);
422 llvm::SmallPtrSet<BlockT*, 8> VisitSet;
423 VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
424 df_ext_iterator<BlockT*, llvm::SmallPtrSet<BlockT*, 8> >
425 BI = df_ext_begin(getHeader(), VisitSet),
426 BE = df_ext_end(getHeader(), VisitSet);
428 // Keep track of the number of BBs visited.
429 unsigned NumVisited = 0;
431 // Sort the blocks vector so that we can use binary search to do quick
433 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
434 std::sort(LoopBBs.begin(), LoopBBs.end());
436 // Check the individual blocks.
437 for ( ; BI != BE; ++BI) {
439 bool HasInsideLoopSuccs = false;
440 bool HasInsideLoopPreds = false;
441 SmallVector<BlockT *, 2> OutsideLoopPreds;
443 typedef GraphTraits<BlockT*> BlockTraits;
444 for (typename BlockTraits::ChildIteratorType SI =
445 BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
447 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
448 HasInsideLoopSuccs = true;
451 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
452 for (typename InvBlockTraits::ChildIteratorType PI =
453 InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
456 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), N))
457 HasInsideLoopPreds = true;
459 OutsideLoopPreds.push_back(N);
462 if (BB == getHeader()) {
463 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
464 } else if (!OutsideLoopPreds.empty()) {
465 // A non-header loop shouldn't be reachable from outside the loop,
466 // though it is permitted if the predecessor is not itself actually
468 BlockT *EntryBB = BB->getParent()->begin();
469 for (df_iterator<BlockT *> NI = df_begin(EntryBB),
470 NE = df_end(EntryBB); NI != NE; ++NI)
471 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
472 assert(*NI != OutsideLoopPreds[i] &&
473 "Loop has multiple entry points!");
475 assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
476 assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
477 assert(BB != getHeader()->getParent()->begin() &&
478 "Loop contains function entry block!");
483 assert(NumVisited == getNumBlocks() && "Unreachable block in loop");
485 // Check the subloops.
486 for (iterator I = begin(), E = end(); I != E; ++I)
487 // Each block in each subloop should be contained within this loop.
488 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
490 assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
491 "Loop does not contain all the blocks of a subloop!");
494 // Check the parent loop pointer.
496 assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
498 "Loop is not a subloop of its parent!");
503 /// verifyLoop - Verify loop structure of this loop and all nested loops.
504 void verifyLoopNest(DenseSet<const LoopT*> *Loops) const {
505 Loops->insert(static_cast<const LoopT *>(this));
508 // Verify the subloops.
509 for (iterator I = begin(), E = end(); I != E; ++I)
510 (*I)->verifyLoopNest(Loops);
513 void print(raw_ostream &OS, unsigned Depth = 0) const {
514 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
517 for (unsigned i = 0; i < getBlocks().size(); ++i) {
519 BlockT *BB = getBlocks()[i];
520 WriteAsOperand(OS, BB, false);
521 if (BB == getHeader()) OS << "<header>";
522 if (BB == getLoopLatch()) OS << "<latch>";
523 if (isLoopExiting(BB)) OS << "<exiting>";
527 for (iterator I = begin(), E = end(); I != E; ++I)
528 (*I)->print(OS, Depth+2);
532 friend class LoopInfoBase<BlockT, LoopT>;
533 explicit LoopBase(BlockT *BB) : ParentLoop(0) {
534 Blocks.push_back(BB);
538 template<class BlockT, class LoopT>
539 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
544 class Loop : public LoopBase<BasicBlock, Loop> {
548 /// isLoopInvariant - Return true if the specified value is loop invariant
550 bool isLoopInvariant(Value *V) const;
552 /// hasLoopInvariantOperands - Return true if all the operands of the
553 /// specified instruction are loop invariant.
554 bool hasLoopInvariantOperands(Instruction *I) const;
556 /// makeLoopInvariant - If the given value is an instruction inside of the
557 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
558 /// Return true if the value after any hoisting is loop invariant. This
559 /// function can be used as a slightly more aggressive replacement for
562 /// If InsertPt is specified, it is the point to hoist instructions to.
563 /// If null, the terminator of the loop preheader is used.
565 bool makeLoopInvariant(Value *V, bool &Changed,
566 Instruction *InsertPt = 0) const;
568 /// makeLoopInvariant - If the given instruction is inside of the
569 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
570 /// Return true if the instruction after any hoisting is loop invariant. This
571 /// function can be used as a slightly more aggressive replacement for
574 /// If InsertPt is specified, it is the point to hoist instructions to.
575 /// If null, the terminator of the loop preheader is used.
577 bool makeLoopInvariant(Instruction *I, bool &Changed,
578 Instruction *InsertPt = 0) const;
580 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
581 /// induction variable: an integer recurrence that starts at 0 and increments
582 /// by one each time through the loop. If so, return the phi node that
583 /// corresponds to it.
585 /// The IndVarSimplify pass transforms loops to have a canonical induction
588 PHINode *getCanonicalInductionVariable() const;
590 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
591 /// times the loop will be executed. Note that this means that the backedge
592 /// of the loop executes N-1 times. If the trip-count cannot be determined,
593 /// this returns null.
595 /// The IndVarSimplify pass transforms loops to have a form that this
596 /// function easily understands.
598 Value *getTripCount() const;
600 /// getSmallConstantTripCount - Returns the trip count of this loop as a
601 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
602 /// of not constant. Will also return 0 if the trip count is very large
605 /// The IndVarSimplify pass transforms loops to have a form that this
606 /// function easily understands.
608 unsigned getSmallConstantTripCount() const;
610 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
611 /// trip count of this loop as a normal unsigned value, if possible. This
612 /// means that the actual trip count is always a multiple of the returned
613 /// value (don't forget the trip count could very well be zero as well!).
615 /// Returns 1 if the trip count is unknown or not guaranteed to be the
616 /// multiple of a constant (which is also the case if the trip count is simply
617 /// constant, use getSmallConstantTripCount for that case), Will also return 1
618 /// if the trip count is very large (>= 2^32).
619 unsigned getSmallConstantTripMultiple() const;
621 /// isLCSSAForm - Return true if the Loop is in LCSSA form
622 bool isLCSSAForm(DominatorTree &DT) const;
624 /// isLoopSimplifyForm - Return true if the Loop is in the form that
625 /// the LoopSimplify form transforms loops to, which is sometimes called
627 bool isLoopSimplifyForm() const;
629 /// hasDedicatedExits - Return true if no exit block for the loop
630 /// has a predecessor that is outside the loop.
631 bool hasDedicatedExits() const;
633 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
634 /// These are the blocks _outside of the current loop_ which are branched to.
635 /// This assumes that loop exits are in canonical form.
637 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
639 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
640 /// block, return that block. Otherwise return null.
641 BasicBlock *getUniqueExitBlock() const;
646 friend class LoopInfoBase<BasicBlock, Loop>;
647 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
650 //===----------------------------------------------------------------------===//
651 /// LoopInfo - This class builds and contains all of the top level loop
652 /// structures in the specified function.
655 template<class BlockT, class LoopT>
657 // BBMap - Mapping of basic blocks to the inner most loop they occur in
658 DenseMap<BlockT *, LoopT *> BBMap;
659 std::vector<LoopT *> TopLevelLoops;
660 friend class LoopBase<BlockT, LoopT>;
661 friend class LoopInfo;
663 void operator=(const LoopInfoBase &); // do not implement
664 LoopInfoBase(const LoopInfo &); // do not implement
667 ~LoopInfoBase() { releaseMemory(); }
669 void releaseMemory() {
670 for (typename std::vector<LoopT *>::iterator I =
671 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
672 delete *I; // Delete all of the loops...
674 BBMap.clear(); // Reset internal state of analysis
675 TopLevelLoops.clear();
678 /// iterator/begin/end - The interface to the top-level loops in the current
681 typedef typename std::vector<LoopT *>::const_iterator iterator;
682 iterator begin() const { return TopLevelLoops.begin(); }
683 iterator end() const { return TopLevelLoops.end(); }
684 bool empty() const { return TopLevelLoops.empty(); }
686 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
687 /// block is in no loop (for example the entry node), null is returned.
689 LoopT *getLoopFor(const BlockT *BB) const {
690 typename DenseMap<BlockT *, LoopT *>::const_iterator I=
691 BBMap.find(const_cast<BlockT*>(BB));
692 return I != BBMap.end() ? I->second : 0;
695 /// operator[] - same as getLoopFor...
697 const LoopT *operator[](const BlockT *BB) const {
698 return getLoopFor(BB);
701 /// getLoopDepth - Return the loop nesting level of the specified block. A
702 /// depth of 0 means the block is not inside any loop.
704 unsigned getLoopDepth(const BlockT *BB) const {
705 const LoopT *L = getLoopFor(BB);
706 return L ? L->getLoopDepth() : 0;
709 // isLoopHeader - True if the block is a loop header node
710 bool isLoopHeader(BlockT *BB) const {
711 const LoopT *L = getLoopFor(BB);
712 return L && L->getHeader() == BB;
715 /// removeLoop - This removes the specified top-level loop from this loop info
716 /// object. The loop is not deleted, as it will presumably be inserted into
718 LoopT *removeLoop(iterator I) {
719 assert(I != end() && "Cannot remove end iterator!");
721 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
722 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
726 /// changeLoopFor - Change the top-level loop that contains BB to the
727 /// specified loop. This should be used by transformations that restructure
728 /// the loop hierarchy tree.
729 void changeLoopFor(BlockT *BB, LoopT *L) {
731 typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
732 if (I != BBMap.end())
739 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
740 /// list with the indicated loop.
741 void changeTopLevelLoop(LoopT *OldLoop,
743 typename std::vector<LoopT *>::iterator I =
744 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
745 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
747 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
748 "Loops already embedded into a subloop!");
751 /// addTopLevelLoop - This adds the specified loop to the collection of
753 void addTopLevelLoop(LoopT *New) {
754 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
755 TopLevelLoops.push_back(New);
758 /// removeBlock - This method completely removes BB from all data structures,
759 /// including all of the Loop objects it is nested in and our mapping from
760 /// BasicBlocks to loops.
761 void removeBlock(BlockT *BB) {
762 typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
763 if (I != BBMap.end()) {
764 for (LoopT *L = I->second; L; L = L->getParentLoop())
765 L->removeBlockFromLoop(BB);
773 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
774 const LoopT *ParentLoop) {
775 if (SubLoop == 0) return true;
776 if (SubLoop == ParentLoop) return false;
777 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
780 void Calculate(DominatorTreeBase<BlockT> &DT) {
781 BlockT *RootNode = DT.getRootNode()->getBlock();
783 for (df_iterator<BlockT*> NI = df_begin(RootNode),
784 NE = df_end(RootNode); NI != NE; ++NI)
785 if (LoopT *L = ConsiderForLoop(*NI, DT))
786 TopLevelLoops.push_back(L);
789 LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
790 if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
792 std::vector<BlockT *> TodoStack;
794 // Scan the predecessors of BB, checking to see if BB dominates any of
795 // them. This identifies backedges which target this node...
796 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
797 for (typename InvBlockTraits::ChildIteratorType I =
798 InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
800 typename InvBlockTraits::NodeType *N = *I;
801 if (DT.dominates(BB, N)) // If BB dominates its predecessor...
802 TodoStack.push_back(N);
805 if (TodoStack.empty()) return 0; // No backedges to this block...
807 // Create a new loop to represent this basic block...
808 LoopT *L = new LoopT(BB);
811 BlockT *EntryBlock = BB->getParent()->begin();
813 while (!TodoStack.empty()) { // Process all the nodes in the loop
814 BlockT *X = TodoStack.back();
815 TodoStack.pop_back();
817 if (!L->contains(X) && // As of yet unprocessed??
818 DT.dominates(EntryBlock, X)) { // X is reachable from entry block?
819 // Check to see if this block already belongs to a loop. If this occurs
820 // then we have a case where a loop that is supposed to be a child of
821 // the current loop was processed before the current loop. When this
822 // occurs, this child loop gets added to a part of the current loop,
823 // making it a sibling to the current loop. We have to reparent this
826 const_cast<LoopT *>(getLoopFor(X)))
827 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
828 // Remove the subloop from its current parent...
829 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
830 LoopT *SLP = SubLoop->ParentLoop; // SubLoopParent
831 typename std::vector<LoopT *>::iterator I =
832 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
833 assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
834 SLP->SubLoops.erase(I); // Remove from parent...
836 // Add the subloop to THIS loop...
837 SubLoop->ParentLoop = L;
838 L->SubLoops.push_back(SubLoop);
841 // Normal case, add the block to our loop...
842 L->Blocks.push_back(X);
844 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
846 // Add all of the predecessors of X to the end of the work stack...
847 TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
848 InvBlockTraits::child_end(X));
852 // If there are any loops nested within this loop, create them now!
853 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
854 E = L->Blocks.end(); I != E; ++I)
855 if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
856 L->SubLoops.push_back(NewLoop);
857 NewLoop->ParentLoop = L;
860 // Add the basic blocks that comprise this loop to the BBMap so that this
861 // loop can be found for them.
863 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
864 E = L->Blocks.end(); I != E; ++I)
865 BBMap.insert(std::make_pair(*I, L));
867 // Now that we have a list of all of the child loops of this loop, check to
868 // see if any of them should actually be nested inside of each other. We
869 // can accidentally pull loops our of their parents, so we must make sure to
870 // organize the loop nests correctly now.
872 std::map<BlockT *, LoopT *> ContainingLoops;
873 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
874 LoopT *Child = L->SubLoops[i];
875 assert(Child->getParentLoop() == L && "Not proper child loop?");
877 if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
878 // If there is already a loop which contains this loop, move this loop
879 // into the containing loop.
880 MoveSiblingLoopInto(Child, ContainingLoop);
881 --i; // The loop got removed from the SubLoops list.
883 // This is currently considered to be a top-level loop. Check to see
884 // if any of the contained blocks are loop headers for subloops we
885 // have already processed.
886 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
887 LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
888 if (BlockLoop == 0) { // Child block not processed yet...
890 } else if (BlockLoop != Child) {
891 LoopT *SubLoop = BlockLoop;
892 // Reparent all of the blocks which used to belong to BlockLoops
893 for (unsigned j = 0, f = SubLoop->Blocks.size(); j != f; ++j)
894 ContainingLoops[SubLoop->Blocks[j]] = Child;
896 // There is already a loop which contains this block, that means
897 // that we should reparent the loop which the block is currently
898 // considered to belong to to be a child of this loop.
899 MoveSiblingLoopInto(SubLoop, Child);
900 --i; // We just shrunk the SubLoops list.
910 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
911 /// of the NewParent Loop, instead of being a sibling of it.
912 void MoveSiblingLoopInto(LoopT *NewChild,
914 LoopT *OldParent = NewChild->getParentLoop();
915 assert(OldParent && OldParent == NewParent->getParentLoop() &&
916 NewChild != NewParent && "Not sibling loops!");
918 // Remove NewChild from being a child of OldParent
919 typename std::vector<LoopT *>::iterator I =
920 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
922 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
923 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
924 NewChild->ParentLoop = 0;
926 InsertLoopInto(NewChild, NewParent);
929 /// InsertLoopInto - This inserts loop L into the specified parent loop. If
930 /// the parent loop contains a loop which should contain L, the loop gets
931 /// inserted into L instead.
932 void InsertLoopInto(LoopT *L, LoopT *Parent) {
933 BlockT *LHeader = L->getHeader();
934 assert(Parent->contains(LHeader) &&
935 "This loop should not be inserted here!");
937 // Check to see if it belongs in a child loop...
938 for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
940 if (Parent->SubLoops[i]->contains(LHeader)) {
941 InsertLoopInto(L, Parent->SubLoops[i]);
945 // If not, insert it here!
946 Parent->SubLoops.push_back(L);
947 L->ParentLoop = Parent;
952 void print(raw_ostream &OS) const {
953 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
954 TopLevelLoops[i]->print(OS);
956 for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
957 E = BBMap.end(); I != E; ++I)
958 OS << "BB '" << I->first->getName() << "' level = "
959 << I->second->getLoopDepth() << "\n";
964 class LoopInfo : public FunctionPass {
965 LoopInfoBase<BasicBlock, Loop> LI;
966 friend class LoopBase<BasicBlock, Loop>;
968 void operator=(const LoopInfo &); // do not implement
969 LoopInfo(const LoopInfo &); // do not implement
971 static char ID; // Pass identification, replacement for typeid
973 LoopInfo() : FunctionPass(ID) {
974 initializeLoopInfoPass(*PassRegistry::getPassRegistry());
977 LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
979 /// iterator/begin/end - The interface to the top-level loops in the current
982 typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
983 inline iterator begin() const { return LI.begin(); }
984 inline iterator end() const { return LI.end(); }
985 bool empty() const { return LI.empty(); }
987 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
988 /// block is in no loop (for example the entry node), null is returned.
990 inline Loop *getLoopFor(const BasicBlock *BB) const {
991 return LI.getLoopFor(BB);
994 /// operator[] - same as getLoopFor...
996 inline const Loop *operator[](const BasicBlock *BB) const {
997 return LI.getLoopFor(BB);
1000 /// getLoopDepth - Return the loop nesting level of the specified block. A
1001 /// depth of 0 means the block is not inside any loop.
1003 inline unsigned getLoopDepth(const BasicBlock *BB) const {
1004 return LI.getLoopDepth(BB);
1007 // isLoopHeader - True if the block is a loop header node
1008 inline bool isLoopHeader(BasicBlock *BB) const {
1009 return LI.isLoopHeader(BB);
1012 /// runOnFunction - Calculate the natural loop information.
1014 virtual bool runOnFunction(Function &F);
1016 virtual void verifyAnalysis() const;
1018 virtual void releaseMemory() { LI.releaseMemory(); }
1020 virtual void print(raw_ostream &O, const Module* M = 0) const;
1022 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1024 /// removeLoop - This removes the specified top-level loop from this loop info
1025 /// object. The loop is not deleted, as it will presumably be inserted into
1027 inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
1029 /// changeLoopFor - Change the top-level loop that contains BB to the
1030 /// specified loop. This should be used by transformations that restructure
1031 /// the loop hierarchy tree.
1032 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
1033 LI.changeLoopFor(BB, L);
1036 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
1037 /// list with the indicated loop.
1038 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
1039 LI.changeTopLevelLoop(OldLoop, NewLoop);
1042 /// addTopLevelLoop - This adds the specified loop to the collection of
1043 /// top-level loops.
1044 inline void addTopLevelLoop(Loop *New) {
1045 LI.addTopLevelLoop(New);
1048 /// removeBlock - This method completely removes BB from all data structures,
1049 /// including all of the Loop objects it is nested in and our mapping from
1050 /// BasicBlocks to loops.
1051 void removeBlock(BasicBlock *BB) {
1055 /// updateUnloop - Update LoopInfo after removing the last backedge from a
1056 /// loop--now the "unloop". This updates the loop forest and parent loops for
1057 /// each block so that Unloop is no longer referenced, but the caller must
1058 /// actually delete the Unloop object.
1059 void updateUnloop(Loop *Unloop);
1061 /// replacementPreservesLCSSAForm - Returns true if replacing From with To
1062 /// everywhere is guaranteed to preserve LCSSA form.
1063 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
1064 // Preserving LCSSA form is only problematic if the replacing value is an
1066 Instruction *I = dyn_cast<Instruction>(To);
1067 if (!I) return true;
1068 // If both instructions are defined in the same basic block then replacement
1069 // cannot break LCSSA form.
1070 if (I->getParent() == From->getParent())
1072 // If the instruction is not defined in a loop then it can safely replace
1074 Loop *ToLoop = getLoopFor(I->getParent());
1075 if (!ToLoop) return true;
1076 // If the replacing instruction is defined in the same loop as the original
1077 // instruction, or in a loop that contains it as an inner loop, then using
1078 // it as a replacement will not break LCSSA form.
1079 return ToLoop->contains(getLoopFor(From->getParent()));
1084 // Allow clients to walk the list of nested loops...
1085 template <> struct GraphTraits<const Loop*> {
1086 typedef const Loop NodeType;
1087 typedef LoopInfo::iterator ChildIteratorType;
1089 static NodeType *getEntryNode(const Loop *L) { return L; }
1090 static inline ChildIteratorType child_begin(NodeType *N) {
1093 static inline ChildIteratorType child_end(NodeType *N) {
1098 template <> struct GraphTraits<Loop*> {
1099 typedef Loop NodeType;
1100 typedef LoopInfo::iterator ChildIteratorType;
1102 static NodeType *getEntryNode(Loop *L) { return L; }
1103 static inline ChildIteratorType child_begin(NodeType *N) {
1106 static inline ChildIteratorType child_end(NodeType *N) {
1111 template<class BlockT, class LoopT>
1113 LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1114 LoopInfoBase<BlockT, LoopT> &LIB) {
1115 assert((Blocks.empty() || LIB[getHeader()] == this) &&
1116 "Incorrect LI specified for this loop!");
1117 assert(NewBB && "Cannot add a null basic block to the loop!");
1118 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1120 LoopT *L = static_cast<LoopT *>(this);
1122 // Add the loop mapping to the LoopInfo object...
1123 LIB.BBMap[NewBB] = L;
1125 // Add the basic block to this loop and all parent loops...
1127 L->Blocks.push_back(NewBB);
1128 L = L->getParentLoop();
1132 } // End llvm namespace