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/DepthFirstIterator.h"
36 #include "llvm/ADT/GraphTraits.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/Analysis/Dominators.h"
39 #include "llvm/Support/CFG.h"
40 #include "llvm/Support/raw_ostream.h"
46 static void RemoveFromVector(std::vector<T*> &V, T *N) {
47 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
48 assert(I != V.end() && "N is not in this list!");
55 template<class N, class M> class LoopInfoBase;
56 template<class N, class M> class LoopBase;
58 //===----------------------------------------------------------------------===//
59 /// LoopBase class - Instances of this class are used to represent loops that
60 /// are detected in the flow graph
62 template<class BlockT, class LoopT>
65 // SubLoops - Loops contained entirely within this one.
66 std::vector<LoopT *> SubLoops;
68 // Blocks - The list of blocks in this loop. First entry is the header node.
69 std::vector<BlockT*> Blocks;
72 LoopBase(const LoopBase<BlockT, LoopT> &);
74 const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
76 /// Loop ctor - This creates an empty loop.
77 LoopBase() : ParentLoop(0) {}
79 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
83 /// getLoopDepth - Return the nesting level of this loop. An outer-most
84 /// loop has depth 1, for consistency with loop depth values used for basic
85 /// blocks, where depth 0 is used for blocks not inside any loops.
86 unsigned getLoopDepth() const {
88 for (const LoopT *CurLoop = ParentLoop; CurLoop;
89 CurLoop = CurLoop->ParentLoop)
93 BlockT *getHeader() const { return Blocks.front(); }
94 LoopT *getParentLoop() const { return ParentLoop; }
96 /// contains - Return true if the specified basic block is in this loop
98 bool contains(const BlockT *BB) const {
99 return std::find(block_begin(), block_end(), BB) != block_end();
102 /// iterator/begin/end - Return the loops contained entirely within this loop.
104 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
105 typedef typename std::vector<LoopT *>::const_iterator iterator;
106 iterator begin() const { return SubLoops.begin(); }
107 iterator end() const { return SubLoops.end(); }
108 bool empty() const { return SubLoops.empty(); }
110 /// getBlocks - Get a list of the basic blocks which make up this loop.
112 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
113 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
114 block_iterator block_begin() const { return Blocks.begin(); }
115 block_iterator block_end() const { return Blocks.end(); }
117 /// isLoopExiting - True if terminator in the block can branch to another
118 /// block that is outside of the current loop.
120 bool isLoopExiting(const BlockT *BB) const {
121 typedef GraphTraits<BlockT*> BlockTraits;
122 for (typename BlockTraits::ChildIteratorType SI =
123 BlockTraits::child_begin(const_cast<BlockT*>(BB)),
124 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
131 /// getNumBackEdges - Calculate the number of back edges to the loop header
133 unsigned getNumBackEdges() const {
134 unsigned NumBackEdges = 0;
135 BlockT *H = getHeader();
137 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
138 for (typename InvBlockTraits::ChildIteratorType I =
139 InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
140 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
147 //===--------------------------------------------------------------------===//
148 // APIs for simple analysis of the loop.
150 // Note that all of these methods can fail on general loops (ie, there may not
151 // be a preheader, etc). For best success, the loop simplification and
152 // induction variable canonicalization pass should be used to normalize loops
153 // for easy analysis. These methods assume canonical loops.
155 /// getExitingBlocks - Return all blocks inside the loop that have successors
156 /// outside of the loop. These are the blocks _inside of the current loop_
157 /// which branch out. The returned list is always unique.
159 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
160 // Sort the blocks vector so that we can use binary search to do quick
162 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
163 std::sort(LoopBBs.begin(), LoopBBs.end());
165 typedef GraphTraits<BlockT*> BlockTraits;
166 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
167 for (typename BlockTraits::ChildIteratorType I =
168 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
170 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
171 // Not in current loop? It must be an exit block.
172 ExitingBlocks.push_back(*BI);
177 /// getExitingBlock - If getExitingBlocks would return exactly one block,
178 /// return that block. Otherwise return null.
179 BlockT *getExitingBlock() const {
180 SmallVector<BlockT*, 8> ExitingBlocks;
181 getExitingBlocks(ExitingBlocks);
182 if (ExitingBlocks.size() == 1)
183 return ExitingBlocks[0];
187 /// getExitBlocks - Return all of the successor blocks of this loop. These
188 /// are the blocks _outside of the current loop_ which are branched to.
190 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
191 // Sort the blocks vector so that we can use binary search to do quick
193 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
194 std::sort(LoopBBs.begin(), LoopBBs.end());
196 typedef GraphTraits<BlockT*> BlockTraits;
197 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
198 for (typename BlockTraits::ChildIteratorType I =
199 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
201 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
202 // Not in current loop? It must be an exit block.
203 ExitBlocks.push_back(*I);
206 /// getExitBlock - If getExitBlocks would return exactly one block,
207 /// return that block. Otherwise return null.
208 BlockT *getExitBlock() const {
209 SmallVector<BlockT*, 8> ExitBlocks;
210 getExitBlocks(ExitBlocks);
211 if (ExitBlocks.size() == 1)
212 return ExitBlocks[0];
216 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
217 typedef std::pair<const BlockT*,const BlockT*> Edge;
218 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
219 // Sort the blocks vector so that we can use binary search to do quick
221 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
222 std::sort(LoopBBs.begin(), LoopBBs.end());
224 typedef GraphTraits<BlockT*> BlockTraits;
225 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
226 for (typename BlockTraits::ChildIteratorType I =
227 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
229 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
230 // Not in current loop? It must be an exit block.
231 ExitEdges.push_back(std::make_pair(*BI, *I));
234 /// getLoopPreheader - If there is a preheader for this loop, return it. A
235 /// loop has a preheader if there is only one edge to the header of the loop
236 /// from outside of the loop. If this is the case, the block branching to the
237 /// header of the loop is the preheader node.
239 /// This method returns null if there is no preheader for the loop.
241 BlockT *getLoopPreheader() const {
242 // Keep track of nodes outside the loop branching to the header...
245 // Loop over the predecessors of the header node...
246 BlockT *Header = getHeader();
247 typedef GraphTraits<BlockT*> BlockTraits;
248 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
249 for (typename InvBlockTraits::ChildIteratorType PI =
250 InvBlockTraits::child_begin(Header),
251 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
252 if (!contains(*PI)) { // If the block is not in the loop...
253 if (Out && Out != *PI)
254 return 0; // Multiple predecessors outside the loop
258 // Make sure there is only one exit out of the preheader.
259 assert(Out && "Header of loop has no predecessors from outside loop?");
260 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
262 if (SI != BlockTraits::child_end(Out))
263 return 0; // Multiple exits from the block, must not be a preheader.
265 // If there is exactly one preheader, return it. If there was zero, then
266 // Out is still null.
270 /// getLoopLatch - If there is a single latch block for this loop, return it.
271 /// A latch block is a block that contains a branch back to the header.
272 BlockT *getLoopLatch() const {
273 BlockT *Header = getHeader();
274 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
275 typename InvBlockTraits::ChildIteratorType PI =
276 InvBlockTraits::child_begin(Header);
277 typename InvBlockTraits::ChildIteratorType PE =
278 InvBlockTraits::child_end(Header);
280 for (; PI != PE; ++PI)
289 //===--------------------------------------------------------------------===//
290 // APIs for updating loop information after changing the CFG
293 /// addBasicBlockToLoop - This method is used by other analyses to update loop
294 /// information. NewBB is set to be a new member of the current loop.
295 /// Because of this, it is added as a member of all parent loops, and is added
296 /// to the specified LoopInfo object as being in the current basic block. It
297 /// is not valid to replace the loop header with this method.
299 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
301 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
302 /// the OldChild entry in our children list with NewChild, and updates the
303 /// parent pointer of OldChild to be null and the NewChild to be this loop.
304 /// This updates the loop depth of the new child.
305 void replaceChildLoopWith(LoopT *OldChild,
307 assert(OldChild->ParentLoop == this && "This loop is already broken!");
308 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
309 typename std::vector<LoopT *>::iterator I =
310 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
311 assert(I != SubLoops.end() && "OldChild not in loop!");
313 OldChild->ParentLoop = 0;
314 NewChild->ParentLoop = static_cast<LoopT *>(this);
317 /// addChildLoop - Add the specified loop to be a child of this loop. This
318 /// updates the loop depth of the new child.
320 void addChildLoop(LoopT *NewChild) {
321 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
322 NewChild->ParentLoop = static_cast<LoopT *>(this);
323 SubLoops.push_back(NewChild);
326 /// removeChildLoop - This removes the specified child from being a subloop of
327 /// this loop. The loop is not deleted, as it will presumably be inserted
328 /// into another loop.
329 LoopT *removeChildLoop(iterator I) {
330 assert(I != SubLoops.end() && "Cannot remove end iterator!");
332 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
333 SubLoops.erase(SubLoops.begin()+(I-begin()));
334 Child->ParentLoop = 0;
338 /// addBlockEntry - This adds a basic block directly to the basic block list.
339 /// This should only be used by transformations that create new loops. Other
340 /// transformations should use addBasicBlockToLoop.
341 void addBlockEntry(BlockT *BB) {
342 Blocks.push_back(BB);
345 /// moveToHeader - This method is used to move BB (which must be part of this
346 /// loop) to be the loop header of the loop (the block that dominates all
348 void moveToHeader(BlockT *BB) {
349 if (Blocks[0] == BB) return;
350 for (unsigned i = 0; ; ++i) {
351 assert(i != Blocks.size() && "Loop does not contain BB!");
352 if (Blocks[i] == BB) {
353 Blocks[i] = Blocks[0];
360 /// removeBlockFromLoop - This removes the specified basic block from the
361 /// current loop, updating the Blocks as appropriate. This does not update
362 /// the mapping in the LoopInfo class.
363 void removeBlockFromLoop(BlockT *BB) {
364 RemoveFromVector(Blocks, BB);
367 /// verifyLoop - Verify loop structure
368 void verifyLoop() const {
370 assert(!Blocks.empty() && "Loop header is missing");
372 // Sort the blocks vector so that we can use binary search to do quick
374 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
375 std::sort(LoopBBs.begin(), LoopBBs.end());
377 // Check the individual blocks.
378 for (block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
380 bool HasInsideLoopSuccs = false;
381 bool HasInsideLoopPreds = false;
382 SmallVector<BlockT *, 2> OutsideLoopPreds;
384 typedef GraphTraits<BlockT*> BlockTraits;
385 for (typename BlockTraits::ChildIteratorType SI =
386 BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
388 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
389 HasInsideLoopSuccs = true;
392 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
393 for (typename InvBlockTraits::ChildIteratorType PI =
394 InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
396 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *PI))
397 HasInsideLoopPreds = true;
399 OutsideLoopPreds.push_back(*PI);
402 if (BB == getHeader()) {
403 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
404 } else if (!OutsideLoopPreds.empty()) {
405 // A non-header loop shouldn't be reachable from outside the loop,
406 // though it is permitted if the predecessor is not itself actually
408 BlockT *EntryBB = BB->getParent()->begin();
409 for (df_iterator<BlockT *> NI = df_begin(EntryBB),
410 NE = df_end(EntryBB); NI != NE; ++NI)
411 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
412 assert(*NI != OutsideLoopPreds[i] &&
413 "Loop has multiple entry points!");
415 assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
416 assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
417 assert(BB != getHeader()->getParent()->begin() &&
418 "Loop contains function entry block!");
421 // Check the subloops.
422 for (iterator I = begin(), E = end(); I != E; ++I)
423 // Each block in each subloop should be contained within this loop.
424 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
426 assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
427 "Loop does not contain all the blocks of a subloop!");
430 // Check the parent loop pointer.
432 assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
434 "Loop is not a subloop of its parent!");
439 /// verifyLoop - Verify loop structure of this loop and all nested loops.
440 void verifyLoopNest() const {
443 // Verify the subloops.
444 for (iterator I = begin(), E = end(); I != E; ++I)
445 (*I)->verifyLoopNest();
448 void print(raw_ostream &OS, unsigned Depth = 0) const {
449 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
452 for (unsigned i = 0; i < getBlocks().size(); ++i) {
454 BlockT *BB = getBlocks()[i];
455 WriteAsOperand(OS, BB, false);
456 if (BB == getHeader()) OS << "<header>";
457 if (BB == getLoopLatch()) OS << "<latch>";
458 if (isLoopExiting(BB)) OS << "<exiting>";
462 for (iterator I = begin(), E = end(); I != E; ++I)
463 (*I)->print(OS, Depth+2);
471 friend class LoopInfoBase<BlockT, LoopT>;
472 explicit LoopBase(BlockT *BB) : ParentLoop(0) {
473 Blocks.push_back(BB);
477 class Loop : public LoopBase<BasicBlock, Loop> {
481 /// isLoopInvariant - Return true if the specified value is loop invariant
483 bool isLoopInvariant(Value *V) const;
485 /// isLoopInvariant - Return true if the specified instruction is
488 bool isLoopInvariant(Instruction *I) const;
490 /// makeLoopInvariant - If the given value is an instruction inside of the
491 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
492 /// Return true if the value after any hoisting is loop invariant. This
493 /// function can be used as a slightly more aggressive replacement for
496 /// If InsertPt is specified, it is the point to hoist instructions to.
497 /// If null, the terminator of the loop preheader is used.
499 bool makeLoopInvariant(Value *V, bool &Changed,
500 Instruction *InsertPt = 0) const;
502 /// makeLoopInvariant - If the given instruction is inside of the
503 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
504 /// Return true if the instruction after any hoisting is loop invariant. This
505 /// function can be used as a slightly more aggressive replacement for
508 /// If InsertPt is specified, it is the point to hoist instructions to.
509 /// If null, the terminator of the loop preheader is used.
511 bool makeLoopInvariant(Instruction *I, bool &Changed,
512 Instruction *InsertPt = 0) const;
514 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
515 /// induction variable: an integer recurrence that starts at 0 and increments
516 /// by one each time through the loop. If so, return the phi node that
517 /// corresponds to it.
519 /// The IndVarSimplify pass transforms loops to have a canonical induction
522 PHINode *getCanonicalInductionVariable() const;
524 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
525 /// the canonical induction variable value for the "next" iteration of the
526 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
528 Instruction *getCanonicalInductionVariableIncrement() const;
530 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
531 /// times the loop will be executed. Note that this means that the backedge
532 /// of the loop executes N-1 times. If the trip-count cannot be determined,
533 /// this returns null.
535 /// The IndVarSimplify pass transforms loops to have a form that this
536 /// function easily understands.
538 Value *getTripCount() const;
540 /// getSmallConstantTripCount - Returns the trip count of this loop as a
541 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
542 /// of not constant. Will also return 0 if the trip count is very large
544 unsigned getSmallConstantTripCount() const;
546 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
547 /// trip count of this loop as a normal unsigned value, if possible. This
548 /// means that the actual trip count is always a multiple of the returned
549 /// value (don't forget the trip count could very well be zero as well!).
551 /// Returns 1 if the trip count is unknown or not guaranteed to be the
552 /// multiple of a constant (which is also the case if the trip count is simply
553 /// constant, use getSmallConstantTripCount for that case), Will also return 1
554 /// if the trip count is very large (>= 2^32).
555 unsigned getSmallConstantTripMultiple() const;
557 /// isLCSSAForm - Return true if the Loop is in LCSSA form
558 bool isLCSSAForm() const;
560 /// isLoopSimplifyForm - Return true if the Loop is in the form that
561 /// the LoopSimplify form transforms loops to, which is sometimes called
563 bool isLoopSimplifyForm() const;
565 /// hasDedicatedExits - Return true if no exit block for the loop
566 /// has a predecessor that is outside the loop.
567 bool hasDedicatedExits() const;
569 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
570 /// These are the blocks _outside of the current loop_ which are branched to.
571 /// This assumes that loop exits are in canonical form.
573 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
575 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
576 /// block, return that block. Otherwise return null.
577 BasicBlock *getUniqueExitBlock() const;
580 friend class LoopInfoBase<BasicBlock, Loop>;
581 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
584 //===----------------------------------------------------------------------===//
585 /// LoopInfo - This class builds and contains all of the top level loop
586 /// structures in the specified function.
589 template<class BlockT, class LoopT>
591 // BBMap - Mapping of basic blocks to the inner most loop they occur in
592 std::map<BlockT *, LoopT *> BBMap;
593 std::vector<LoopT *> TopLevelLoops;
594 friend class LoopBase<BlockT, LoopT>;
596 void operator=(const LoopInfoBase &); // do not implement
597 LoopInfoBase(const LoopInfo &); // do not implement
600 ~LoopInfoBase() { releaseMemory(); }
602 void releaseMemory() {
603 for (typename std::vector<LoopT *>::iterator I =
604 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
605 delete *I; // Delete all of the loops...
607 BBMap.clear(); // Reset internal state of analysis
608 TopLevelLoops.clear();
611 /// iterator/begin/end - The interface to the top-level loops in the current
614 typedef typename std::vector<LoopT *>::const_iterator iterator;
615 iterator begin() const { return TopLevelLoops.begin(); }
616 iterator end() const { return TopLevelLoops.end(); }
617 bool empty() const { return TopLevelLoops.empty(); }
619 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
620 /// block is in no loop (for example the entry node), null is returned.
622 LoopT *getLoopFor(const BlockT *BB) const {
623 typename std::map<BlockT *, LoopT *>::const_iterator I=
624 BBMap.find(const_cast<BlockT*>(BB));
625 return I != BBMap.end() ? I->second : 0;
628 /// operator[] - same as getLoopFor...
630 const LoopT *operator[](const BlockT *BB) const {
631 return getLoopFor(BB);
634 /// getLoopDepth - Return the loop nesting level of the specified block. A
635 /// depth of 0 means the block is not inside any loop.
637 unsigned getLoopDepth(const BlockT *BB) const {
638 const LoopT *L = getLoopFor(BB);
639 return L ? L->getLoopDepth() : 0;
642 // isLoopHeader - True if the block is a loop header node
643 bool isLoopHeader(BlockT *BB) const {
644 const LoopT *L = getLoopFor(BB);
645 return L && L->getHeader() == BB;
648 /// removeLoop - This removes the specified top-level loop from this loop info
649 /// object. The loop is not deleted, as it will presumably be inserted into
651 LoopT *removeLoop(iterator I) {
652 assert(I != end() && "Cannot remove end iterator!");
654 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
655 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
659 /// changeLoopFor - Change the top-level loop that contains BB to the
660 /// specified loop. This should be used by transformations that restructure
661 /// the loop hierarchy tree.
662 void changeLoopFor(BlockT *BB, LoopT *L) {
663 LoopT *&OldLoop = BBMap[BB];
664 assert(OldLoop && "Block not in a loop yet!");
668 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
669 /// list with the indicated loop.
670 void changeTopLevelLoop(LoopT *OldLoop,
672 typename std::vector<LoopT *>::iterator I =
673 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
674 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
676 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
677 "Loops already embedded into a subloop!");
680 /// addTopLevelLoop - This adds the specified loop to the collection of
682 void addTopLevelLoop(LoopT *New) {
683 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
684 TopLevelLoops.push_back(New);
687 /// removeBlock - This method completely removes BB from all data structures,
688 /// including all of the Loop objects it is nested in and our mapping from
689 /// BasicBlocks to loops.
690 void removeBlock(BlockT *BB) {
691 typename std::map<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
692 if (I != BBMap.end()) {
693 for (LoopT *L = I->second; L; L = L->getParentLoop())
694 L->removeBlockFromLoop(BB);
702 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
703 const LoopT *ParentLoop) {
704 if (SubLoop == 0) return true;
705 if (SubLoop == ParentLoop) return false;
706 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
709 void Calculate(DominatorTreeBase<BlockT> &DT) {
710 BlockT *RootNode = DT.getRootNode()->getBlock();
712 for (df_iterator<BlockT*> NI = df_begin(RootNode),
713 NE = df_end(RootNode); NI != NE; ++NI)
714 if (LoopT *L = ConsiderForLoop(*NI, DT))
715 TopLevelLoops.push_back(L);
718 LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
719 if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
721 std::vector<BlockT *> TodoStack;
723 // Scan the predecessors of BB, checking to see if BB dominates any of
724 // them. This identifies backedges which target this node...
725 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
726 for (typename InvBlockTraits::ChildIteratorType I =
727 InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
729 if (DT.dominates(BB, *I)) // If BB dominates its predecessor...
730 TodoStack.push_back(*I);
732 if (TodoStack.empty()) return 0; // No backedges to this block...
734 // Create a new loop to represent this basic block...
735 LoopT *L = new LoopT(BB);
738 BlockT *EntryBlock = BB->getParent()->begin();
740 while (!TodoStack.empty()) { // Process all the nodes in the loop
741 BlockT *X = TodoStack.back();
742 TodoStack.pop_back();
744 if (!L->contains(X) && // As of yet unprocessed??
745 DT.dominates(EntryBlock, X)) { // X is reachable from entry block?
746 // Check to see if this block already belongs to a loop. If this occurs
747 // then we have a case where a loop that is supposed to be a child of
748 // the current loop was processed before the current loop. When this
749 // occurs, this child loop gets added to a part of the current loop,
750 // making it a sibling to the current loop. We have to reparent this
753 const_cast<LoopT *>(getLoopFor(X)))
754 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
755 // Remove the subloop from its current parent...
756 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
757 LoopT *SLP = SubLoop->ParentLoop; // SubLoopParent
758 typename std::vector<LoopT *>::iterator I =
759 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
760 assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
761 SLP->SubLoops.erase(I); // Remove from parent...
763 // Add the subloop to THIS loop...
764 SubLoop->ParentLoop = L;
765 L->SubLoops.push_back(SubLoop);
768 // Normal case, add the block to our loop...
769 L->Blocks.push_back(X);
771 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
773 // Add all of the predecessors of X to the end of the work stack...
774 TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
775 InvBlockTraits::child_end(X));
779 // If there are any loops nested within this loop, create them now!
780 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
781 E = L->Blocks.end(); I != E; ++I)
782 if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
783 L->SubLoops.push_back(NewLoop);
784 NewLoop->ParentLoop = L;
787 // Add the basic blocks that comprise this loop to the BBMap so that this
788 // loop can be found for them.
790 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
791 E = L->Blocks.end(); I != E; ++I)
792 BBMap.insert(std::make_pair(*I, L));
794 // Now that we have a list of all of the child loops of this loop, check to
795 // see if any of them should actually be nested inside of each other. We
796 // can accidentally pull loops our of their parents, so we must make sure to
797 // organize the loop nests correctly now.
799 std::map<BlockT *, LoopT *> ContainingLoops;
800 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
801 LoopT *Child = L->SubLoops[i];
802 assert(Child->getParentLoop() == L && "Not proper child loop?");
804 if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
805 // If there is already a loop which contains this loop, move this loop
806 // into the containing loop.
807 MoveSiblingLoopInto(Child, ContainingLoop);
808 --i; // The loop got removed from the SubLoops list.
810 // This is currently considered to be a top-level loop. Check to see
811 // if any of the contained blocks are loop headers for subloops we
812 // have already processed.
813 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
814 LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
815 if (BlockLoop == 0) { // Child block not processed yet...
817 } else if (BlockLoop != Child) {
818 LoopT *SubLoop = BlockLoop;
819 // Reparent all of the blocks which used to belong to BlockLoops
820 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
821 ContainingLoops[SubLoop->Blocks[j]] = Child;
823 // There is already a loop which contains this block, that means
824 // that we should reparent the loop which the block is currently
825 // considered to belong to to be a child of this loop.
826 MoveSiblingLoopInto(SubLoop, Child);
827 --i; // We just shrunk the SubLoops list.
837 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
838 /// of the NewParent Loop, instead of being a sibling of it.
839 void MoveSiblingLoopInto(LoopT *NewChild,
841 LoopT *OldParent = NewChild->getParentLoop();
842 assert(OldParent && OldParent == NewParent->getParentLoop() &&
843 NewChild != NewParent && "Not sibling loops!");
845 // Remove NewChild from being a child of OldParent
846 typename std::vector<LoopT *>::iterator I =
847 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
849 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
850 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
851 NewChild->ParentLoop = 0;
853 InsertLoopInto(NewChild, NewParent);
856 /// InsertLoopInto - This inserts loop L into the specified parent loop. If
857 /// the parent loop contains a loop which should contain L, the loop gets
858 /// inserted into L instead.
859 void InsertLoopInto(LoopT *L, LoopT *Parent) {
860 BlockT *LHeader = L->getHeader();
861 assert(Parent->contains(LHeader) &&
862 "This loop should not be inserted here!");
864 // Check to see if it belongs in a child loop...
865 for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
867 if (Parent->SubLoops[i]->contains(LHeader)) {
868 InsertLoopInto(L, Parent->SubLoops[i]);
872 // If not, insert it here!
873 Parent->SubLoops.push_back(L);
874 L->ParentLoop = Parent;
879 void print(raw_ostream &OS) const {
880 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
881 TopLevelLoops[i]->print(OS);
883 for (std::map<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
884 E = BBMap.end(); I != E; ++I)
885 OS << "BB '" << I->first->getName() << "' level = "
886 << I->second->getLoopDepth() << "\n";
891 class LoopInfo : public FunctionPass {
892 LoopInfoBase<BasicBlock, Loop> LI;
893 friend class LoopBase<BasicBlock, Loop>;
895 void operator=(const LoopInfo &); // do not implement
896 LoopInfo(const LoopInfo &); // do not implement
898 static char ID; // Pass identification, replacement for typeid
900 LoopInfo() : FunctionPass(&ID) {}
902 LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
904 /// iterator/begin/end - The interface to the top-level loops in the current
907 typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
908 inline iterator begin() const { return LI.begin(); }
909 inline iterator end() const { return LI.end(); }
910 bool empty() const { return LI.empty(); }
912 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
913 /// block is in no loop (for example the entry node), null is returned.
915 inline Loop *getLoopFor(const BasicBlock *BB) const {
916 return LI.getLoopFor(BB);
919 /// operator[] - same as getLoopFor...
921 inline const Loop *operator[](const BasicBlock *BB) const {
922 return LI.getLoopFor(BB);
925 /// getLoopDepth - Return the loop nesting level of the specified block. A
926 /// depth of 0 means the block is not inside any loop.
928 inline unsigned getLoopDepth(const BasicBlock *BB) const {
929 return LI.getLoopDepth(BB);
932 // isLoopHeader - True if the block is a loop header node
933 inline bool isLoopHeader(BasicBlock *BB) const {
934 return LI.isLoopHeader(BB);
937 /// runOnFunction - Calculate the natural loop information.
939 virtual bool runOnFunction(Function &F);
941 virtual void verifyAnalysis() const;
943 virtual void releaseMemory() { LI.releaseMemory(); }
945 virtual void print(raw_ostream &O, const Module* M = 0) const;
947 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
949 /// removeLoop - This removes the specified top-level loop from this loop info
950 /// object. The loop is not deleted, as it will presumably be inserted into
952 inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
954 /// changeLoopFor - Change the top-level loop that contains BB to the
955 /// specified loop. This should be used by transformations that restructure
956 /// the loop hierarchy tree.
957 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
958 LI.changeLoopFor(BB, L);
961 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
962 /// list with the indicated loop.
963 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
964 LI.changeTopLevelLoop(OldLoop, NewLoop);
967 /// addTopLevelLoop - This adds the specified loop to the collection of
969 inline void addTopLevelLoop(Loop *New) {
970 LI.addTopLevelLoop(New);
973 /// removeBlock - This method completely removes BB from all data structures,
974 /// including all of the Loop objects it is nested in and our mapping from
975 /// BasicBlocks to loops.
976 void removeBlock(BasicBlock *BB) {
982 // Allow clients to walk the list of nested loops...
983 template <> struct GraphTraits<const Loop*> {
984 typedef const Loop NodeType;
985 typedef LoopInfo::iterator ChildIteratorType;
987 static NodeType *getEntryNode(const Loop *L) { return L; }
988 static inline ChildIteratorType child_begin(NodeType *N) {
991 static inline ChildIteratorType child_end(NodeType *N) {
996 template <> struct GraphTraits<Loop*> {
997 typedef Loop NodeType;
998 typedef LoopInfo::iterator ChildIteratorType;
1000 static NodeType *getEntryNode(Loop *L) { return L; }
1001 static inline ChildIteratorType child_begin(NodeType *N) {
1004 static inline ChildIteratorType child_end(NodeType *N) {
1009 template<class BlockT, class LoopT>
1011 LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1012 LoopInfoBase<BlockT, LoopT> &LIB) {
1013 assert((Blocks.empty() || LIB[getHeader()] == this) &&
1014 "Incorrect LI specified for this loop!");
1015 assert(NewBB && "Cannot add a null basic block to the loop!");
1016 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1018 LoopT *L = static_cast<LoopT *>(this);
1020 // Add the loop mapping to the LoopInfo object...
1021 LIB.BBMap[NewBB] = L;
1023 // Add the basic block to this loop and all parent loops...
1025 L->Blocks.push_back(NewBB);
1026 L = L->getParentLoop();
1030 } // End llvm namespace