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. Note that natural
12 // loops may actually be several loops that share the same header node.
14 // This analysis calculates the nesting structure of loops in a function. For
15 // each natural loop identified, this analysis identifies natural loops
16 // contained entirely within the loop and the basic blocks the make up the loop.
18 // It can calculate on the fly various bits of information, for example:
20 // * whether there is a preheader for the loop
21 // * the number of back edges to the header
22 // * whether or not a particular block branches out of the loop
23 // * 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/Constants.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/ADT/DepthFirstIterator.h"
37 #include "llvm/ADT/GraphTraits.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Support/CFG.h"
42 #include "llvm/Support/Streams.h"
47 static void RemoveFromVector(std::vector<T*> &V, T *N) {
48 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
49 assert(I != V.end() && "N is not in this list!");
59 template<class N> class LoopInfoBase;
60 template<class N> class LoopBase;
62 typedef LoopBase<BasicBlock> Loop;
64 //===----------------------------------------------------------------------===//
65 /// LoopBase class - Instances of this class are used to represent loops that
66 /// are detected in the flow graph
68 template<class BlockT>
70 LoopBase<BlockT> *ParentLoop;
71 // SubLoops - Loops contained entirely within this one.
72 std::vector<LoopBase<BlockT>*> SubLoops;
74 // Blocks - The list of blocks in this loop. First entry is the header node.
75 std::vector<BlockT*> Blocks;
77 LoopBase(const LoopBase<BlockT> &); // DO NOT IMPLEMENT
78 const LoopBase<BlockT>&operator=(const LoopBase<BlockT> &);// DO NOT IMPLEMENT
80 /// Loop ctor - This creates an empty loop.
81 LoopBase() : ParentLoop(0) {}
83 for (unsigned 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 LoopBase<BlockT> *CurLoop = ParentLoop; CurLoop;
93 CurLoop = CurLoop->ParentLoop)
97 BlockT *getHeader() const { return Blocks.front(); }
98 LoopBase<BlockT> *getParentLoop() const { return ParentLoop; }
100 /// contains - Return true if the specified basic block is in this loop
102 bool contains(const BlockT *BB) const {
103 return std::find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
106 /// iterator/begin/end - Return the loops contained entirely within this loop.
108 const std::vector<LoopBase<BlockT>*> &getSubLoops() const { return SubLoops; }
109 typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
110 iterator begin() const { return SubLoops.begin(); }
111 iterator end() const { return SubLoops.end(); }
112 bool empty() const { return SubLoops.empty(); }
114 /// getBlocks - Get a list of the basic blocks which make up this loop.
116 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
117 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
118 block_iterator block_begin() const { return Blocks.begin(); }
119 block_iterator block_end() const { return Blocks.end(); }
121 /// isLoopExit - True if terminator in the block can branch to another block
122 /// that is outside of the current loop.
124 bool isLoopExit(const BlockT *BB) const {
125 typedef GraphTraits<BlockT*> BlockTraits;
126 for (typename BlockTraits::ChildIteratorType SI =
127 BlockTraits::child_begin(const_cast<BlockT*>(BB)),
128 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
135 /// getNumBackEdges - Calculate the number of back edges to the loop header
137 unsigned getNumBackEdges() const {
138 unsigned NumBackEdges = 0;
139 BlockT *H = getHeader();
141 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
142 for (typename InvBlockTraits::ChildIteratorType I =
143 InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
144 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
151 /// isLoopInvariant - Return true if the specified value is loop invariant
153 inline bool isLoopInvariant(Value *V) const {
154 if (Instruction *I = dyn_cast<Instruction>(V))
155 return !contains(I->getParent());
156 return true; // All non-instructions are loop invariant
159 //===--------------------------------------------------------------------===//
160 // APIs for simple analysis of the loop.
162 // Note that all of these methods can fail on general loops (ie, there may not
163 // be a preheader, etc). For best success, the loop simplification and
164 // induction variable canonicalization pass should be used to normalize loops
165 // for easy analysis. These methods assume canonical loops.
167 /// getExitingBlocks - Return all blocks inside the loop that have successors
168 /// outside of the loop. These are the blocks _inside of the current loop_
169 /// which branch out. The returned list is always unique.
171 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
172 // Sort the blocks vector so that we can use binary search to do quick
174 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
175 std::sort(LoopBBs.begin(), LoopBBs.end());
177 typedef GraphTraits<BlockT*> BlockTraits;
178 for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
179 BE = Blocks.end(); BI != BE; ++BI)
180 for (typename BlockTraits::ChildIteratorType I =
181 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
183 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
184 // Not in current loop? It must be an exit block.
185 ExitingBlocks.push_back(*BI);
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 {
194 // Sort the blocks vector so that we can use binary search to do quick
196 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
197 std::sort(LoopBBs.begin(), LoopBBs.end());
199 typedef GraphTraits<BlockT*> BlockTraits;
200 for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
201 BE = Blocks.end(); BI != BE; ++BI)
202 for (typename BlockTraits::ChildIteratorType I =
203 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
205 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
206 // Not in current loop? It must be an exit block.
207 ExitBlocks.push_back(*I);
210 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
211 /// These are the blocks _outside of the current loop_ which are branched to.
212 /// This assumes that loop is in canonical form.
214 void getUniqueExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
215 // Sort the blocks vector so that we can use binary search to do quick
217 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
218 std::sort(LoopBBs.begin(), LoopBBs.end());
220 std::vector<BlockT*> switchExitBlocks;
222 for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
223 BE = Blocks.end(); BI != BE; ++BI) {
225 BlockT *current = *BI;
226 switchExitBlocks.clear();
228 typedef GraphTraits<BlockT*> BlockTraits;
229 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
230 for (typename BlockTraits::ChildIteratorType I =
231 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
233 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
234 // If block is inside the loop then it is not a exit block.
237 typename InvBlockTraits::ChildIteratorType PI =
238 InvBlockTraits::child_begin(*I);
239 BlockT *firstPred = *PI;
241 // If current basic block is this exit block's first predecessor
242 // then only insert exit block in to the output ExitBlocks vector.
243 // This ensures that same exit block is not inserted twice into
244 // ExitBlocks vector.
245 if (current != firstPred)
248 // If a terminator has more then two successors, for example SwitchInst,
249 // then it is possible that there are multiple edges from current block
250 // to one exit block.
251 if (std::distance(BlockTraits::child_begin(current),
252 BlockTraits::child_end(current)) <= 2) {
253 ExitBlocks.push_back(*I);
257 // In case of multiple edges from current block to exit block, collect
258 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
260 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
261 == switchExitBlocks.end()) {
262 switchExitBlocks.push_back(*I);
263 ExitBlocks.push_back(*I);
269 /// getLoopPreheader - If there is a preheader for this loop, return it. A
270 /// loop has a preheader if there is only one edge to the header of the loop
271 /// from outside of the loop. If this is the case, the block branching to the
272 /// header of the loop is the preheader node.
274 /// This method returns null if there is no preheader for the loop.
276 BlockT *getLoopPreheader() const {
277 // Keep track of nodes outside the loop branching to the header...
280 // Loop over the predecessors of the header node...
281 BlockT *Header = getHeader();
282 typedef GraphTraits<BlockT*> BlockTraits;
283 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
284 for (typename InvBlockTraits::ChildIteratorType PI =
285 InvBlockTraits::child_begin(Header),
286 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
287 if (!contains(*PI)) { // If the block is not in the loop...
288 if (Out && Out != *PI)
289 return 0; // Multiple predecessors outside the loop
293 // Make sure there is only one exit out of the preheader.
294 assert(Out && "Header of loop has no predecessors from outside loop?");
295 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
297 if (SI != BlockTraits::child_end(Out))
298 return 0; // Multiple exits from the block, must not be a preheader.
300 // If there is exactly one preheader, return it. If there was zero, then
301 // Out is still null.
305 /// getLoopLatch - If there is a latch block for this loop, return it. A
306 /// latch block is the canonical backedge for a loop. A loop header in normal
307 /// form has two edges into it: one from a preheader and one from a latch
309 BlockT *getLoopLatch() const {
310 BlockT *Header = getHeader();
311 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
312 typename InvBlockTraits::ChildIteratorType PI =
313 InvBlockTraits::child_begin(Header);
314 typename InvBlockTraits::ChildIteratorType PE =
315 InvBlockTraits::child_end(Header);
316 if (PI == PE) return 0; // no preds?
322 if (PI == PE) return 0; // only one pred?
325 if (Latch) return 0; // multiple backedges
329 if (PI != PE) return 0; // more than two preds
334 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
335 /// induction variable: an integer recurrence that starts at 0 and increments
336 /// by one each time through the loop. If so, return the phi node that
337 /// corresponds to it.
339 inline PHINode *getCanonicalInductionVariable() const {
340 BlockT *H = getHeader();
342 BlockT *Incoming = 0, *Backedge = 0;
343 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
344 typename InvBlockTraits::ChildIteratorType PI =
345 InvBlockTraits::child_begin(H);
346 assert(PI != InvBlockTraits::child_end(H) &&
347 "Loop must have at least one backedge!");
349 if (PI == InvBlockTraits::child_end(H)) return 0; // dead loop
351 if (PI != InvBlockTraits::child_end(H)) return 0; // multiple backedges?
353 if (contains(Incoming)) {
354 if (contains(Backedge))
356 std::swap(Incoming, Backedge);
357 } else if (!contains(Backedge))
360 // Loop over all of the PHI nodes, looking for a canonical indvar.
361 for (typename BlockT::iterator I = H->begin(); isa<PHINode>(I); ++I) {
362 PHINode *PN = cast<PHINode>(I);
363 if (ConstantInt *CI =
364 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
365 if (CI->isNullValue())
366 if (Instruction *Inc =
367 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
368 if (Inc->getOpcode() == Instruction::Add &&
369 Inc->getOperand(0) == PN)
370 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
371 if (CI->equalsInt(1))
377 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
378 /// the canonical induction variable value for the "next" iteration of the
379 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
381 inline Instruction *getCanonicalInductionVariableIncrement() const {
382 if (PHINode *PN = getCanonicalInductionVariable()) {
383 bool P1InLoop = contains(PN->getIncomingBlock(1));
384 return cast<Instruction>(PN->getIncomingValue(P1InLoop));
389 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
390 /// times the loop will be executed. Note that this means that the backedge
391 /// of the loop executes N-1 times. If the trip-count cannot be determined,
392 /// this returns null.
394 inline Value *getTripCount() const {
395 // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
396 // canonical induction variable and V is the trip count of the loop.
397 Instruction *Inc = getCanonicalInductionVariableIncrement();
398 if (Inc == 0) return 0;
399 PHINode *IV = cast<PHINode>(Inc->getOperand(0));
401 BlockT *BackedgeBlock =
402 IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
404 if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
405 if (BI->isConditional()) {
406 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
407 if (ICI->getOperand(0) == Inc) {
408 if (BI->getSuccessor(0) == getHeader()) {
409 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
410 return ICI->getOperand(1);
411 } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
412 return ICI->getOperand(1);
421 /// isLCSSAForm - Return true if the Loop is in LCSSA form
422 inline bool isLCSSAForm() const {
423 // Sort the blocks vector so that we can use binary search to do quick
425 SmallPtrSet<BlockT*, 16> LoopBBs(block_begin(), block_end());
427 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
429 for (typename BlockT::iterator I = BB->begin(), E = BB->end(); I != E;++I)
430 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
432 BlockT *UserBB = cast<Instruction>(*UI)->getParent();
433 if (PHINode *P = dyn_cast<PHINode>(*UI)) {
434 unsigned OperandNo = UI.getOperandNo();
435 UserBB = P->getIncomingBlock(OperandNo/2);
438 // Check the current block, as a fast-path. Most values are used in
439 // the same block they are defined in.
440 if (UserBB != BB && !LoopBBs.count(UserBB))
448 //===--------------------------------------------------------------------===//
449 // APIs for updating loop information after changing the CFG
452 /// addBasicBlockToLoop - This method is used by other analyses to update loop
453 /// information. NewBB is set to be a new member of the current loop.
454 /// Because of this, it is added as a member of all parent loops, and is added
455 /// to the specified LoopInfo object as being in the current basic block. It
456 /// is not valid to replace the loop header with this method.
458 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT> &LI);
460 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
461 /// the OldChild entry in our children list with NewChild, and updates the
462 /// parent pointer of OldChild to be null and the NewChild to be this loop.
463 /// This updates the loop depth of the new child.
464 void replaceChildLoopWith(LoopBase<BlockT> *OldChild,
465 LoopBase<BlockT> *NewChild) {
466 assert(OldChild->ParentLoop == this && "This loop is already broken!");
467 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
468 typename std::vector<LoopBase<BlockT>*>::iterator I =
469 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
470 assert(I != SubLoops.end() && "OldChild not in loop!");
472 OldChild->ParentLoop = 0;
473 NewChild->ParentLoop = this;
476 /// addChildLoop - Add the specified loop to be a child of this loop. This
477 /// updates the loop depth of the new child.
479 void addChildLoop(LoopBase<BlockT> *NewChild) {
480 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
481 NewChild->ParentLoop = this;
482 SubLoops.push_back(NewChild);
485 /// removeChildLoop - This removes the specified child from being a subloop of
486 /// this loop. The loop is not deleted, as it will presumably be inserted
487 /// into another loop.
488 LoopBase<BlockT> *removeChildLoop(iterator I) {
489 assert(I != SubLoops.end() && "Cannot remove end iterator!");
490 LoopBase<BlockT> *Child = *I;
491 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
492 SubLoops.erase(SubLoops.begin()+(I-begin()));
493 Child->ParentLoop = 0;
497 /// addBlockEntry - This adds a basic block directly to the basic block list.
498 /// This should only be used by transformations that create new loops. Other
499 /// transformations should use addBasicBlockToLoop.
500 void addBlockEntry(BlockT *BB) {
501 Blocks.push_back(BB);
504 /// moveToHeader - This method is used to move BB (which must be part of this
505 /// loop) to be the loop header of the loop (the block that dominates all
507 void moveToHeader(BlockT *BB) {
508 if (Blocks[0] == BB) return;
509 for (unsigned i = 0; ; ++i) {
510 assert(i != Blocks.size() && "Loop does not contain BB!");
511 if (Blocks[i] == BB) {
512 Blocks[i] = Blocks[0];
519 /// removeBlockFromLoop - This removes the specified basic block from the
520 /// current loop, updating the Blocks as appropriate. This does not update
521 /// the mapping in the LoopInfo class.
522 void removeBlockFromLoop(BlockT *BB) {
523 RemoveFromVector(Blocks, BB);
526 /// verifyLoop - Verify loop structure
527 void verifyLoop() const {
529 assert (getHeader() && "Loop header is missing");
530 assert (getLoopPreheader() && "Loop preheader is missing");
531 assert (getLoopLatch() && "Loop latch is missing");
532 for (typename std::vector<LoopBase<BlockT>*>::const_iterator I =
533 SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
538 void print(std::ostream &OS, unsigned Depth = 0) const {
539 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
541 for (unsigned i = 0; i < getBlocks().size(); ++i) {
543 WriteAsOperand(OS, getBlocks()[i], false);
547 for (iterator I = begin(), E = end(); I != E; ++I)
548 (*I)->print(OS, Depth+2);
551 void print(std::ostream *O, unsigned Depth = 0) const {
552 if (O) print(*O, Depth);
560 friend class LoopInfoBase<BlockT>;
561 LoopBase(BlockT *BB) : ParentLoop(0) {
562 Blocks.push_back(BB);
567 //===----------------------------------------------------------------------===//
568 /// LoopInfo - This class builds and contains all of the top level loop
569 /// structures in the specified function.
572 template<class BlockT>
574 // BBMap - Mapping of basic blocks to the inner most loop they occur in
575 std::map<BlockT*, LoopBase<BlockT>*> BBMap;
576 std::vector<LoopBase<BlockT>*> TopLevelLoops;
577 friend class LoopBase<BlockT>;
581 ~LoopInfoBase() { releaseMemory(); }
583 void releaseMemory() {
584 for (typename std::vector<LoopBase<BlockT>* >::iterator I =
585 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
586 delete *I; // Delete all of the loops...
588 BBMap.clear(); // Reset internal state of analysis
589 TopLevelLoops.clear();
592 /// iterator/begin/end - The interface to the top-level loops in the current
595 typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
596 iterator begin() const { return TopLevelLoops.begin(); }
597 iterator end() const { return TopLevelLoops.end(); }
599 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
600 /// block is in no loop (for example the entry node), null is returned.
602 LoopBase<BlockT> *getLoopFor(const BlockT *BB) const {
603 typename std::map<BlockT *, LoopBase<BlockT>*>::const_iterator I=
604 BBMap.find(const_cast<BlockT*>(BB));
605 return I != BBMap.end() ? I->second : 0;
608 /// operator[] - same as getLoopFor...
610 const LoopBase<BlockT> *operator[](const BlockT *BB) const {
611 return getLoopFor(BB);
614 /// getLoopDepth - Return the loop nesting level of the specified block. A
615 /// depth of 0 means the block is not inside any loop.
617 unsigned getLoopDepth(const BlockT *BB) const {
618 const LoopBase<BlockT> *L = getLoopFor(BB);
619 return L ? L->getLoopDepth() : 0;
622 // isLoopHeader - True if the block is a loop header node
623 bool isLoopHeader(BlockT *BB) const {
624 const LoopBase<BlockT> *L = getLoopFor(BB);
625 return L && L->getHeader() == BB;
628 /// removeLoop - This removes the specified top-level loop from this loop info
629 /// object. The loop is not deleted, as it will presumably be inserted into
631 LoopBase<BlockT> *removeLoop(iterator I) {
632 assert(I != end() && "Cannot remove end iterator!");
633 LoopBase<BlockT> *L = *I;
634 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
635 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
639 /// changeLoopFor - Change the top-level loop that contains BB to the
640 /// specified loop. This should be used by transformations that restructure
641 /// the loop hierarchy tree.
642 void changeLoopFor(BlockT *BB, LoopBase<BlockT> *L) {
643 LoopBase<BlockT> *&OldLoop = BBMap[BB];
644 assert(OldLoop && "Block not in a loop yet!");
648 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
649 /// list with the indicated loop.
650 void changeTopLevelLoop(LoopBase<BlockT> *OldLoop,
651 LoopBase<BlockT> *NewLoop) {
652 typename std::vector<LoopBase<BlockT>*>::iterator I =
653 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
654 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
656 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
657 "Loops already embedded into a subloop!");
660 /// addTopLevelLoop - This adds the specified loop to the collection of
662 void addTopLevelLoop(LoopBase<BlockT> *New) {
663 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
664 TopLevelLoops.push_back(New);
667 /// removeBlock - This method completely removes BB from all data structures,
668 /// including all of the Loop objects it is nested in and our mapping from
669 /// BasicBlocks to loops.
670 void removeBlock(BlockT *BB) {
671 typename std::map<BlockT *, LoopBase<BlockT>*>::iterator I = BBMap.find(BB);
672 if (I != BBMap.end()) {
673 for (LoopBase<BlockT> *L = I->second; L; L = L->getParentLoop())
674 L->removeBlockFromLoop(BB);
682 static bool isNotAlreadyContainedIn(LoopBase<BlockT> *SubLoop,
683 LoopBase<BlockT> *ParentLoop) {
684 if (SubLoop == 0) return true;
685 if (SubLoop == ParentLoop) return false;
686 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
689 void Calculate(DominatorTreeBase<BlockT> &DT) {
690 BlockT *RootNode = DT.getRootNode()->getBlock();
692 for (df_iterator<BlockT*> NI = df_begin(RootNode),
693 NE = df_end(RootNode); NI != NE; ++NI)
694 if (LoopBase<BlockT> *L = ConsiderForLoop(*NI, DT))
695 TopLevelLoops.push_back(L);
698 LoopBase<BlockT> *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
699 if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
701 std::vector<BlockT *> TodoStack;
703 // Scan the predecessors of BB, checking to see if BB dominates any of
704 // them. This identifies backedges which target this node...
705 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
706 for (typename InvBlockTraits::ChildIteratorType I =
707 InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
709 if (DT.dominates(BB, *I)) // If BB dominates it's predecessor...
710 TodoStack.push_back(*I);
712 if (TodoStack.empty()) return 0; // No backedges to this block...
714 // Create a new loop to represent this basic block...
715 LoopBase<BlockT> *L = new LoopBase<BlockT>(BB);
718 BlockT *EntryBlock = BB->getParent()->begin();
720 while (!TodoStack.empty()) { // Process all the nodes in the loop
721 BlockT *X = TodoStack.back();
722 TodoStack.pop_back();
724 if (!L->contains(X) && // As of yet unprocessed??
725 DT.dominates(EntryBlock, X)) { // X is reachable from entry block?
726 // Check to see if this block already belongs to a loop. If this occurs
727 // then we have a case where a loop that is supposed to be a child of
728 // the current loop was processed before the current loop. When this
729 // occurs, this child loop gets added to a part of the current loop,
730 // making it a sibling to the current loop. We have to reparent this
732 if (LoopBase<BlockT> *SubLoop =
733 const_cast<LoopBase<BlockT>*>(getLoopFor(X)))
734 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
735 // Remove the subloop from it's current parent...
736 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
737 LoopBase<BlockT> *SLP = SubLoop->ParentLoop; // SubLoopParent
738 typename std::vector<LoopBase<BlockT>*>::iterator I =
739 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
740 assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
741 SLP->SubLoops.erase(I); // Remove from parent...
743 // Add the subloop to THIS loop...
744 SubLoop->ParentLoop = L;
745 L->SubLoops.push_back(SubLoop);
748 // Normal case, add the block to our loop...
749 L->Blocks.push_back(X);
751 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
753 // Add all of the predecessors of X to the end of the work stack...
754 TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
755 InvBlockTraits::child_end(X));
759 // If there are any loops nested within this loop, create them now!
760 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
761 E = L->Blocks.end(); I != E; ++I)
762 if (LoopBase<BlockT> *NewLoop = ConsiderForLoop(*I, DT)) {
763 L->SubLoops.push_back(NewLoop);
764 NewLoop->ParentLoop = L;
767 // Add the basic blocks that comprise this loop to the BBMap so that this
768 // loop can be found for them.
770 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
771 E = L->Blocks.end(); I != E; ++I) {
772 typename std::map<BlockT*, LoopBase<BlockT>*>::iterator BBMI =
773 BBMap.lower_bound(*I);
774 if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet...
775 BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level
778 // Now that we have a list of all of the child loops of this loop, check to
779 // see if any of them should actually be nested inside of each other. We
780 // can accidentally pull loops our of their parents, so we must make sure to
781 // organize the loop nests correctly now.
783 std::map<BlockT*, LoopBase<BlockT>*> ContainingLoops;
784 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
785 LoopBase<BlockT> *Child = L->SubLoops[i];
786 assert(Child->getParentLoop() == L && "Not proper child loop?");
788 if (LoopBase<BlockT> *ContainingLoop =
789 ContainingLoops[Child->getHeader()]) {
790 // If there is already a loop which contains this loop, move this loop
791 // into the containing loop.
792 MoveSiblingLoopInto(Child, ContainingLoop);
793 --i; // The loop got removed from the SubLoops list.
795 // This is currently considered to be a top-level loop. Check to see
796 // if any of the contained blocks are loop headers for subloops we
797 // have already processed.
798 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
799 LoopBase<BlockT> *&BlockLoop = ContainingLoops[Child->Blocks[b]];
800 if (BlockLoop == 0) { // Child block not processed yet...
802 } else if (BlockLoop != Child) {
803 LoopBase<BlockT> *SubLoop = BlockLoop;
804 // Reparent all of the blocks which used to belong to BlockLoops
805 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
806 ContainingLoops[SubLoop->Blocks[j]] = Child;
808 // There is already a loop which contains this block, that means
809 // that we should reparent the loop which the block is currently
810 // considered to belong to to be a child of this loop.
811 MoveSiblingLoopInto(SubLoop, Child);
812 --i; // We just shrunk the SubLoops list.
822 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
823 /// of the NewParent Loop, instead of being a sibling of it.
824 void MoveSiblingLoopInto(LoopBase<BlockT> *NewChild,
825 LoopBase<BlockT> *NewParent) {
826 LoopBase<BlockT> *OldParent = NewChild->getParentLoop();
827 assert(OldParent && OldParent == NewParent->getParentLoop() &&
828 NewChild != NewParent && "Not sibling loops!");
830 // Remove NewChild from being a child of OldParent
831 typename std::vector<LoopBase<BlockT>*>::iterator I =
832 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
834 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
835 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
836 NewChild->ParentLoop = 0;
838 InsertLoopInto(NewChild, NewParent);
841 /// InsertLoopInto - This inserts loop L into the specified parent loop. If
842 /// the parent loop contains a loop which should contain L, the loop gets
843 /// inserted into L instead.
844 void InsertLoopInto(LoopBase<BlockT> *L, LoopBase<BlockT> *Parent) {
845 BlockT *LHeader = L->getHeader();
846 assert(Parent->contains(LHeader) &&
847 "This loop should not be inserted here!");
849 // Check to see if it belongs in a child loop...
850 for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
851 if (Parent->SubLoops[i]->contains(LHeader)) {
852 InsertLoopInto(L, Parent->SubLoops[i]);
856 // If not, insert it here!
857 Parent->SubLoops.push_back(L);
858 L->ParentLoop = Parent;
863 void print(std::ostream &OS, const Module* ) const {
864 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
865 TopLevelLoops[i]->print(OS);
867 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
868 E = BBMap.end(); I != E; ++I)
869 OS << "BB '" << I->first->getName() << "' level = "
870 << I->second->getLoopDepth() << "\n";
875 class LoopInfo : public FunctionPass {
876 LoopInfoBase<BasicBlock>* LI;
877 friend class LoopBase<BasicBlock>;
880 static char ID; // Pass identification, replacement for typeid
882 LoopInfo() : FunctionPass(intptr_t(&ID)) {
883 LI = new LoopInfoBase<BasicBlock>();
886 ~LoopInfo() { delete LI; }
888 LoopInfoBase<BasicBlock>& getBase() { return *LI; }
890 /// iterator/begin/end - The interface to the top-level loops in the current
893 typedef std::vector<Loop*>::const_iterator iterator;
894 inline iterator begin() const { return LI->begin(); }
895 inline iterator end() const { return LI->end(); }
897 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
898 /// block is in no loop (for example the entry node), null is returned.
900 inline Loop *getLoopFor(const BasicBlock *BB) const {
901 return LI->getLoopFor(BB);
904 /// operator[] - same as getLoopFor...
906 inline const Loop *operator[](const BasicBlock *BB) const {
907 return LI->getLoopFor(BB);
910 /// getLoopDepth - Return the loop nesting level of the specified block. A
911 /// depth of 0 means the block is not inside any loop.
913 inline unsigned getLoopDepth(const BasicBlock *BB) const {
914 return LI->getLoopDepth(BB);
917 // isLoopHeader - True if the block is a loop header node
918 inline bool isLoopHeader(BasicBlock *BB) const {
919 return LI->isLoopHeader(BB);
922 /// runOnFunction - Calculate the natural loop information.
924 virtual bool runOnFunction(Function &F);
926 virtual void releaseMemory() { LI->releaseMemory(); }
928 virtual void print(std::ostream &O, const Module* M = 0) const {
929 if (O) LI->print(O, M);
932 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
934 /// removeLoop - This removes the specified top-level loop from this loop info
935 /// object. The loop is not deleted, as it will presumably be inserted into
937 inline Loop *removeLoop(iterator I) { return LI->removeLoop(I); }
939 /// changeLoopFor - Change the top-level loop that contains BB to the
940 /// specified loop. This should be used by transformations that restructure
941 /// the loop hierarchy tree.
942 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
943 LI->changeLoopFor(BB, L);
946 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
947 /// list with the indicated loop.
948 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
949 LI->changeTopLevelLoop(OldLoop, NewLoop);
952 /// addTopLevelLoop - This adds the specified loop to the collection of
954 inline void addTopLevelLoop(Loop *New) {
955 LI->addTopLevelLoop(New);
958 /// removeBlock - This method completely removes BB from all data structures,
959 /// including all of the Loop objects it is nested in and our mapping from
960 /// BasicBlocks to loops.
961 void removeBlock(BasicBlock *BB) {
967 // Allow clients to walk the list of nested loops...
968 template <> struct GraphTraits<const Loop*> {
969 typedef const Loop NodeType;
970 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
972 static NodeType *getEntryNode(const Loop *L) { return L; }
973 static inline ChildIteratorType child_begin(NodeType *N) {
976 static inline ChildIteratorType child_end(NodeType *N) {
981 template <> struct GraphTraits<Loop*> {
982 typedef Loop NodeType;
983 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
985 static NodeType *getEntryNode(Loop *L) { return L; }
986 static inline ChildIteratorType child_begin(NodeType *N) {
989 static inline ChildIteratorType child_end(NodeType *N) {
994 template<class BlockT>
995 void LoopBase<BlockT>::addBasicBlockToLoop(BlockT *NewBB,
996 LoopInfoBase<BlockT> &LIB) {
997 assert((Blocks.empty() || LIB[getHeader()] == this) &&
998 "Incorrect LI specified for this loop!");
999 assert(NewBB && "Cannot add a null basic block to the loop!");
1000 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1002 // Add the loop mapping to the LoopInfo object...
1003 LIB.BBMap[NewBB] = this;
1005 // Add the basic block to this loop and all parent loops...
1006 LoopBase<BlockT> *L = this;
1008 L->Blocks.push_back(NewBB);
1009 L = L->getParentLoop();
1013 } // End llvm namespace
1015 // Make sure that any clients of this file link in LoopInfo.cpp
1016 FORCE_DEFINING_FILE_TO_BE_LINKED(LoopInfo)