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/Debug.h"
41 #include "llvm/Support/raw_ostream.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!");
56 template<class N, class M> class LoopInfoBase;
57 template<class N, class M> class LoopBase;
59 //===----------------------------------------------------------------------===//
60 /// LoopBase class - Instances of this class are used to represent loops that
61 /// are detected in the flow graph
63 template<class BlockT, class LoopT>
66 // SubLoops - Loops contained entirely within this one.
67 std::vector<LoopT *> SubLoops;
69 // Blocks - The list of blocks in this loop. First entry is the header node.
70 std::vector<BlockT*> Blocks;
73 LoopBase(const LoopBase<BlockT, LoopT> &);
75 const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
77 /// Loop ctor - This creates an empty loop.
78 LoopBase() : ParentLoop(0) {}
80 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
84 /// getLoopDepth - Return the nesting level of this loop. An outer-most
85 /// loop has depth 1, for consistency with loop depth values used for basic
86 /// blocks, where depth 0 is used for blocks not inside any loops.
87 unsigned getLoopDepth() const {
89 for (const LoopT *CurLoop = ParentLoop; CurLoop;
90 CurLoop = CurLoop->ParentLoop)
94 BlockT *getHeader() const { return Blocks.front(); }
95 LoopT *getParentLoop() const { return ParentLoop; }
97 /// contains - Return true if the specified loop is contained within in
100 bool contains(const LoopT *L) const {
101 if (L == this) return true;
102 if (L == 0) return false;
103 return contains(L->getParentLoop());
106 /// contains - Return true if the specified basic block is in this loop.
108 bool contains(const BlockT *BB) const {
109 return std::find(block_begin(), block_end(), BB) != block_end();
112 /// contains - Return true if the specified instruction is in this loop.
114 template<class InstT>
115 bool contains(const InstT *Inst) const {
116 return contains(Inst->getParent());
119 /// iterator/begin/end - Return the loops contained entirely within this loop.
121 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
122 typedef typename std::vector<LoopT *>::const_iterator iterator;
123 iterator begin() const { return SubLoops.begin(); }
124 iterator end() const { return SubLoops.end(); }
125 bool empty() const { return SubLoops.empty(); }
127 /// getBlocks - Get a list of the basic blocks which make up this loop.
129 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
130 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
131 block_iterator block_begin() const { return Blocks.begin(); }
132 block_iterator block_end() const { return Blocks.end(); }
134 /// isLoopExiting - True if terminator in the block can branch to another
135 /// block that is outside of the current loop.
137 bool isLoopExiting(const BlockT *BB) const {
138 typedef GraphTraits<BlockT*> BlockTraits;
139 for (typename BlockTraits::ChildIteratorType SI =
140 BlockTraits::child_begin(const_cast<BlockT*>(BB)),
141 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
148 /// getNumBackEdges - Calculate the number of back edges to the loop header
150 unsigned getNumBackEdges() const {
151 unsigned NumBackEdges = 0;
152 BlockT *H = getHeader();
154 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
155 for (typename InvBlockTraits::ChildIteratorType I =
156 InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
157 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
164 //===--------------------------------------------------------------------===//
165 // APIs for simple analysis of the loop.
167 // Note that all of these methods can fail on general loops (ie, there may not
168 // be a preheader, etc). For best success, the loop simplification and
169 // induction variable canonicalization pass should be used to normalize loops
170 // for easy analysis. These methods assume canonical loops.
172 /// getExitingBlocks - Return all blocks inside the loop that have successors
173 /// outside of the loop. These are the blocks _inside of the current loop_
174 /// which branch out. The returned list is always unique.
176 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
177 // Sort the blocks vector so that we can use binary search to do quick
179 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
180 std::sort(LoopBBs.begin(), LoopBBs.end());
182 typedef GraphTraits<BlockT*> BlockTraits;
183 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
184 for (typename BlockTraits::ChildIteratorType I =
185 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
187 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
188 // Not in current loop? It must be an exit block.
189 ExitingBlocks.push_back(*BI);
194 /// getExitingBlock - If getExitingBlocks would return exactly one block,
195 /// return that block. Otherwise return null.
196 BlockT *getExitingBlock() const {
197 SmallVector<BlockT*, 8> ExitingBlocks;
198 getExitingBlocks(ExitingBlocks);
199 if (ExitingBlocks.size() == 1)
200 return ExitingBlocks[0];
204 /// getExitBlocks - Return all of the successor blocks of this loop. These
205 /// are the blocks _outside of the current loop_ which are branched to.
207 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
208 // Sort the blocks vector so that we can use binary search to do quick
210 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
211 std::sort(LoopBBs.begin(), LoopBBs.end());
213 typedef GraphTraits<BlockT*> BlockTraits;
214 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
215 for (typename BlockTraits::ChildIteratorType I =
216 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
218 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
219 // Not in current loop? It must be an exit block.
220 ExitBlocks.push_back(*I);
223 /// getExitBlock - If getExitBlocks would return exactly one block,
224 /// return that block. Otherwise return null.
225 BlockT *getExitBlock() const {
226 SmallVector<BlockT*, 8> ExitBlocks;
227 getExitBlocks(ExitBlocks);
228 if (ExitBlocks.size() == 1)
229 return ExitBlocks[0];
233 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
234 typedef std::pair<const BlockT*,const BlockT*> Edge;
235 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
236 // Sort the blocks vector so that we can use binary search to do quick
238 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
239 std::sort(LoopBBs.begin(), LoopBBs.end());
241 typedef GraphTraits<BlockT*> BlockTraits;
242 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
243 for (typename BlockTraits::ChildIteratorType I =
244 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
246 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
247 // Not in current loop? It must be an exit block.
248 ExitEdges.push_back(std::make_pair(*BI, *I));
251 /// getLoopPreheader - If there is a preheader for this loop, return it. A
252 /// loop has a preheader if there is only one edge to the header of the loop
253 /// from outside of the loop. If this is the case, the block branching to the
254 /// header of the loop is the preheader node.
256 /// This method returns null if there is no preheader for the loop.
258 BlockT *getLoopPreheader() const {
259 // Keep track of nodes outside the loop branching to the header...
262 // Loop over the predecessors of the header node...
263 BlockT *Header = getHeader();
264 typedef GraphTraits<BlockT*> BlockTraits;
265 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
266 for (typename InvBlockTraits::ChildIteratorType PI =
267 InvBlockTraits::child_begin(Header),
268 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
269 if (!contains(*PI)) { // If the block is not in the loop...
270 if (Out && Out != *PI)
271 return 0; // Multiple predecessors outside the loop
275 // Make sure there is only one exit out of the preheader.
276 assert(Out && "Header of loop has no predecessors from outside loop?");
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 // If there is exactly one preheader, return it. If there was zero, then
283 // Out is still null.
287 /// getLoopLatch - If there is a single latch block for this loop, return it.
288 /// A latch block is a block that contains a branch back to the header.
289 BlockT *getLoopLatch() const {
290 BlockT *Header = getHeader();
291 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
292 typename InvBlockTraits::ChildIteratorType PI =
293 InvBlockTraits::child_begin(Header);
294 typename InvBlockTraits::ChildIteratorType PE =
295 InvBlockTraits::child_end(Header);
297 for (; PI != PE; ++PI)
306 //===--------------------------------------------------------------------===//
307 // APIs for updating loop information after changing the CFG
310 /// addBasicBlockToLoop - This method is used by other analyses to update loop
311 /// information. NewBB is set to be a new member of the current loop.
312 /// Because of this, it is added as a member of all parent loops, and is added
313 /// to the specified LoopInfo object as being in the current basic block. It
314 /// is not valid to replace the loop header with this method.
316 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
318 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
319 /// the OldChild entry in our children list with NewChild, and updates the
320 /// parent pointer of OldChild to be null and the NewChild to be this loop.
321 /// This updates the loop depth of the new child.
322 void replaceChildLoopWith(LoopT *OldChild,
324 assert(OldChild->ParentLoop == this && "This loop is already broken!");
325 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
326 typename std::vector<LoopT *>::iterator I =
327 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
328 assert(I != SubLoops.end() && "OldChild not in loop!");
330 OldChild->ParentLoop = 0;
331 NewChild->ParentLoop = static_cast<LoopT *>(this);
334 /// addChildLoop - Add the specified loop to be a child of this loop. This
335 /// updates the loop depth of the new child.
337 void addChildLoop(LoopT *NewChild) {
338 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
339 NewChild->ParentLoop = static_cast<LoopT *>(this);
340 SubLoops.push_back(NewChild);
343 /// removeChildLoop - This removes the specified child from being a subloop of
344 /// this loop. The loop is not deleted, as it will presumably be inserted
345 /// into another loop.
346 LoopT *removeChildLoop(iterator I) {
347 assert(I != SubLoops.end() && "Cannot remove end iterator!");
349 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
350 SubLoops.erase(SubLoops.begin()+(I-begin()));
351 Child->ParentLoop = 0;
355 /// addBlockEntry - This adds a basic block directly to the basic block list.
356 /// This should only be used by transformations that create new loops. Other
357 /// transformations should use addBasicBlockToLoop.
358 void addBlockEntry(BlockT *BB) {
359 Blocks.push_back(BB);
362 /// moveToHeader - This method is used to move BB (which must be part of this
363 /// loop) to be the loop header of the loop (the block that dominates all
365 void moveToHeader(BlockT *BB) {
366 if (Blocks[0] == BB) return;
367 for (unsigned i = 0; ; ++i) {
368 assert(i != Blocks.size() && "Loop does not contain BB!");
369 if (Blocks[i] == BB) {
370 Blocks[i] = Blocks[0];
377 /// removeBlockFromLoop - This removes the specified basic block from the
378 /// current loop, updating the Blocks as appropriate. This does not update
379 /// the mapping in the LoopInfo class.
380 void removeBlockFromLoop(BlockT *BB) {
381 RemoveFromVector(Blocks, BB);
384 /// verifyLoop - Verify loop structure
385 void verifyLoop() const {
387 assert(!Blocks.empty() && "Loop header is missing");
389 // Sort the blocks vector so that we can use binary search to do quick
391 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
392 std::sort(LoopBBs.begin(), LoopBBs.end());
394 // Check the individual blocks.
395 for (block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
397 bool HasInsideLoopSuccs = false;
398 bool HasInsideLoopPreds = false;
399 SmallVector<BlockT *, 2> OutsideLoopPreds;
401 typedef GraphTraits<BlockT*> BlockTraits;
402 for (typename BlockTraits::ChildIteratorType SI =
403 BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
405 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
406 HasInsideLoopSuccs = true;
409 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
410 for (typename InvBlockTraits::ChildIteratorType PI =
411 InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
413 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *PI))
414 HasInsideLoopPreds = true;
416 OutsideLoopPreds.push_back(*PI);
419 if (BB == getHeader()) {
420 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
421 } else if (!OutsideLoopPreds.empty()) {
422 // A non-header loop shouldn't be reachable from outside the loop,
423 // though it is permitted if the predecessor is not itself actually
425 BlockT *EntryBB = BB->getParent()->begin();
426 for (df_iterator<BlockT *> NI = df_begin(EntryBB),
427 NE = df_end(EntryBB); NI != NE; ++NI)
428 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
429 assert(*NI != OutsideLoopPreds[i] &&
430 "Loop has multiple entry points!");
432 assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
433 assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
434 assert(BB != getHeader()->getParent()->begin() &&
435 "Loop contains function entry block!");
438 // Check the subloops.
439 for (iterator I = begin(), E = end(); I != E; ++I)
440 // Each block in each subloop should be contained within this loop.
441 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
443 assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
444 "Loop does not contain all the blocks of a subloop!");
447 // Check the parent loop pointer.
449 assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
451 "Loop is not a subloop of its parent!");
456 /// verifyLoop - Verify loop structure of this loop and all nested loops.
457 void verifyLoopNest() const {
460 // Verify the subloops.
461 for (iterator I = begin(), E = end(); I != E; ++I)
462 (*I)->verifyLoopNest();
465 void print(raw_ostream &OS, unsigned Depth = 0) const {
466 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
469 for (unsigned i = 0; i < getBlocks().size(); ++i) {
471 BlockT *BB = getBlocks()[i];
472 WriteAsOperand(OS, BB, false);
473 if (BB == getHeader()) OS << "<header>";
474 if (BB == getLoopLatch()) OS << "<latch>";
475 if (isLoopExiting(BB)) OS << "<exiting>";
479 for (iterator I = begin(), E = end(); I != E; ++I)
480 (*I)->print(OS, Depth+2);
488 friend class LoopInfoBase<BlockT, LoopT>;
489 explicit LoopBase(BlockT *BB) : ParentLoop(0) {
490 Blocks.push_back(BB);
494 class Loop : public LoopBase<BasicBlock, Loop> {
498 /// isLoopInvariant - Return true if the specified value is loop invariant
500 bool isLoopInvariant(Value *V) const;
502 /// isLoopInvariant - Return true if the specified instruction is
505 bool isLoopInvariant(Instruction *I) const;
507 /// makeLoopInvariant - If the given value is an instruction inside of the
508 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
509 /// Return true if the value after any hoisting is loop invariant. This
510 /// function can be used as a slightly more aggressive replacement for
513 /// If InsertPt is specified, it is the point to hoist instructions to.
514 /// If null, the terminator of the loop preheader is used.
516 bool makeLoopInvariant(Value *V, bool &Changed,
517 Instruction *InsertPt = 0) const;
519 /// makeLoopInvariant - If the given instruction is inside of the
520 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
521 /// Return true if the instruction after any hoisting is loop invariant. This
522 /// function can be used as a slightly more aggressive replacement for
525 /// If InsertPt is specified, it is the point to hoist instructions to.
526 /// If null, the terminator of the loop preheader is used.
528 bool makeLoopInvariant(Instruction *I, bool &Changed,
529 Instruction *InsertPt = 0) const;
531 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
532 /// induction variable: an integer recurrence that starts at 0 and increments
533 /// by one each time through the loop. If so, return the phi node that
534 /// corresponds to it.
536 /// The IndVarSimplify pass transforms loops to have a canonical induction
539 PHINode *getCanonicalInductionVariable() const;
541 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
542 /// the canonical induction variable value for the "next" iteration of the
543 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
545 Instruction *getCanonicalInductionVariableIncrement() const;
547 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
548 /// times the loop will be executed. Note that this means that the backedge
549 /// of the loop executes N-1 times. If the trip-count cannot be determined,
550 /// this returns null.
552 /// The IndVarSimplify pass transforms loops to have a form that this
553 /// function easily understands.
555 Value *getTripCount() const;
557 /// getSmallConstantTripCount - Returns the trip count of this loop as a
558 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
559 /// of not constant. Will also return 0 if the trip count is very large
561 unsigned getSmallConstantTripCount() const;
563 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
564 /// trip count of this loop as a normal unsigned value, if possible. This
565 /// means that the actual trip count is always a multiple of the returned
566 /// value (don't forget the trip count could very well be zero as well!).
568 /// Returns 1 if the trip count is unknown or not guaranteed to be the
569 /// multiple of a constant (which is also the case if the trip count is simply
570 /// constant, use getSmallConstantTripCount for that case), Will also return 1
571 /// if the trip count is very large (>= 2^32).
572 unsigned getSmallConstantTripMultiple() const;
574 /// isLCSSAForm - Return true if the Loop is in LCSSA form
575 bool isLCSSAForm() const;
577 /// isLoopSimplifyForm - Return true if the Loop is in the form that
578 /// the LoopSimplify form transforms loops to, which is sometimes called
580 bool isLoopSimplifyForm() const;
582 /// hasDedicatedExits - Return true if no exit block for the loop
583 /// has a predecessor that is outside the loop.
584 bool hasDedicatedExits() const;
586 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
587 /// These are the blocks _outside of the current loop_ which are branched to.
588 /// This assumes that loop exits are in canonical form.
590 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
592 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
593 /// block, return that block. Otherwise return null.
594 BasicBlock *getUniqueExitBlock() const;
597 friend class LoopInfoBase<BasicBlock, Loop>;
598 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
601 //===----------------------------------------------------------------------===//
602 /// LoopInfo - This class builds and contains all of the top level loop
603 /// structures in the specified function.
606 template<class BlockT, class LoopT>
608 // BBMap - Mapping of basic blocks to the inner most loop they occur in
609 std::map<BlockT *, LoopT *> BBMap;
610 std::vector<LoopT *> TopLevelLoops;
611 friend class LoopBase<BlockT, LoopT>;
613 void operator=(const LoopInfoBase &); // do not implement
614 LoopInfoBase(const LoopInfo &); // do not implement
617 ~LoopInfoBase() { releaseMemory(); }
619 void releaseMemory() {
620 for (typename std::vector<LoopT *>::iterator I =
621 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
622 delete *I; // Delete all of the loops...
624 BBMap.clear(); // Reset internal state of analysis
625 TopLevelLoops.clear();
628 /// iterator/begin/end - The interface to the top-level loops in the current
631 typedef typename std::vector<LoopT *>::const_iterator iterator;
632 iterator begin() const { return TopLevelLoops.begin(); }
633 iterator end() const { return TopLevelLoops.end(); }
634 bool empty() const { return TopLevelLoops.empty(); }
636 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
637 /// block is in no loop (for example the entry node), null is returned.
639 LoopT *getLoopFor(const BlockT *BB) const {
640 typename std::map<BlockT *, LoopT *>::const_iterator I=
641 BBMap.find(const_cast<BlockT*>(BB));
642 return I != BBMap.end() ? I->second : 0;
645 /// operator[] - same as getLoopFor...
647 const LoopT *operator[](const BlockT *BB) const {
648 return getLoopFor(BB);
651 /// getLoopDepth - Return the loop nesting level of the specified block. A
652 /// depth of 0 means the block is not inside any loop.
654 unsigned getLoopDepth(const BlockT *BB) const {
655 const LoopT *L = getLoopFor(BB);
656 return L ? L->getLoopDepth() : 0;
659 // isLoopHeader - True if the block is a loop header node
660 bool isLoopHeader(BlockT *BB) const {
661 const LoopT *L = getLoopFor(BB);
662 return L && L->getHeader() == BB;
665 /// removeLoop - This removes the specified top-level loop from this loop info
666 /// object. The loop is not deleted, as it will presumably be inserted into
668 LoopT *removeLoop(iterator I) {
669 assert(I != end() && "Cannot remove end iterator!");
671 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
672 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
676 /// changeLoopFor - Change the top-level loop that contains BB to the
677 /// specified loop. This should be used by transformations that restructure
678 /// the loop hierarchy tree.
679 void changeLoopFor(BlockT *BB, LoopT *L) {
680 LoopT *&OldLoop = BBMap[BB];
681 assert(OldLoop && "Block not in a loop yet!");
685 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
686 /// list with the indicated loop.
687 void changeTopLevelLoop(LoopT *OldLoop,
689 typename std::vector<LoopT *>::iterator I =
690 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
691 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
693 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
694 "Loops already embedded into a subloop!");
697 /// addTopLevelLoop - This adds the specified loop to the collection of
699 void addTopLevelLoop(LoopT *New) {
700 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
701 TopLevelLoops.push_back(New);
704 /// removeBlock - This method completely removes BB from all data structures,
705 /// including all of the Loop objects it is nested in and our mapping from
706 /// BasicBlocks to loops.
707 void removeBlock(BlockT *BB) {
708 typename std::map<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
709 if (I != BBMap.end()) {
710 for (LoopT *L = I->second; L; L = L->getParentLoop())
711 L->removeBlockFromLoop(BB);
719 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
720 const LoopT *ParentLoop) {
721 if (SubLoop == 0) return true;
722 if (SubLoop == ParentLoop) return false;
723 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
726 void Calculate(DominatorTreeBase<BlockT> &DT) {
727 BlockT *RootNode = DT.getRootNode()->getBlock();
729 for (df_iterator<BlockT*> NI = df_begin(RootNode),
730 NE = df_end(RootNode); NI != NE; ++NI)
731 if (LoopT *L = ConsiderForLoop(*NI, DT))
732 TopLevelLoops.push_back(L);
735 LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
736 if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
738 std::vector<BlockT *> TodoStack;
740 // Scan the predecessors of BB, checking to see if BB dominates any of
741 // them. This identifies backedges which target this node...
742 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
743 for (typename InvBlockTraits::ChildIteratorType I =
744 InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
746 if (DT.dominates(BB, *I)) // If BB dominates its predecessor...
747 TodoStack.push_back(*I);
749 if (TodoStack.empty()) return 0; // No backedges to this block...
751 // Create a new loop to represent this basic block...
752 LoopT *L = new LoopT(BB);
755 BlockT *EntryBlock = BB->getParent()->begin();
757 while (!TodoStack.empty()) { // Process all the nodes in the loop
758 BlockT *X = TodoStack.back();
759 TodoStack.pop_back();
761 if (!L->contains(X) && // As of yet unprocessed??
762 DT.dominates(EntryBlock, X)) { // X is reachable from entry block?
763 // Check to see if this block already belongs to a loop. If this occurs
764 // then we have a case where a loop that is supposed to be a child of
765 // the current loop was processed before the current loop. When this
766 // occurs, this child loop gets added to a part of the current loop,
767 // making it a sibling to the current loop. We have to reparent this
770 const_cast<LoopT *>(getLoopFor(X)))
771 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
772 // Remove the subloop from its current parent...
773 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
774 LoopT *SLP = SubLoop->ParentLoop; // SubLoopParent
775 typename std::vector<LoopT *>::iterator I =
776 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
777 assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
778 SLP->SubLoops.erase(I); // Remove from parent...
780 // Add the subloop to THIS loop...
781 SubLoop->ParentLoop = L;
782 L->SubLoops.push_back(SubLoop);
785 // Normal case, add the block to our loop...
786 L->Blocks.push_back(X);
788 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
790 // Add all of the predecessors of X to the end of the work stack...
791 TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
792 InvBlockTraits::child_end(X));
796 // If there are any loops nested within this loop, create them now!
797 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
798 E = L->Blocks.end(); I != E; ++I)
799 if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
800 L->SubLoops.push_back(NewLoop);
801 NewLoop->ParentLoop = L;
804 // Add the basic blocks that comprise this loop to the BBMap so that this
805 // loop can be found for them.
807 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
808 E = L->Blocks.end(); I != E; ++I)
809 BBMap.insert(std::make_pair(*I, L));
811 // Now that we have a list of all of the child loops of this loop, check to
812 // see if any of them should actually be nested inside of each other. We
813 // can accidentally pull loops our of their parents, so we must make sure to
814 // organize the loop nests correctly now.
816 std::map<BlockT *, LoopT *> ContainingLoops;
817 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
818 LoopT *Child = L->SubLoops[i];
819 assert(Child->getParentLoop() == L && "Not proper child loop?");
821 if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
822 // If there is already a loop which contains this loop, move this loop
823 // into the containing loop.
824 MoveSiblingLoopInto(Child, ContainingLoop);
825 --i; // The loop got removed from the SubLoops list.
827 // This is currently considered to be a top-level loop. Check to see
828 // if any of the contained blocks are loop headers for subloops we
829 // have already processed.
830 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
831 LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
832 if (BlockLoop == 0) { // Child block not processed yet...
834 } else if (BlockLoop != Child) {
835 LoopT *SubLoop = BlockLoop;
836 // Reparent all of the blocks which used to belong to BlockLoops
837 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
838 ContainingLoops[SubLoop->Blocks[j]] = Child;
840 // There is already a loop which contains this block, that means
841 // that we should reparent the loop which the block is currently
842 // considered to belong to to be a child of this loop.
843 MoveSiblingLoopInto(SubLoop, Child);
844 --i; // We just shrunk the SubLoops list.
854 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
855 /// of the NewParent Loop, instead of being a sibling of it.
856 void MoveSiblingLoopInto(LoopT *NewChild,
858 LoopT *OldParent = NewChild->getParentLoop();
859 assert(OldParent && OldParent == NewParent->getParentLoop() &&
860 NewChild != NewParent && "Not sibling loops!");
862 // Remove NewChild from being a child of OldParent
863 typename std::vector<LoopT *>::iterator I =
864 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
866 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
867 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
868 NewChild->ParentLoop = 0;
870 InsertLoopInto(NewChild, NewParent);
873 /// InsertLoopInto - This inserts loop L into the specified parent loop. If
874 /// the parent loop contains a loop which should contain L, the loop gets
875 /// inserted into L instead.
876 void InsertLoopInto(LoopT *L, LoopT *Parent) {
877 BlockT *LHeader = L->getHeader();
878 assert(Parent->contains(LHeader) &&
879 "This loop should not be inserted here!");
881 // Check to see if it belongs in a child loop...
882 for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
884 if (Parent->SubLoops[i]->contains(LHeader)) {
885 InsertLoopInto(L, Parent->SubLoops[i]);
889 // If not, insert it here!
890 Parent->SubLoops.push_back(L);
891 L->ParentLoop = Parent;
896 void print(raw_ostream &OS) const {
897 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
898 TopLevelLoops[i]->print(OS);
900 for (std::map<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
901 E = BBMap.end(); I != E; ++I)
902 OS << "BB '" << I->first->getName() << "' level = "
903 << I->second->getLoopDepth() << "\n";
908 class LoopInfo : public FunctionPass {
909 LoopInfoBase<BasicBlock, Loop> LI;
910 friend class LoopBase<BasicBlock, Loop>;
912 void operator=(const LoopInfo &); // do not implement
913 LoopInfo(const LoopInfo &); // do not implement
915 static char ID; // Pass identification, replacement for typeid
917 LoopInfo() : FunctionPass(&ID) {}
919 LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
921 /// iterator/begin/end - The interface to the top-level loops in the current
924 typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
925 inline iterator begin() const { return LI.begin(); }
926 inline iterator end() const { return LI.end(); }
927 bool empty() const { return LI.empty(); }
929 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
930 /// block is in no loop (for example the entry node), null is returned.
932 inline Loop *getLoopFor(const BasicBlock *BB) const {
933 return LI.getLoopFor(BB);
936 /// operator[] - same as getLoopFor...
938 inline const Loop *operator[](const BasicBlock *BB) const {
939 return LI.getLoopFor(BB);
942 /// getLoopDepth - Return the loop nesting level of the specified block. A
943 /// depth of 0 means the block is not inside any loop.
945 inline unsigned getLoopDepth(const BasicBlock *BB) const {
946 return LI.getLoopDepth(BB);
949 // isLoopHeader - True if the block is a loop header node
950 inline bool isLoopHeader(BasicBlock *BB) const {
951 return LI.isLoopHeader(BB);
954 /// runOnFunction - Calculate the natural loop information.
956 virtual bool runOnFunction(Function &F);
958 virtual void verifyAnalysis() const;
960 virtual void releaseMemory() { LI.releaseMemory(); }
962 virtual void print(raw_ostream &O, const Module* M = 0) const;
964 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
966 /// removeLoop - This removes the specified top-level loop from this loop info
967 /// object. The loop is not deleted, as it will presumably be inserted into
969 inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
971 /// changeLoopFor - Change the top-level loop that contains BB to the
972 /// specified loop. This should be used by transformations that restructure
973 /// the loop hierarchy tree.
974 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
975 LI.changeLoopFor(BB, L);
978 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
979 /// list with the indicated loop.
980 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
981 LI.changeTopLevelLoop(OldLoop, NewLoop);
984 /// addTopLevelLoop - This adds the specified loop to the collection of
986 inline void addTopLevelLoop(Loop *New) {
987 LI.addTopLevelLoop(New);
990 /// removeBlock - This method completely removes BB from all data structures,
991 /// including all of the Loop objects it is nested in and our mapping from
992 /// BasicBlocks to loops.
993 void removeBlock(BasicBlock *BB) {
999 // Allow clients to walk the list of nested loops...
1000 template <> struct GraphTraits<const Loop*> {
1001 typedef const Loop NodeType;
1002 typedef LoopInfo::iterator ChildIteratorType;
1004 static NodeType *getEntryNode(const Loop *L) { return L; }
1005 static inline ChildIteratorType child_begin(NodeType *N) {
1008 static inline ChildIteratorType child_end(NodeType *N) {
1013 template <> struct GraphTraits<Loop*> {
1014 typedef Loop NodeType;
1015 typedef LoopInfo::iterator ChildIteratorType;
1017 static NodeType *getEntryNode(Loop *L) { return L; }
1018 static inline ChildIteratorType child_begin(NodeType *N) {
1021 static inline ChildIteratorType child_end(NodeType *N) {
1026 template<class BlockT, class LoopT>
1028 LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1029 LoopInfoBase<BlockT, LoopT> &LIB) {
1030 assert((Blocks.empty() || LIB[getHeader()] == this) &&
1031 "Incorrect LI specified for this loop!");
1032 assert(NewBB && "Cannot add a null basic block to the loop!");
1033 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1035 LoopT *L = static_cast<LoopT *>(this);
1037 // Add the loop mapping to the LoopInfo object...
1038 LIB.BBMap[NewBB] = L;
1040 // Add the basic block to this loop and all parent loops...
1042 L->Blocks.push_back(NewBB);
1043 L = L->getParentLoop();
1047 } // End llvm namespace