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/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/GraphTraits.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/Analysis/Dominators.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/raw_ostream.h"
45 static void RemoveFromVector(std::vector<T*> &V, T *N) {
46 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
47 assert(I != V.end() && "N is not in this list!");
54 template<class N, class M> class LoopInfoBase;
55 template<class N, class M> class LoopBase;
57 //===----------------------------------------------------------------------===//
58 /// LoopBase class - Instances of this class are used to represent loops that
59 /// are detected in the flow graph
61 template<class BlockT, class LoopT>
64 // SubLoops - Loops contained entirely within this one.
65 std::vector<LoopT *> SubLoops;
67 // Blocks - The list of blocks in this loop. First entry is the header node.
68 std::vector<BlockT*> Blocks;
71 LoopBase(const LoopBase<BlockT, LoopT> &);
73 const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
75 /// Loop ctor - This creates an empty loop.
76 LoopBase() : ParentLoop(0) {}
78 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
82 /// getLoopDepth - Return the nesting level of this loop. An outer-most
83 /// loop has depth 1, for consistency with loop depth values used for basic
84 /// blocks, where depth 0 is used for blocks not inside any loops.
85 unsigned getLoopDepth() const {
87 for (const LoopT *CurLoop = ParentLoop; CurLoop;
88 CurLoop = CurLoop->ParentLoop)
92 BlockT *getHeader() const { return Blocks.front(); }
93 LoopT *getParentLoop() const { return ParentLoop; }
95 /// contains - Return true if the specified basic block is in this loop
97 bool contains(const BlockT *BB) const {
98 return std::find(block_begin(), block_end(), BB) != block_end();
101 /// iterator/begin/end - Return the loops contained entirely within this loop.
103 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
104 typedef typename std::vector<LoopT *>::const_iterator iterator;
105 iterator begin() const { return SubLoops.begin(); }
106 iterator end() const { return SubLoops.end(); }
107 bool empty() const { return SubLoops.empty(); }
109 /// getBlocks - Get a list of the basic blocks which make up this loop.
111 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
112 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
113 block_iterator block_begin() const { return Blocks.begin(); }
114 block_iterator block_end() const { return Blocks.end(); }
116 /// isLoopExit - True if terminator in the block can branch to another block
117 /// that is outside of the current loop.
119 bool isLoopExit(const BlockT *BB) const {
120 typedef GraphTraits<BlockT*> BlockTraits;
121 for (typename BlockTraits::ChildIteratorType SI =
122 BlockTraits::child_begin(const_cast<BlockT*>(BB)),
123 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
130 /// getNumBackEdges - Calculate the number of back edges to the loop header
132 unsigned getNumBackEdges() const {
133 unsigned NumBackEdges = 0;
134 BlockT *H = getHeader();
136 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
137 for (typename InvBlockTraits::ChildIteratorType I =
138 InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
139 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
146 //===--------------------------------------------------------------------===//
147 // APIs for simple analysis of the loop.
149 // Note that all of these methods can fail on general loops (ie, there may not
150 // be a preheader, etc). For best success, the loop simplification and
151 // induction variable canonicalization pass should be used to normalize loops
152 // for easy analysis. These methods assume canonical loops.
154 /// getExitingBlocks - Return all blocks inside the loop that have successors
155 /// outside of the loop. These are the blocks _inside of the current loop_
156 /// which branch out. The returned list is always unique.
158 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
159 // Sort the blocks vector so that we can use binary search to do quick
161 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
162 std::sort(LoopBBs.begin(), LoopBBs.end());
164 typedef GraphTraits<BlockT*> BlockTraits;
165 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
166 for (typename BlockTraits::ChildIteratorType I =
167 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
169 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
170 // Not in current loop? It must be an exit block.
171 ExitingBlocks.push_back(*BI);
176 /// getExitingBlock - If getExitingBlocks would return exactly one block,
177 /// return that block. Otherwise return null.
178 BlockT *getExitingBlock() const {
179 SmallVector<BlockT*, 8> ExitingBlocks;
180 getExitingBlocks(ExitingBlocks);
181 if (ExitingBlocks.size() == 1)
182 return ExitingBlocks[0];
186 /// getExitBlocks - Return all of the successor blocks of this loop. These
187 /// are the blocks _outside of the current loop_ which are branched to.
189 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
190 // Sort the blocks vector so that we can use binary search to do quick
192 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
193 std::sort(LoopBBs.begin(), LoopBBs.end());
195 typedef GraphTraits<BlockT*> BlockTraits;
196 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
197 for (typename BlockTraits::ChildIteratorType I =
198 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
200 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
201 // Not in current loop? It must be an exit block.
202 ExitBlocks.push_back(*I);
205 /// getExitBlock - If getExitBlocks would return exactly one block,
206 /// return that block. Otherwise return null.
207 BlockT *getExitBlock() const {
208 SmallVector<BlockT*, 8> ExitBlocks;
209 getExitBlocks(ExitBlocks);
210 if (ExitBlocks.size() == 1)
211 return ExitBlocks[0];
215 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
216 /// (Modelled after getExitingBlocks().)
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 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
235 /// These are the blocks _outside of the current loop_ which are branched to.
236 /// This assumes that loop is in canonical form.
238 void getUniqueExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
239 // Sort the blocks vector so that we can use binary search to do quick
241 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
242 std::sort(LoopBBs.begin(), LoopBBs.end());
244 std::vector<BlockT*> switchExitBlocks;
246 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
248 BlockT *current = *BI;
249 switchExitBlocks.clear();
251 typedef GraphTraits<BlockT*> BlockTraits;
252 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
253 for (typename BlockTraits::ChildIteratorType I =
254 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
256 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
257 // If block is inside the loop then it is not a exit block.
260 typename InvBlockTraits::ChildIteratorType PI =
261 InvBlockTraits::child_begin(*I);
262 BlockT *firstPred = *PI;
264 // If current basic block is this exit block's first predecessor
265 // then only insert exit block in to the output ExitBlocks vector.
266 // This ensures that same exit block is not inserted twice into
267 // ExitBlocks vector.
268 if (current != firstPred)
271 // If a terminator has more then two successors, for example SwitchInst,
272 // then it is possible that there are multiple edges from current block
273 // to one exit block.
274 if (std::distance(BlockTraits::child_begin(current),
275 BlockTraits::child_end(current)) <= 2) {
276 ExitBlocks.push_back(*I);
280 // In case of multiple edges from current block to exit block, collect
281 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
283 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
284 == switchExitBlocks.end()) {
285 switchExitBlocks.push_back(*I);
286 ExitBlocks.push_back(*I);
292 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
293 /// block, return that block. Otherwise return null.
294 BlockT *getUniqueExitBlock() const {
295 SmallVector<BlockT*, 8> UniqueExitBlocks;
296 getUniqueExitBlocks(UniqueExitBlocks);
297 if (UniqueExitBlocks.size() == 1)
298 return UniqueExitBlocks[0];
302 /// getLoopPreheader - If there is a preheader for this loop, return it. A
303 /// loop has a preheader if there is only one edge to the header of the loop
304 /// from outside of the loop. If this is the case, the block branching to the
305 /// header of the loop is the preheader node.
307 /// This method returns null if there is no preheader for the loop.
309 BlockT *getLoopPreheader() const {
310 // Keep track of nodes outside the loop branching to the header...
313 // Loop over the predecessors of the header node...
314 BlockT *Header = getHeader();
315 typedef GraphTraits<BlockT*> BlockTraits;
316 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
317 for (typename InvBlockTraits::ChildIteratorType PI =
318 InvBlockTraits::child_begin(Header),
319 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
320 if (!contains(*PI)) { // If the block is not in the loop...
321 if (Out && Out != *PI)
322 return 0; // Multiple predecessors outside the loop
326 // Make sure there is only one exit out of the preheader.
327 assert(Out && "Header of loop has no predecessors from outside loop?");
328 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
330 if (SI != BlockTraits::child_end(Out))
331 return 0; // Multiple exits from the block, must not be a preheader.
333 // If there is exactly one preheader, return it. If there was zero, then
334 // Out is still null.
338 /// getLoopLatch - If there is a single latch block for this loop, return it.
339 /// A latch block is a block that contains a branch back to the header.
340 /// A loop header in normal form has two edges into it: one from a preheader
341 /// and one from a latch block.
342 BlockT *getLoopLatch() const {
343 BlockT *Header = getHeader();
344 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
345 typename InvBlockTraits::ChildIteratorType PI =
346 InvBlockTraits::child_begin(Header);
347 typename InvBlockTraits::ChildIteratorType PE =
348 InvBlockTraits::child_end(Header);
349 if (PI == PE) return 0; // no preds?
355 if (PI == PE) return 0; // only one pred?
358 if (Latch) return 0; // multiple backedges
362 if (PI != PE) return 0; // more than two preds
367 //===--------------------------------------------------------------------===//
368 // APIs for updating loop information after changing the CFG
371 /// addBasicBlockToLoop - This method is used by other analyses to update loop
372 /// information. NewBB is set to be a new member of the current loop.
373 /// Because of this, it is added as a member of all parent loops, and is added
374 /// to the specified LoopInfo object as being in the current basic block. It
375 /// is not valid to replace the loop header with this method.
377 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
379 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
380 /// the OldChild entry in our children list with NewChild, and updates the
381 /// parent pointer of OldChild to be null and the NewChild to be this loop.
382 /// This updates the loop depth of the new child.
383 void replaceChildLoopWith(LoopT *OldChild,
385 assert(OldChild->ParentLoop == this && "This loop is already broken!");
386 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
387 typename std::vector<LoopT *>::iterator I =
388 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
389 assert(I != SubLoops.end() && "OldChild not in loop!");
391 OldChild->ParentLoop = 0;
392 NewChild->ParentLoop = static_cast<LoopT *>(this);
395 /// addChildLoop - Add the specified loop to be a child of this loop. This
396 /// updates the loop depth of the new child.
398 void addChildLoop(LoopT *NewChild) {
399 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
400 NewChild->ParentLoop = static_cast<LoopT *>(this);
401 SubLoops.push_back(NewChild);
404 /// removeChildLoop - This removes the specified child from being a subloop of
405 /// this loop. The loop is not deleted, as it will presumably be inserted
406 /// into another loop.
407 LoopT *removeChildLoop(iterator I) {
408 assert(I != SubLoops.end() && "Cannot remove end iterator!");
410 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
411 SubLoops.erase(SubLoops.begin()+(I-begin()));
412 Child->ParentLoop = 0;
416 /// addBlockEntry - This adds a basic block directly to the basic block list.
417 /// This should only be used by transformations that create new loops. Other
418 /// transformations should use addBasicBlockToLoop.
419 void addBlockEntry(BlockT *BB) {
420 Blocks.push_back(BB);
423 /// moveToHeader - This method is used to move BB (which must be part of this
424 /// loop) to be the loop header of the loop (the block that dominates all
426 void moveToHeader(BlockT *BB) {
427 if (Blocks[0] == BB) return;
428 for (unsigned i = 0; ; ++i) {
429 assert(i != Blocks.size() && "Loop does not contain BB!");
430 if (Blocks[i] == BB) {
431 Blocks[i] = Blocks[0];
438 /// removeBlockFromLoop - This removes the specified basic block from the
439 /// current loop, updating the Blocks as appropriate. This does not update
440 /// the mapping in the LoopInfo class.
441 void removeBlockFromLoop(BlockT *BB) {
442 RemoveFromVector(Blocks, BB);
445 /// verifyLoop - Verify loop structure
446 void verifyLoop() const {
448 assert (getHeader() && "Loop header is missing");
449 assert (getLoopPreheader() && "Loop preheader is missing");
450 assert (getLoopLatch() && "Loop latch is missing");
451 for (iterator I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
456 void print(raw_ostream &OS, unsigned Depth = 0) const {
457 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
460 for (unsigned i = 0; i < getBlocks().size(); ++i) {
462 BlockT *BB = getBlocks()[i];
463 WriteAsOperand(OS, BB, false);
464 if (BB == getHeader()) OS << "<header>";
465 if (BB == getLoopLatch()) OS << "<latch>";
466 if (isLoopExit(BB)) OS << "<exit>";
470 for (iterator I = begin(), E = end(); I != E; ++I)
471 (*I)->print(OS, Depth+2);
479 friend class LoopInfoBase<BlockT, LoopT>;
480 explicit LoopBase(BlockT *BB) : ParentLoop(0) {
481 Blocks.push_back(BB);
485 class Loop : public LoopBase<BasicBlock, Loop> {
489 /// isLoopInvariant - Return true if the specified value is loop invariant
491 bool isLoopInvariant(Value *V) const;
493 /// isLoopInvariant - Return true if the specified instruction is
496 bool isLoopInvariant(Instruction *I) const;
498 /// makeLoopInvariant - If the given value is an instruction inside of the
499 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
500 /// Return true if the value after any hoisting is loop invariant. This
501 /// function can be used as a slightly more aggressive replacement for
504 /// If InsertPt is specified, it is the point to hoist instructions to.
505 /// If null, the terminator of the loop preheader is used.
507 bool makeLoopInvariant(Value *V, bool &Changed,
508 Instruction *InsertPt = 0) const;
510 /// makeLoopInvariant - If the given instruction is inside of the
511 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
512 /// Return true if the instruction after any hoisting is loop invariant. This
513 /// function can be used as a slightly more aggressive replacement for
516 /// If InsertPt is specified, it is the point to hoist instructions to.
517 /// If null, the terminator of the loop preheader is used.
519 bool makeLoopInvariant(Instruction *I, bool &Changed,
520 Instruction *InsertPt = 0) const;
522 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
523 /// induction variable: an integer recurrence that starts at 0 and increments
524 /// by one each time through the loop. If so, return the phi node that
525 /// corresponds to it.
527 /// The IndVarSimplify pass transforms loops to have a canonical induction
530 PHINode *getCanonicalInductionVariable() const;
532 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
533 /// the canonical induction variable value for the "next" iteration of the
534 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
536 Instruction *getCanonicalInductionVariableIncrement() const;
538 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
539 /// times the loop will be executed. Note that this means that the backedge
540 /// of the loop executes N-1 times. If the trip-count cannot be determined,
541 /// this returns null.
543 /// The IndVarSimplify pass transforms loops to have a form that this
544 /// function easily understands.
546 Value *getTripCount() const;
548 /// getSmallConstantTripCount - Returns the trip count of this loop as a
549 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
550 /// of not constant. Will also return 0 if the trip count is very large
552 unsigned getSmallConstantTripCount() const;
554 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
555 /// trip count of this loop as a normal unsigned value, if possible. This
556 /// means that the actual trip count is always a multiple of the returned
557 /// value (don't forget the trip count could very well be zero as well!).
559 /// Returns 1 if the trip count is unknown or not guaranteed to be the
560 /// multiple of a constant (which is also the case if the trip count is simply
561 /// constant, use getSmallConstantTripCount for that case), Will also return 1
562 /// if the trip count is very large (>= 2^32).
563 unsigned getSmallConstantTripMultiple() const;
565 /// isLCSSAForm - Return true if the Loop is in LCSSA form
566 bool isLCSSAForm() const;
568 /// isLoopSimplifyForm - Return true if the Loop is in the form that
569 /// the LoopSimplify form transforms loops to, which is sometimes called
571 bool isLoopSimplifyForm() const;
574 friend class LoopInfoBase<BasicBlock, Loop>;
575 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
578 //===----------------------------------------------------------------------===//
579 /// LoopInfo - This class builds and contains all of the top level loop
580 /// structures in the specified function.
583 template<class BlockT, class LoopT>
585 // BBMap - Mapping of basic blocks to the inner most loop they occur in
586 std::map<BlockT *, LoopT *> BBMap;
587 std::vector<LoopT *> TopLevelLoops;
588 friend class LoopBase<BlockT, LoopT>;
590 void operator=(const LoopInfoBase &); // do not implement
591 LoopInfoBase(const LoopInfo &); // do not implement
594 ~LoopInfoBase() { releaseMemory(); }
596 void releaseMemory() {
597 for (typename std::vector<LoopT *>::iterator I =
598 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
599 delete *I; // Delete all of the loops...
601 BBMap.clear(); // Reset internal state of analysis
602 TopLevelLoops.clear();
605 /// iterator/begin/end - The interface to the top-level loops in the current
608 typedef typename std::vector<LoopT *>::const_iterator iterator;
609 iterator begin() const { return TopLevelLoops.begin(); }
610 iterator end() const { return TopLevelLoops.end(); }
611 bool empty() const { return TopLevelLoops.empty(); }
613 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
614 /// block is in no loop (for example the entry node), null is returned.
616 LoopT *getLoopFor(const BlockT *BB) const {
617 typename std::map<BlockT *, LoopT *>::const_iterator I=
618 BBMap.find(const_cast<BlockT*>(BB));
619 return I != BBMap.end() ? I->second : 0;
622 /// operator[] - same as getLoopFor...
624 const LoopT *operator[](const BlockT *BB) const {
625 return getLoopFor(BB);
628 /// getLoopDepth - Return the loop nesting level of the specified block. A
629 /// depth of 0 means the block is not inside any loop.
631 unsigned getLoopDepth(const BlockT *BB) const {
632 const LoopT *L = getLoopFor(BB);
633 return L ? L->getLoopDepth() : 0;
636 // isLoopHeader - True if the block is a loop header node
637 bool isLoopHeader(BlockT *BB) const {
638 const LoopT *L = getLoopFor(BB);
639 return L && L->getHeader() == BB;
642 /// removeLoop - This removes the specified top-level loop from this loop info
643 /// object. The loop is not deleted, as it will presumably be inserted into
645 LoopT *removeLoop(iterator I) {
646 assert(I != end() && "Cannot remove end iterator!");
648 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
649 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
653 /// changeLoopFor - Change the top-level loop that contains BB to the
654 /// specified loop. This should be used by transformations that restructure
655 /// the loop hierarchy tree.
656 void changeLoopFor(BlockT *BB, LoopT *L) {
657 LoopT *&OldLoop = BBMap[BB];
658 assert(OldLoop && "Block not in a loop yet!");
662 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
663 /// list with the indicated loop.
664 void changeTopLevelLoop(LoopT *OldLoop,
666 typename std::vector<LoopT *>::iterator I =
667 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
668 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
670 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
671 "Loops already embedded into a subloop!");
674 /// addTopLevelLoop - This adds the specified loop to the collection of
676 void addTopLevelLoop(LoopT *New) {
677 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
678 TopLevelLoops.push_back(New);
681 /// removeBlock - This method completely removes BB from all data structures,
682 /// including all of the Loop objects it is nested in and our mapping from
683 /// BasicBlocks to loops.
684 void removeBlock(BlockT *BB) {
685 typename std::map<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
686 if (I != BBMap.end()) {
687 for (LoopT *L = I->second; L; L = L->getParentLoop())
688 L->removeBlockFromLoop(BB);
696 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
697 const LoopT *ParentLoop) {
698 if (SubLoop == 0) return true;
699 if (SubLoop == ParentLoop) return false;
700 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
703 void Calculate(DominatorTreeBase<BlockT> &DT) {
704 BlockT *RootNode = DT.getRootNode()->getBlock();
706 for (df_iterator<BlockT*> NI = df_begin(RootNode),
707 NE = df_end(RootNode); NI != NE; ++NI)
708 if (LoopT *L = ConsiderForLoop(*NI, DT))
709 TopLevelLoops.push_back(L);
712 LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
713 if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
715 std::vector<BlockT *> TodoStack;
717 // Scan the predecessors of BB, checking to see if BB dominates any of
718 // them. This identifies backedges which target this node...
719 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
720 for (typename InvBlockTraits::ChildIteratorType I =
721 InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
723 if (DT.dominates(BB, *I)) // If BB dominates it's predecessor...
724 TodoStack.push_back(*I);
726 if (TodoStack.empty()) return 0; // No backedges to this block...
728 // Create a new loop to represent this basic block...
729 LoopT *L = new LoopT(BB);
732 BlockT *EntryBlock = BB->getParent()->begin();
734 while (!TodoStack.empty()) { // Process all the nodes in the loop
735 BlockT *X = TodoStack.back();
736 TodoStack.pop_back();
738 if (!L->contains(X) && // As of yet unprocessed??
739 DT.dominates(EntryBlock, X)) { // X is reachable from entry block?
740 // Check to see if this block already belongs to a loop. If this occurs
741 // then we have a case where a loop that is supposed to be a child of
742 // the current loop was processed before the current loop. When this
743 // occurs, this child loop gets added to a part of the current loop,
744 // making it a sibling to the current loop. We have to reparent this
747 const_cast<LoopT *>(getLoopFor(X)))
748 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
749 // Remove the subloop from it's current parent...
750 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
751 LoopT *SLP = SubLoop->ParentLoop; // SubLoopParent
752 typename std::vector<LoopT *>::iterator I =
753 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
754 assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
755 SLP->SubLoops.erase(I); // Remove from parent...
757 // Add the subloop to THIS loop...
758 SubLoop->ParentLoop = L;
759 L->SubLoops.push_back(SubLoop);
762 // Normal case, add the block to our loop...
763 L->Blocks.push_back(X);
765 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
767 // Add all of the predecessors of X to the end of the work stack...
768 TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
769 InvBlockTraits::child_end(X));
773 // If there are any loops nested within this loop, create them now!
774 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
775 E = L->Blocks.end(); I != E; ++I)
776 if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
777 L->SubLoops.push_back(NewLoop);
778 NewLoop->ParentLoop = L;
781 // Add the basic blocks that comprise this loop to the BBMap so that this
782 // loop can be found for them.
784 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
785 E = L->Blocks.end(); I != E; ++I) {
786 typename std::map<BlockT*, LoopT *>::iterator BBMI = BBMap.find(*I);
787 if (BBMI == BBMap.end()) // Not in map yet...
788 BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level
791 // Now that we have a list of all of the child loops of this loop, check to
792 // see if any of them should actually be nested inside of each other. We
793 // can accidentally pull loops our of their parents, so we must make sure to
794 // organize the loop nests correctly now.
796 std::map<BlockT *, LoopT *> ContainingLoops;
797 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
798 LoopT *Child = L->SubLoops[i];
799 assert(Child->getParentLoop() == L && "Not proper child loop?");
801 if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
802 // If there is already a loop which contains this loop, move this loop
803 // into the containing loop.
804 MoveSiblingLoopInto(Child, ContainingLoop);
805 --i; // The loop got removed from the SubLoops list.
807 // This is currently considered to be a top-level loop. Check to see
808 // if any of the contained blocks are loop headers for subloops we
809 // have already processed.
810 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
811 LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
812 if (BlockLoop == 0) { // Child block not processed yet...
814 } else if (BlockLoop != Child) {
815 LoopT *SubLoop = BlockLoop;
816 // Reparent all of the blocks which used to belong to BlockLoops
817 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
818 ContainingLoops[SubLoop->Blocks[j]] = Child;
820 // There is already a loop which contains this block, that means
821 // that we should reparent the loop which the block is currently
822 // considered to belong to to be a child of this loop.
823 MoveSiblingLoopInto(SubLoop, Child);
824 --i; // We just shrunk the SubLoops list.
834 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
835 /// of the NewParent Loop, instead of being a sibling of it.
836 void MoveSiblingLoopInto(LoopT *NewChild,
838 LoopT *OldParent = NewChild->getParentLoop();
839 assert(OldParent && OldParent == NewParent->getParentLoop() &&
840 NewChild != NewParent && "Not sibling loops!");
842 // Remove NewChild from being a child of OldParent
843 typename std::vector<LoopT *>::iterator I =
844 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
846 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
847 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
848 NewChild->ParentLoop = 0;
850 InsertLoopInto(NewChild, NewParent);
853 /// InsertLoopInto - This inserts loop L into the specified parent loop. If
854 /// the parent loop contains a loop which should contain L, the loop gets
855 /// inserted into L instead.
856 void InsertLoopInto(LoopT *L, LoopT *Parent) {
857 BlockT *LHeader = L->getHeader();
858 assert(Parent->contains(LHeader) &&
859 "This loop should not be inserted here!");
861 // Check to see if it belongs in a child loop...
862 for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
864 if (Parent->SubLoops[i]->contains(LHeader)) {
865 InsertLoopInto(L, Parent->SubLoops[i]);
869 // If not, insert it here!
870 Parent->SubLoops.push_back(L);
871 L->ParentLoop = Parent;
876 void print(raw_ostream &OS) const {
877 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
878 TopLevelLoops[i]->print(OS);
880 for (std::map<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
881 E = BBMap.end(); I != E; ++I)
882 OS << "BB '" << I->first->getName() << "' level = "
883 << I->second->getLoopDepth() << "\n";
888 class LoopInfo : public FunctionPass {
889 LoopInfoBase<BasicBlock, Loop> LI;
890 friend class LoopBase<BasicBlock, Loop>;
892 void operator=(const LoopInfo &); // do not implement
893 LoopInfo(const LoopInfo &); // do not implement
895 static char ID; // Pass identification, replacement for typeid
897 LoopInfo() : FunctionPass(&ID) {}
899 LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
901 /// iterator/begin/end - The interface to the top-level loops in the current
904 typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
905 inline iterator begin() const { return LI.begin(); }
906 inline iterator end() const { return LI.end(); }
907 bool empty() const { return LI.empty(); }
909 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
910 /// block is in no loop (for example the entry node), null is returned.
912 inline Loop *getLoopFor(const BasicBlock *BB) const {
913 return LI.getLoopFor(BB);
916 /// operator[] - same as getLoopFor...
918 inline const Loop *operator[](const BasicBlock *BB) const {
919 return LI.getLoopFor(BB);
922 /// getLoopDepth - Return the loop nesting level of the specified block. A
923 /// depth of 0 means the block is not inside any loop.
925 inline unsigned getLoopDepth(const BasicBlock *BB) const {
926 return LI.getLoopDepth(BB);
929 // isLoopHeader - True if the block is a loop header node
930 inline bool isLoopHeader(BasicBlock *BB) const {
931 return LI.isLoopHeader(BB);
934 /// runOnFunction - Calculate the natural loop information.
936 virtual bool runOnFunction(Function &F);
938 virtual void releaseMemory() { LI.releaseMemory(); }
940 virtual void print(raw_ostream &O, const Module* M = 0) const;
942 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
944 /// removeLoop - This removes the specified top-level loop from this loop info
945 /// object. The loop is not deleted, as it will presumably be inserted into
947 inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
949 /// changeLoopFor - Change the top-level loop that contains BB to the
950 /// specified loop. This should be used by transformations that restructure
951 /// the loop hierarchy tree.
952 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
953 LI.changeLoopFor(BB, L);
956 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
957 /// list with the indicated loop.
958 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
959 LI.changeTopLevelLoop(OldLoop, NewLoop);
962 /// addTopLevelLoop - This adds the specified loop to the collection of
964 inline void addTopLevelLoop(Loop *New) {
965 LI.addTopLevelLoop(New);
968 /// removeBlock - This method completely removes BB from all data structures,
969 /// including all of the Loop objects it is nested in and our mapping from
970 /// BasicBlocks to loops.
971 void removeBlock(BasicBlock *BB) {
975 static bool isNotAlreadyContainedIn(const Loop *SubLoop,
976 const Loop *ParentLoop) {
978 LoopInfoBase<BasicBlock, Loop>::isNotAlreadyContainedIn(SubLoop,
984 // Allow clients to walk the list of nested loops...
985 template <> struct GraphTraits<const Loop*> {
986 typedef const Loop NodeType;
987 typedef LoopInfo::iterator ChildIteratorType;
989 static NodeType *getEntryNode(const Loop *L) { return L; }
990 static inline ChildIteratorType child_begin(NodeType *N) {
993 static inline ChildIteratorType child_end(NodeType *N) {
998 template <> struct GraphTraits<Loop*> {
999 typedef Loop NodeType;
1000 typedef LoopInfo::iterator ChildIteratorType;
1002 static NodeType *getEntryNode(Loop *L) { return L; }
1003 static inline ChildIteratorType child_begin(NodeType *N) {
1006 static inline ChildIteratorType child_end(NodeType *N) {
1011 template<class BlockT, class LoopT>
1013 LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1014 LoopInfoBase<BlockT, LoopT> &LIB) {
1015 assert((Blocks.empty() || LIB[getHeader()] == this) &&
1016 "Incorrect LI specified for this loop!");
1017 assert(NewBB && "Cannot add a null basic block to the loop!");
1018 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1020 LoopT *L = static_cast<LoopT *>(this);
1022 // Add the loop mapping to the LoopInfo object...
1023 LIB.BBMap[NewBB] = L;
1025 // Add the basic block to this loop and all parent loops...
1027 L->Blocks.push_back(NewBB);
1028 L = L->getParentLoop();
1032 } // End llvm namespace