1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the LoopInfo class that is used to identify natural loops
11 // and determine the loop depth of various nodes of the CFG. A natural loop
12 // has exactly one entry-point, which is called the header. Note that natural
13 // loops may actually be several loops that share the same header node.
15 // This analysis calculates the nesting structure of loops in a function. For
16 // each natural loop identified, this analysis identifies natural loops
17 // contained entirely within the loop and the basic blocks the make up the loop.
19 // It can calculate on the fly various bits of information, for example:
21 // * whether there is a preheader for the loop
22 // * the number of back edges to the header
23 // * whether or not a particular block branches out of the loop
24 // * the successor blocks of the loop
29 //===----------------------------------------------------------------------===//
31 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
32 #define LLVM_ANALYSIS_LOOP_INFO_H
34 #include "llvm/Pass.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/DepthFirstIterator.h"
37 #include "llvm/ADT/GraphTraits.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Support/CFG.h"
42 #include "llvm/Support/raw_ostream.h"
48 static void RemoveFromVector(std::vector<T*> &V, T *N) {
49 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
50 assert(I != V.end() && "N is not in this list!");
57 template<class N, class M> class LoopInfoBase;
58 template<class N, class M> class LoopBase;
60 //===----------------------------------------------------------------------===//
61 /// LoopBase class - Instances of this class are used to represent loops that
62 /// are detected in the flow graph
64 template<class BlockT, class LoopT>
67 // SubLoops - Loops contained entirely within this one.
68 std::vector<LoopT *> SubLoops;
70 // Blocks - The list of blocks in this loop. First entry is the header node.
71 std::vector<BlockT*> Blocks;
74 LoopBase(const LoopBase<BlockT, LoopT> &);
76 const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
78 /// Loop ctor - This creates an empty loop.
79 LoopBase() : ParentLoop(0) {}
81 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
85 /// getLoopDepth - Return the nesting level of this loop. An outer-most
86 /// loop has depth 1, for consistency with loop depth values used for basic
87 /// blocks, where depth 0 is used for blocks not inside any loops.
88 unsigned getLoopDepth() const {
90 for (const LoopT *CurLoop = ParentLoop; CurLoop;
91 CurLoop = CurLoop->ParentLoop)
95 BlockT *getHeader() const { return Blocks.front(); }
96 LoopT *getParentLoop() const { return ParentLoop; }
98 /// contains - Return true if the specified loop is contained within in
101 bool contains(const LoopT *L) const {
102 if (L == this) return true;
103 if (L == 0) return false;
104 return contains(L->getParentLoop());
107 /// contains - Return true if the specified basic block is in this loop.
109 bool contains(const BlockT *BB) const {
110 return std::find(block_begin(), block_end(), BB) != block_end();
113 /// contains - Return true if the specified instruction is in this loop.
115 template<class InstT>
116 bool contains(const InstT *Inst) const {
117 return contains(Inst->getParent());
120 /// iterator/begin/end - Return the loops contained entirely within this loop.
122 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
123 typedef typename std::vector<LoopT *>::const_iterator iterator;
124 iterator begin() const { return SubLoops.begin(); }
125 iterator end() const { return SubLoops.end(); }
126 bool empty() const { return SubLoops.empty(); }
128 /// getBlocks - Get a list of the basic blocks which make up this loop.
130 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
131 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
132 block_iterator block_begin() const { return Blocks.begin(); }
133 block_iterator block_end() const { return Blocks.end(); }
135 /// isLoopExiting - True if terminator in the block can branch to another
136 /// block that is outside of the current loop.
138 bool isLoopExiting(const BlockT *BB) const {
139 typedef GraphTraits<BlockT*> BlockTraits;
140 for (typename BlockTraits::ChildIteratorType SI =
141 BlockTraits::child_begin(const_cast<BlockT*>(BB)),
142 SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
149 /// getNumBackEdges - Calculate the number of back edges to the loop header
151 unsigned getNumBackEdges() const {
152 unsigned NumBackEdges = 0;
153 BlockT *H = getHeader();
155 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
156 for (typename InvBlockTraits::ChildIteratorType I =
157 InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
158 E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
165 //===--------------------------------------------------------------------===//
166 // APIs for simple analysis of the loop.
168 // Note that all of these methods can fail on general loops (ie, there may not
169 // be a preheader, etc). For best success, the loop simplification and
170 // induction variable canonicalization pass should be used to normalize loops
171 // for easy analysis. These methods assume canonical loops.
173 /// getExitingBlocks - Return all blocks inside the loop that have successors
174 /// outside of the loop. These are the blocks _inside of the current loop_
175 /// which branch out. The returned list is always unique.
177 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
178 // Sort the blocks vector so that we can use binary search to do quick
180 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
181 std::sort(LoopBBs.begin(), LoopBBs.end());
183 typedef GraphTraits<BlockT*> BlockTraits;
184 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
185 for (typename BlockTraits::ChildIteratorType I =
186 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
188 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
189 // Not in current loop? It must be an exit block.
190 ExitingBlocks.push_back(*BI);
195 /// getExitingBlock - If getExitingBlocks would return exactly one block,
196 /// return that block. Otherwise return null.
197 BlockT *getExitingBlock() const {
198 SmallVector<BlockT*, 8> ExitingBlocks;
199 getExitingBlocks(ExitingBlocks);
200 if (ExitingBlocks.size() == 1)
201 return ExitingBlocks[0];
205 /// getExitBlocks - Return all of the successor blocks of this loop. These
206 /// are the blocks _outside of the current loop_ which are branched to.
208 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
209 // Sort the blocks vector so that we can use binary search to do quick
211 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
212 std::sort(LoopBBs.begin(), LoopBBs.end());
214 typedef GraphTraits<BlockT*> BlockTraits;
215 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
216 for (typename BlockTraits::ChildIteratorType I =
217 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
219 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
220 // Not in current loop? It must be an exit block.
221 ExitBlocks.push_back(*I);
224 /// getExitBlock - If getExitBlocks would return exactly one block,
225 /// return that block. Otherwise return null.
226 BlockT *getExitBlock() const {
227 SmallVector<BlockT*, 8> ExitBlocks;
228 getExitBlocks(ExitBlocks);
229 if (ExitBlocks.size() == 1)
230 return ExitBlocks[0];
235 typedef std::pair<BlockT*, BlockT*> Edge;
237 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
238 template <typename EdgeT>
239 void getExitEdges(SmallVectorImpl<EdgeT> &ExitEdges) const {
240 // Sort the blocks vector so that we can use binary search to do quick
242 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
243 array_pod_sort(LoopBBs.begin(), LoopBBs.end());
245 typedef GraphTraits<BlockT*> BlockTraits;
246 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
247 for (typename BlockTraits::ChildIteratorType I =
248 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
250 if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
251 // Not in current loop? It must be an exit block.
252 ExitEdges.push_back(EdgeT(*BI, *I));
255 /// getLoopPreheader - If there is a preheader for this loop, return it. A
256 /// loop has a preheader if there is only one edge to the header of the loop
257 /// from outside of the loop. If this is the case, the block branching to the
258 /// header of the loop is the preheader node.
260 /// This method returns null if there is no preheader for the loop.
262 BlockT *getLoopPreheader() const {
263 // Keep track of nodes outside the loop branching to the header...
264 BlockT *Out = getLoopPredecessor();
267 // Make sure there is only one exit out of the preheader.
268 typedef GraphTraits<BlockT*> BlockTraits;
269 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
271 if (SI != BlockTraits::child_end(Out))
272 return 0; // Multiple exits from the block, must not be a preheader.
274 // The predecessor has exactly one successor, so it is a preheader.
278 /// getLoopPredecessor - If the given loop's header has exactly one unique
279 /// predecessor outside the loop, return it. Otherwise return null.
280 /// This is less strict that the loop "preheader" concept, which requires
281 /// the predecessor to have exactly one successor.
283 BlockT *getLoopPredecessor() const {
284 // Keep track of nodes outside the loop branching to the header...
287 // Loop over the predecessors of the header node...
288 BlockT *Header = getHeader();
289 typedef GraphTraits<BlockT*> BlockTraits;
290 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
291 for (typename InvBlockTraits::ChildIteratorType PI =
292 InvBlockTraits::child_begin(Header),
293 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
294 typename InvBlockTraits::NodeType *N = *PI;
295 if (!contains(N)) { // If the block is not in the loop...
297 return 0; // Multiple predecessors outside the loop
302 // Make sure there is only one exit out of the preheader.
303 assert(Out && "Header of loop has no predecessors from outside loop?");
307 /// getLoopLatch - If there is a single latch block for this loop, return it.
308 /// A latch block is a block that contains a branch back to the header.
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);
317 for (; PI != PE; ++PI) {
318 typename InvBlockTraits::NodeType *N = *PI;
328 //===--------------------------------------------------------------------===//
329 // APIs for updating loop information after changing the CFG
332 /// addBasicBlockToLoop - This method is used by other analyses to update loop
333 /// information. NewBB is set to be a new member of the current loop.
334 /// Because of this, it is added as a member of all parent loops, and is added
335 /// to the specified LoopInfo object as being in the current basic block. It
336 /// is not valid to replace the loop header with this method.
338 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
340 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
341 /// the OldChild entry in our children list with NewChild, and updates the
342 /// parent pointer of OldChild to be null and the NewChild to be this loop.
343 /// This updates the loop depth of the new child.
344 void replaceChildLoopWith(LoopT *OldChild,
346 assert(OldChild->ParentLoop == this && "This loop is already broken!");
347 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
348 typename std::vector<LoopT *>::iterator I =
349 std::find(SubLoops.begin(), SubLoops.end(), OldChild);
350 assert(I != SubLoops.end() && "OldChild not in loop!");
352 OldChild->ParentLoop = 0;
353 NewChild->ParentLoop = static_cast<LoopT *>(this);
356 /// addChildLoop - Add the specified loop to be a child of this loop. This
357 /// updates the loop depth of the new child.
359 void addChildLoop(LoopT *NewChild) {
360 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
361 NewChild->ParentLoop = static_cast<LoopT *>(this);
362 SubLoops.push_back(NewChild);
365 /// removeChildLoop - This removes the specified child from being a subloop of
366 /// this loop. The loop is not deleted, as it will presumably be inserted
367 /// into another loop.
368 LoopT *removeChildLoop(iterator I) {
369 assert(I != SubLoops.end() && "Cannot remove end iterator!");
371 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
372 SubLoops.erase(SubLoops.begin()+(I-begin()));
373 Child->ParentLoop = 0;
377 /// addBlockEntry - This adds a basic block directly to the basic block list.
378 /// This should only be used by transformations that create new loops. Other
379 /// transformations should use addBasicBlockToLoop.
380 void addBlockEntry(BlockT *BB) {
381 Blocks.push_back(BB);
384 /// moveToHeader - This method is used to move BB (which must be part of this
385 /// loop) to be the loop header of the loop (the block that dominates all
387 void moveToHeader(BlockT *BB) {
388 if (Blocks[0] == BB) return;
389 for (unsigned i = 0; ; ++i) {
390 assert(i != Blocks.size() && "Loop does not contain BB!");
391 if (Blocks[i] == BB) {
392 Blocks[i] = Blocks[0];
399 /// removeBlockFromLoop - This removes the specified basic block from the
400 /// current loop, updating the Blocks as appropriate. This does not update
401 /// the mapping in the LoopInfo class.
402 void removeBlockFromLoop(BlockT *BB) {
403 RemoveFromVector(Blocks, BB);
406 /// verifyLoop - Verify loop structure
407 void verifyLoop() const {
409 assert(!Blocks.empty() && "Loop header is missing");
411 // Sort the blocks vector so that we can use binary search to do quick
413 SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
414 std::sort(LoopBBs.begin(), LoopBBs.end());
416 // Check the individual blocks.
417 for (block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
419 bool HasInsideLoopSuccs = false;
420 bool HasInsideLoopPreds = false;
421 SmallVector<BlockT *, 2> OutsideLoopPreds;
423 typedef GraphTraits<BlockT*> BlockTraits;
424 for (typename BlockTraits::ChildIteratorType SI =
425 BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
427 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
428 HasInsideLoopSuccs = true;
431 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
432 for (typename InvBlockTraits::ChildIteratorType PI =
433 InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
435 typename InvBlockTraits::NodeType *N = *PI;
436 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), N))
437 HasInsideLoopPreds = true;
439 OutsideLoopPreds.push_back(N);
442 if (BB == getHeader()) {
443 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
444 } else if (!OutsideLoopPreds.empty()) {
445 // A non-header loop shouldn't be reachable from outside the loop,
446 // though it is permitted if the predecessor is not itself actually
448 BlockT *EntryBB = BB->getParent()->begin();
449 for (df_iterator<BlockT *> NI = df_begin(EntryBB),
450 NE = df_end(EntryBB); NI != NE; ++NI)
451 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
452 assert(*NI != OutsideLoopPreds[i] &&
453 "Loop has multiple entry points!");
455 assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
456 assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
457 assert(BB != getHeader()->getParent()->begin() &&
458 "Loop contains function entry block!");
461 // Check the subloops.
462 for (iterator I = begin(), E = end(); I != E; ++I)
463 // Each block in each subloop should be contained within this loop.
464 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
466 assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
467 "Loop does not contain all the blocks of a subloop!");
470 // Check the parent loop pointer.
472 assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
474 "Loop is not a subloop of its parent!");
479 /// verifyLoop - Verify loop structure of this loop and all nested loops.
480 void verifyLoopNest() const {
483 // Verify the subloops.
484 for (iterator I = begin(), E = end(); I != E; ++I)
485 (*I)->verifyLoopNest();
488 void print(raw_ostream &OS, unsigned Depth = 0) const {
489 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
492 for (unsigned i = 0; i < getBlocks().size(); ++i) {
494 BlockT *BB = getBlocks()[i];
495 WriteAsOperand(OS, BB, false);
496 if (BB == getHeader()) OS << "<header>";
497 if (BB == getLoopLatch()) OS << "<latch>";
498 if (isLoopExiting(BB)) OS << "<exiting>";
502 for (iterator I = begin(), E = end(); I != E; ++I)
503 (*I)->print(OS, Depth+2);
507 friend class LoopInfoBase<BlockT, LoopT>;
508 explicit LoopBase(BlockT *BB) : ParentLoop(0) {
509 Blocks.push_back(BB);
513 template<class BlockT, class LoopT>
514 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
519 class Loop : public LoopBase<BasicBlock, Loop> {
523 /// isLoopInvariant - Return true if the specified value is loop invariant
525 bool isLoopInvariant(Value *V) const;
527 /// hasLoopInvariantOperands - Return true if all the operands of the
528 /// specified instruction are loop invariant.
529 bool hasLoopInvariantOperands(Instruction *I) const;
531 /// makeLoopInvariant - If the given value is an instruction inside of the
532 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
533 /// Return true if the value after any hoisting is loop invariant. This
534 /// function can be used as a slightly more aggressive replacement for
537 /// If InsertPt is specified, it is the point to hoist instructions to.
538 /// If null, the terminator of the loop preheader is used.
540 bool makeLoopInvariant(Value *V, bool &Changed,
541 Instruction *InsertPt = 0) const;
543 /// makeLoopInvariant - If the given instruction is inside of the
544 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
545 /// Return true if the instruction after any hoisting is loop invariant. This
546 /// function can be used as a slightly more aggressive replacement for
549 /// If InsertPt is specified, it is the point to hoist instructions to.
550 /// If null, the terminator of the loop preheader is used.
552 bool makeLoopInvariant(Instruction *I, bool &Changed,
553 Instruction *InsertPt = 0) const;
555 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
556 /// induction variable: an integer recurrence that starts at 0 and increments
557 /// by one each time through the loop. If so, return the phi node that
558 /// corresponds to it.
560 /// The IndVarSimplify pass transforms loops to have a canonical induction
563 PHINode *getCanonicalInductionVariable() const;
565 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
566 /// times the loop will be executed. Note that this means that the backedge
567 /// of the loop executes N-1 times. If the trip-count cannot be determined,
568 /// this returns null.
570 /// The IndVarSimplify pass transforms loops to have a form that this
571 /// function easily understands.
573 Value *getTripCount() const;
575 /// getSmallConstantTripCount - Returns the trip count of this loop as a
576 /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
577 /// of not constant. Will also return 0 if the trip count is very large
580 /// The IndVarSimplify pass transforms loops to have a form that this
581 /// function easily understands.
583 unsigned getSmallConstantTripCount() const;
585 /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
586 /// trip count of this loop as a normal unsigned value, if possible. This
587 /// means that the actual trip count is always a multiple of the returned
588 /// value (don't forget the trip count could very well be zero as well!).
590 /// Returns 1 if the trip count is unknown or not guaranteed to be the
591 /// multiple of a constant (which is also the case if the trip count is simply
592 /// constant, use getSmallConstantTripCount for that case), Will also return 1
593 /// if the trip count is very large (>= 2^32).
594 unsigned getSmallConstantTripMultiple() const;
596 /// isLCSSAForm - Return true if the Loop is in LCSSA form
597 bool isLCSSAForm(DominatorTree &DT) const;
599 /// isLoopSimplifyForm - Return true if the Loop is in the form that
600 /// the LoopSimplify form transforms loops to, which is sometimes called
602 bool isLoopSimplifyForm() const;
604 /// hasDedicatedExits - Return true if no exit block for the loop
605 /// has a predecessor that is outside the loop.
606 bool hasDedicatedExits() const;
608 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
609 /// These are the blocks _outside of the current loop_ which are branched to.
610 /// This assumes that loop exits are in canonical form.
612 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
614 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
615 /// block, return that block. Otherwise return null.
616 BasicBlock *getUniqueExitBlock() const;
621 friend class LoopInfoBase<BasicBlock, Loop>;
622 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
625 //===----------------------------------------------------------------------===//
626 /// LoopInfo - This class builds and contains all of the top level loop
627 /// structures in the specified function.
630 template<class BlockT, class LoopT>
632 // BBMap - Mapping of basic blocks to the inner most loop they occur in
633 DenseMap<BlockT *, LoopT *> BBMap;
634 std::vector<LoopT *> TopLevelLoops;
635 friend class LoopBase<BlockT, LoopT>;
637 void operator=(const LoopInfoBase &); // do not implement
638 LoopInfoBase(const LoopInfo &); // do not implement
641 ~LoopInfoBase() { releaseMemory(); }
643 void releaseMemory() {
644 for (typename std::vector<LoopT *>::iterator I =
645 TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
646 delete *I; // Delete all of the loops...
648 BBMap.clear(); // Reset internal state of analysis
649 TopLevelLoops.clear();
652 /// iterator/begin/end - The interface to the top-level loops in the current
655 typedef typename std::vector<LoopT *>::const_iterator iterator;
656 iterator begin() const { return TopLevelLoops.begin(); }
657 iterator end() const { return TopLevelLoops.end(); }
658 bool empty() const { return TopLevelLoops.empty(); }
660 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
661 /// block is in no loop (for example the entry node), null is returned.
663 LoopT *getLoopFor(const BlockT *BB) const {
664 typename DenseMap<BlockT *, LoopT *>::const_iterator I=
665 BBMap.find(const_cast<BlockT*>(BB));
666 return I != BBMap.end() ? I->second : 0;
669 /// operator[] - same as getLoopFor...
671 const LoopT *operator[](const BlockT *BB) const {
672 return getLoopFor(BB);
675 /// getLoopDepth - Return the loop nesting level of the specified block. A
676 /// depth of 0 means the block is not inside any loop.
678 unsigned getLoopDepth(const BlockT *BB) const {
679 const LoopT *L = getLoopFor(BB);
680 return L ? L->getLoopDepth() : 0;
683 // isLoopHeader - True if the block is a loop header node
684 bool isLoopHeader(BlockT *BB) const {
685 const LoopT *L = getLoopFor(BB);
686 return L && L->getHeader() == BB;
689 /// removeLoop - This removes the specified top-level loop from this loop info
690 /// object. The loop is not deleted, as it will presumably be inserted into
692 LoopT *removeLoop(iterator I) {
693 assert(I != end() && "Cannot remove end iterator!");
695 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
696 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
700 /// changeLoopFor - Change the top-level loop that contains BB to the
701 /// specified loop. This should be used by transformations that restructure
702 /// the loop hierarchy tree.
703 void changeLoopFor(BlockT *BB, LoopT *L) {
704 LoopT *&OldLoop = BBMap[BB];
705 assert(OldLoop && "Block not in a loop yet!");
709 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
710 /// list with the indicated loop.
711 void changeTopLevelLoop(LoopT *OldLoop,
713 typename std::vector<LoopT *>::iterator I =
714 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
715 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
717 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
718 "Loops already embedded into a subloop!");
721 /// addTopLevelLoop - This adds the specified loop to the collection of
723 void addTopLevelLoop(LoopT *New) {
724 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
725 TopLevelLoops.push_back(New);
728 /// removeBlock - This method completely removes BB from all data structures,
729 /// including all of the Loop objects it is nested in and our mapping from
730 /// BasicBlocks to loops.
731 void removeBlock(BlockT *BB) {
732 typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
733 if (I != BBMap.end()) {
734 for (LoopT *L = I->second; L; L = L->getParentLoop())
735 L->removeBlockFromLoop(BB);
743 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
744 const LoopT *ParentLoop) {
745 if (SubLoop == 0) return true;
746 if (SubLoop == ParentLoop) return false;
747 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
750 void Calculate(DominatorTreeBase<BlockT> &DT) {
751 BlockT *RootNode = DT.getRootNode()->getBlock();
753 for (df_iterator<BlockT*> NI = df_begin(RootNode),
754 NE = df_end(RootNode); NI != NE; ++NI)
755 if (LoopT *L = ConsiderForLoop(*NI, DT))
756 TopLevelLoops.push_back(L);
759 LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
760 if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
762 std::vector<BlockT *> TodoStack;
764 // Scan the predecessors of BB, checking to see if BB dominates any of
765 // them. This identifies backedges which target this node...
766 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
767 for (typename InvBlockTraits::ChildIteratorType I =
768 InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
770 typename InvBlockTraits::NodeType *N = *I;
771 if (DT.dominates(BB, N)) // If BB dominates its predecessor...
772 TodoStack.push_back(N);
775 if (TodoStack.empty()) return 0; // No backedges to this block...
777 // Create a new loop to represent this basic block...
778 LoopT *L = new LoopT(BB);
781 BlockT *EntryBlock = BB->getParent()->begin();
783 while (!TodoStack.empty()) { // Process all the nodes in the loop
784 BlockT *X = TodoStack.back();
785 TodoStack.pop_back();
787 if (!L->contains(X) && // As of yet unprocessed??
788 DT.dominates(EntryBlock, X)) { // X is reachable from entry block?
789 // Check to see if this block already belongs to a loop. If this occurs
790 // then we have a case where a loop that is supposed to be a child of
791 // the current loop was processed before the current loop. When this
792 // occurs, this child loop gets added to a part of the current loop,
793 // making it a sibling to the current loop. We have to reparent this
796 const_cast<LoopT *>(getLoopFor(X)))
797 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
798 // Remove the subloop from its current parent...
799 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
800 LoopT *SLP = SubLoop->ParentLoop; // SubLoopParent
801 typename std::vector<LoopT *>::iterator I =
802 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
803 assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
804 SLP->SubLoops.erase(I); // Remove from parent...
806 // Add the subloop to THIS loop...
807 SubLoop->ParentLoop = L;
808 L->SubLoops.push_back(SubLoop);
811 // Normal case, add the block to our loop...
812 L->Blocks.push_back(X);
814 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
816 // Add all of the predecessors of X to the end of the work stack...
817 TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
818 InvBlockTraits::child_end(X));
822 // If there are any loops nested within this loop, create them now!
823 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
824 E = L->Blocks.end(); I != E; ++I)
825 if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
826 L->SubLoops.push_back(NewLoop);
827 NewLoop->ParentLoop = L;
830 // Add the basic blocks that comprise this loop to the BBMap so that this
831 // loop can be found for them.
833 for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
834 E = L->Blocks.end(); I != E; ++I)
835 BBMap.insert(std::make_pair(*I, L));
837 // Now that we have a list of all of the child loops of this loop, check to
838 // see if any of them should actually be nested inside of each other. We
839 // can accidentally pull loops our of their parents, so we must make sure to
840 // organize the loop nests correctly now.
842 std::map<BlockT *, LoopT *> ContainingLoops;
843 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
844 LoopT *Child = L->SubLoops[i];
845 assert(Child->getParentLoop() == L && "Not proper child loop?");
847 if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
848 // If there is already a loop which contains this loop, move this loop
849 // into the containing loop.
850 MoveSiblingLoopInto(Child, ContainingLoop);
851 --i; // The loop got removed from the SubLoops list.
853 // This is currently considered to be a top-level loop. Check to see
854 // if any of the contained blocks are loop headers for subloops we
855 // have already processed.
856 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
857 LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
858 if (BlockLoop == 0) { // Child block not processed yet...
860 } else if (BlockLoop != Child) {
861 LoopT *SubLoop = BlockLoop;
862 // Reparent all of the blocks which used to belong to BlockLoops
863 for (unsigned j = 0, f = SubLoop->Blocks.size(); j != f; ++j)
864 ContainingLoops[SubLoop->Blocks[j]] = Child;
866 // There is already a loop which contains this block, that means
867 // that we should reparent the loop which the block is currently
868 // considered to belong to to be a child of this loop.
869 MoveSiblingLoopInto(SubLoop, Child);
870 --i; // We just shrunk the SubLoops list.
880 /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
881 /// of the NewParent Loop, instead of being a sibling of it.
882 void MoveSiblingLoopInto(LoopT *NewChild,
884 LoopT *OldParent = NewChild->getParentLoop();
885 assert(OldParent && OldParent == NewParent->getParentLoop() &&
886 NewChild != NewParent && "Not sibling loops!");
888 // Remove NewChild from being a child of OldParent
889 typename std::vector<LoopT *>::iterator I =
890 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
892 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
893 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
894 NewChild->ParentLoop = 0;
896 InsertLoopInto(NewChild, NewParent);
899 /// InsertLoopInto - This inserts loop L into the specified parent loop. If
900 /// the parent loop contains a loop which should contain L, the loop gets
901 /// inserted into L instead.
902 void InsertLoopInto(LoopT *L, LoopT *Parent) {
903 BlockT *LHeader = L->getHeader();
904 assert(Parent->contains(LHeader) &&
905 "This loop should not be inserted here!");
907 // Check to see if it belongs in a child loop...
908 for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
910 if (Parent->SubLoops[i]->contains(LHeader)) {
911 InsertLoopInto(L, Parent->SubLoops[i]);
915 // If not, insert it here!
916 Parent->SubLoops.push_back(L);
917 L->ParentLoop = Parent;
922 void print(raw_ostream &OS) const {
923 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
924 TopLevelLoops[i]->print(OS);
926 for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
927 E = BBMap.end(); I != E; ++I)
928 OS << "BB '" << I->first->getName() << "' level = "
929 << I->second->getLoopDepth() << "\n";
934 class LoopInfo : public FunctionPass {
935 LoopInfoBase<BasicBlock, Loop> LI;
936 friend class LoopBase<BasicBlock, Loop>;
938 void operator=(const LoopInfo &); // do not implement
939 LoopInfo(const LoopInfo &); // do not implement
941 static char ID; // Pass identification, replacement for typeid
943 LoopInfo() : FunctionPass(ID) {
944 initializeLoopInfoPass(*PassRegistry::getPassRegistry());
947 LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
949 /// iterator/begin/end - The interface to the top-level loops in the current
952 typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
953 inline iterator begin() const { return LI.begin(); }
954 inline iterator end() const { return LI.end(); }
955 bool empty() const { return LI.empty(); }
957 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
958 /// block is in no loop (for example the entry node), null is returned.
960 inline Loop *getLoopFor(const BasicBlock *BB) const {
961 return LI.getLoopFor(BB);
964 /// operator[] - same as getLoopFor...
966 inline const Loop *operator[](const BasicBlock *BB) const {
967 return LI.getLoopFor(BB);
970 /// getLoopDepth - Return the loop nesting level of the specified block. A
971 /// depth of 0 means the block is not inside any loop.
973 inline unsigned getLoopDepth(const BasicBlock *BB) const {
974 return LI.getLoopDepth(BB);
977 // isLoopHeader - True if the block is a loop header node
978 inline bool isLoopHeader(BasicBlock *BB) const {
979 return LI.isLoopHeader(BB);
982 /// runOnFunction - Calculate the natural loop information.
984 virtual bool runOnFunction(Function &F);
986 virtual void verifyAnalysis() const;
988 virtual void releaseMemory() { LI.releaseMemory(); }
990 virtual void print(raw_ostream &O, const Module* M = 0) const;
992 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
994 /// removeLoop - This removes the specified top-level loop from this loop info
995 /// object. The loop is not deleted, as it will presumably be inserted into
997 inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
999 /// changeLoopFor - Change the top-level loop that contains BB to the
1000 /// specified loop. This should be used by transformations that restructure
1001 /// the loop hierarchy tree.
1002 inline void changeLoopFor(BasicBlock *BB, Loop *L) {
1003 LI.changeLoopFor(BB, L);
1006 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
1007 /// list with the indicated loop.
1008 inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
1009 LI.changeTopLevelLoop(OldLoop, NewLoop);
1012 /// addTopLevelLoop - This adds the specified loop to the collection of
1013 /// top-level loops.
1014 inline void addTopLevelLoop(Loop *New) {
1015 LI.addTopLevelLoop(New);
1018 /// removeBlock - This method completely removes BB from all data structures,
1019 /// including all of the Loop objects it is nested in and our mapping from
1020 /// BasicBlocks to loops.
1021 void removeBlock(BasicBlock *BB) {
1025 /// replacementPreservesLCSSAForm - Returns true if replacing From with To
1026 /// everywhere is guaranteed to preserve LCSSA form.
1027 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
1028 // Preserving LCSSA form is only problematic if the replacing value is an
1030 Instruction *I = dyn_cast<Instruction>(To);
1031 if (!I) return true;
1032 // If the instruction is not defined in a loop then it can safely replace
1034 Loop *ToLoop = getLoopFor(I->getParent());
1035 if (!ToLoop) return true;
1036 // If the replacing instruction is defined in the same loop as the original
1037 // instruction, or in a loop that contains it as an inner loop, then using
1038 // it as a replacement will not break LCSSA form.
1039 return ToLoop->contains(getLoopFor(From->getParent()));
1044 // Allow clients to walk the list of nested loops...
1045 template <> struct GraphTraits<const Loop*> {
1046 typedef const Loop NodeType;
1047 typedef LoopInfo::iterator ChildIteratorType;
1049 static NodeType *getEntryNode(const Loop *L) { return L; }
1050 static inline ChildIteratorType child_begin(NodeType *N) {
1053 static inline ChildIteratorType child_end(NodeType *N) {
1058 template <> struct GraphTraits<Loop*> {
1059 typedef Loop NodeType;
1060 typedef LoopInfo::iterator ChildIteratorType;
1062 static NodeType *getEntryNode(Loop *L) { return L; }
1063 static inline ChildIteratorType child_begin(NodeType *N) {
1066 static inline ChildIteratorType child_end(NodeType *N) {
1071 template<class BlockT, class LoopT>
1073 LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1074 LoopInfoBase<BlockT, LoopT> &LIB) {
1075 assert((Blocks.empty() || LIB[getHeader()] == this) &&
1076 "Incorrect LI specified for this loop!");
1077 assert(NewBB && "Cannot add a null basic block to the loop!");
1078 assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1080 LoopT *L = static_cast<LoopT *>(this);
1082 // Add the loop mapping to the LoopInfo object...
1083 LIB.BBMap[NewBB] = L;
1085 // Add the basic block to this loop and all parent loops...
1087 L->Blocks.push_back(NewBB);
1088 L = L->getParentLoop();
1092 } // End llvm namespace