Move typedef of loop to top of the file where it is more obvious.
[oota-llvm.git] / include / llvm / Analysis / LoopInfo.h
1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
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.
17 //
18 // It can calculate on the fly various bits of information, for example:
19 //
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
24 //  * the loop depth
25 //  * the trip count
26 //  * etc...
27 //
28 //===----------------------------------------------------------------------===//
29
30 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
31 #define LLVM_ANALYSIS_LOOP_INFO_H
32
33 #include "llvm/Pass.h"
34 #include "llvm/Constants.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/ADT/DepthFirstIterator.h"
37 #include "llvm/ADT/GraphTraits.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Support/CFG.h"
42 #include "llvm/Support/Streams.h"
43 #include <algorithm>
44 #include <ostream>
45
46 template<typename T>
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!");
50   V.erase(I);
51 }
52
53 namespace llvm {
54
55 class DominatorTree;
56 class LoopInfo;
57 class PHINode;
58 class Instruction;
59 template<class N> class LoopInfoBase;
60 template<class N> class LoopBase;
61
62 typedef LoopBase<BasicBlock> Loop;
63
64 //===----------------------------------------------------------------------===//
65 /// LoopBase class - Instances of this class are used to represent loops that
66 /// are detected in the flow graph
67 ///
68 template<class BlockT>
69 class LoopBase {
70   LoopBase<BlockT> *ParentLoop;
71   // SubLoops - Loops contained entirely within this one.
72   std::vector<LoopBase<BlockT>*> SubLoops;
73
74   // Blocks - The list of blocks in this loop.  First entry is the header node.
75   std::vector<BlockT*> Blocks;
76
77   LoopBase(const LoopBase<BlockT> &);                  // DO NOT IMPLEMENT
78   const LoopBase<BlockT>&operator=(const LoopBase<BlockT> &);// DO NOT IMPLEMENT
79 public:
80   /// Loop ctor - This creates an empty loop.
81   LoopBase() : ParentLoop(0) {}
82   ~LoopBase() {
83     for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
84       delete SubLoops[i];
85   }
86
87   unsigned getLoopDepth() const {
88     unsigned D = 0;
89     for (const LoopBase<BlockT> *CurLoop = this; CurLoop;
90          CurLoop = CurLoop->ParentLoop)
91       ++D;
92     return D;
93   }
94   BlockT *getHeader() const { return Blocks.front(); }
95   LoopBase<BlockT> *getParentLoop() const { return ParentLoop; }
96
97   /// contains - Return true if the specified basic block is in this loop
98   ///
99   bool contains(const BlockT *BB) const {
100     return std::find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
101   }
102
103   /// iterator/begin/end - Return the loops contained entirely within this loop.
104   ///
105   const std::vector<LoopBase<BlockT>*> &getSubLoops() const { return SubLoops; }
106   typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
107   iterator begin() const { return SubLoops.begin(); }
108   iterator end() const { return SubLoops.end(); }
109   bool empty() const { return SubLoops.empty(); }
110
111   /// getBlocks - Get a list of the basic blocks which make up this loop.
112   ///
113   const std::vector<BlockT*> &getBlocks() const { return Blocks; }
114   typedef typename std::vector<BlockT*>::const_iterator block_iterator;
115   block_iterator block_begin() const { return Blocks.begin(); }
116   block_iterator block_end() const { return Blocks.end(); }
117
118   /// isLoopExit - True if terminator in the block can branch to another block
119   /// that is outside of the current loop.
120   ///
121   bool isLoopExit(const BlockT *BB) const {
122     typedef GraphTraits<BlockT*> BlockTraits;
123     for (typename BlockTraits::ChildIteratorType SI =
124          BlockTraits::child_begin(const_cast<BlockT*>(BB)),
125          SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
126       if (!contains(*SI))
127         return true;
128     }
129     return false;
130   }
131
132   /// getNumBackEdges - Calculate the number of back edges to the loop header
133   ///
134   unsigned getNumBackEdges() const {
135     unsigned NumBackEdges = 0;
136     BlockT *H = getHeader();
137
138     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
139     for (typename InvBlockTraits::ChildIteratorType I =
140          InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
141          E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
142       if (contains(*I))
143         ++NumBackEdges;
144
145     return NumBackEdges;
146   }
147
148   /// isLoopInvariant - Return true if the specified value is loop invariant
149   ///
150   inline bool isLoopInvariant(Value *V) const {
151     if (Instruction *I = dyn_cast<Instruction>(V))
152       return !contains(I->getParent());
153     return true;  // All non-instructions are loop invariant
154   }
155
156   //===--------------------------------------------------------------------===//
157   // APIs for simple analysis of the loop.
158   //
159   // Note that all of these methods can fail on general loops (ie, there may not
160   // be a preheader, etc).  For best success, the loop simplification and
161   // induction variable canonicalization pass should be used to normalize loops
162   // for easy analysis.  These methods assume canonical loops.
163
164   /// getExitingBlocks - Return all blocks inside the loop that have successors
165   /// outside of the loop.  These are the blocks _inside of the current loop_
166   /// which branch out.  The returned list is always unique.
167   ///
168   void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
169     // Sort the blocks vector so that we can use binary search to do quick
170     // lookups.
171     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
172     std::sort(LoopBBs.begin(), LoopBBs.end());
173
174     typedef GraphTraits<BlockT*> BlockTraits;
175     for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
176          BE = Blocks.end(); BI != BE; ++BI)
177       for (typename BlockTraits::ChildIteratorType I =
178           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
179           I != E; ++I)
180         if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
181           // Not in current loop? It must be an exit block.
182           ExitingBlocks.push_back(*BI);
183           break;
184         }
185   }
186
187   /// getExitBlocks - Return all of the successor blocks of this loop.  These
188   /// are the blocks _outside of the current loop_ which are branched to.
189   ///
190   void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
191     // Sort the blocks vector so that we can use binary search to do quick
192     // lookups.
193     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
194     std::sort(LoopBBs.begin(), LoopBBs.end());
195
196     typedef GraphTraits<BlockT*> BlockTraits;
197     for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
198          BE = Blocks.end(); BI != BE; ++BI)
199       for (typename BlockTraits::ChildIteratorType I =
200            BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
201            I != E; ++I)
202         if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
203           // Not in current loop? It must be an exit block.
204           ExitBlocks.push_back(*I);
205   }
206
207   /// getUniqueExitBlocks - Return all unique successor blocks of this loop. 
208   /// These are the blocks _outside of the current loop_ which are branched to.
209   /// This assumes that loop is in canonical form.
210   ///
211   void getUniqueExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
212     // Sort the blocks vector so that we can use binary search to do quick
213     // lookups.
214     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
215     std::sort(LoopBBs.begin(), LoopBBs.end());
216
217     std::vector<BlockT*> switchExitBlocks;  
218
219     for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
220          BE = Blocks.end(); BI != BE; ++BI) {
221
222       BlockT *current = *BI;
223       switchExitBlocks.clear();
224
225       typedef GraphTraits<BlockT*> BlockTraits;
226       typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
227       for (typename BlockTraits::ChildIteratorType I =
228            BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
229            I != E; ++I) {
230         if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
231       // If block is inside the loop then it is not a exit block.
232           continue;
233       
234         typename InvBlockTraits::ChildIteratorType PI =
235                                                 InvBlockTraits::child_begin(*I);
236         BlockT *firstPred = *PI;
237
238         // If current basic block is this exit block's first predecessor
239         // then only insert exit block in to the output ExitBlocks vector.
240         // This ensures that same exit block is not inserted twice into
241         // ExitBlocks vector.
242         if (current != firstPred) 
243           continue;
244
245         // If a terminator has more then two successors, for example SwitchInst,
246         // then it is possible that there are multiple edges from current block 
247         // to one exit block. 
248         if (std::distance(BlockTraits::child_begin(current),
249                           BlockTraits::child_end(current)) <= 2) {
250           ExitBlocks.push_back(*I);
251           continue;
252         }
253
254         // In case of multiple edges from current block to exit block, collect
255         // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
256         // duplicate edges.
257         if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I) 
258             == switchExitBlocks.end()) {
259           switchExitBlocks.push_back(*I);
260           ExitBlocks.push_back(*I);
261         }
262       }
263     }
264   }
265
266   /// getLoopPreheader - If there is a preheader for this loop, return it.  A
267   /// loop has a preheader if there is only one edge to the header of the loop
268   /// from outside of the loop.  If this is the case, the block branching to the
269   /// header of the loop is the preheader node.
270   ///
271   /// This method returns null if there is no preheader for the loop.
272   ///
273   BlockT *getLoopPreheader() const {
274     // Keep track of nodes outside the loop branching to the header...
275     BlockT *Out = 0;
276
277     // Loop over the predecessors of the header node...
278     BlockT *Header = getHeader();
279     typedef GraphTraits<BlockT*> BlockTraits;
280     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
281     for (typename InvBlockTraits::ChildIteratorType PI =
282          InvBlockTraits::child_begin(Header),
283          PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
284       if (!contains(*PI)) {     // If the block is not in the loop...
285         if (Out && Out != *PI)
286           return 0;             // Multiple predecessors outside the loop
287         Out = *PI;
288       }
289
290     // Make sure there is only one exit out of the preheader.
291     assert(Out && "Header of loop has no predecessors from outside loop?");
292     typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
293     ++SI;
294     if (SI != BlockTraits::child_end(Out))
295       return 0;  // Multiple exits from the block, must not be a preheader.
296
297     // If there is exactly one preheader, return it.  If there was zero, then
298     // Out is still null.
299     return Out;
300   }
301
302   /// getLoopLatch - If there is a latch block for this loop, return it.  A
303   /// latch block is the canonical backedge for a loop.  A loop header in normal
304   /// form has two edges into it: one from a preheader and one from a latch
305   /// block.
306   BlockT *getLoopLatch() const {
307     BlockT *Header = getHeader();
308     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
309     typename InvBlockTraits::ChildIteratorType PI =
310                                             InvBlockTraits::child_begin(Header);
311     typename InvBlockTraits::ChildIteratorType PE =
312                                               InvBlockTraits::child_end(Header);
313     if (PI == PE) return 0;  // no preds?
314
315     BlockT *Latch = 0;
316     if (contains(*PI))
317       Latch = *PI;
318     ++PI;
319     if (PI == PE) return 0;  // only one pred?
320
321     if (contains(*PI)) {
322       if (Latch) return 0;  // multiple backedges
323       Latch = *PI;
324     }
325     ++PI;
326     if (PI != PE) return 0;  // more than two preds
327
328     return Latch;
329   }
330   
331   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
332   /// induction variable: an integer recurrence that starts at 0 and increments
333   /// by one each time through the loop.  If so, return the phi node that
334   /// corresponds to it.
335   ///
336   inline PHINode *getCanonicalInductionVariable() const {
337     BlockT *H = getHeader();
338
339     BlockT *Incoming = 0, *Backedge = 0;
340     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
341     typename InvBlockTraits::ChildIteratorType PI =
342                                                  InvBlockTraits::child_begin(H);
343     assert(PI != InvBlockTraits::child_end(H) &&
344            "Loop must have at least one backedge!");
345     Backedge = *PI++;
346     if (PI == InvBlockTraits::child_end(H)) return 0;  // dead loop
347     Incoming = *PI++;
348     if (PI != InvBlockTraits::child_end(H)) return 0;  // multiple backedges?
349
350     if (contains(Incoming)) {
351       if (contains(Backedge))
352         return 0;
353       std::swap(Incoming, Backedge);
354     } else if (!contains(Backedge))
355       return 0;
356
357     // Loop over all of the PHI nodes, looking for a canonical indvar.
358     for (typename BlockT::iterator I = H->begin(); isa<PHINode>(I); ++I) {
359       PHINode *PN = cast<PHINode>(I);
360       if (Instruction *Inc =
361           dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
362         if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
363           if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
364             if (CI->equalsInt(1))
365               return PN;
366     }
367     return 0;
368   }
369
370   /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
371   /// the canonical induction variable value for the "next" iteration of the
372   /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
373   ///
374   inline Instruction *getCanonicalInductionVariableIncrement() const {
375     if (PHINode *PN = getCanonicalInductionVariable()) {
376       bool P1InLoop = contains(PN->getIncomingBlock(1));
377       return cast<Instruction>(PN->getIncomingValue(P1InLoop));
378     }
379     return 0;
380   }
381
382   /// getTripCount - Return a loop-invariant LLVM value indicating the number of
383   /// times the loop will be executed.  Note that this means that the backedge
384   /// of the loop executes N-1 times.  If the trip-count cannot be determined,
385   /// this returns null.
386   ///
387   inline Value *getTripCount() const {
388     // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
389     // canonical induction variable and V is the trip count of the loop.
390     Instruction *Inc = getCanonicalInductionVariableIncrement();
391     if (Inc == 0) return 0;
392     PHINode *IV = cast<PHINode>(Inc->getOperand(0));
393
394     BlockT *BackedgeBlock =
395             IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
396
397     if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
398       if (BI->isConditional()) {
399         if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
400           if (ICI->getOperand(0) == Inc)
401             if (BI->getSuccessor(0) == getHeader()) {
402               if (ICI->getPredicate() == ICmpInst::ICMP_NE)
403                 return ICI->getOperand(1);
404             } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
405               return ICI->getOperand(1);
406             }
407         }
408       }
409
410     return 0;
411   }
412   
413   /// isLCSSAForm - Return true if the Loop is in LCSSA form
414   inline bool isLCSSAForm() const {
415     // Sort the blocks vector so that we can use binary search to do quick
416     // lookups.
417     SmallPtrSet<BlockT*, 16> LoopBBs(block_begin(), block_end());
418
419     for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
420       BlockT *BB = *BI;
421       for (typename BlockT::iterator I = BB->begin(), E = BB->end(); I != E;++I)
422         for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
423              ++UI) {
424           BlockT *UserBB = cast<Instruction>(*UI)->getParent();
425           if (PHINode *P = dyn_cast<PHINode>(*UI)) {
426             unsigned OperandNo = UI.getOperandNo();
427             UserBB = P->getIncomingBlock(OperandNo/2);
428           }
429
430           // Check the current block, as a fast-path.  Most values are used in
431           // the same block they are defined in.
432           if (UserBB != BB && !LoopBBs.count(UserBB))
433             return false;
434         }
435     }
436
437     return true;
438   }
439
440   //===--------------------------------------------------------------------===//
441   // APIs for updating loop information after changing the CFG
442   //
443
444   /// addBasicBlockToLoop - This method is used by other analyses to update loop
445   /// information.  NewBB is set to be a new member of the current loop.
446   /// Because of this, it is added as a member of all parent loops, and is added
447   /// to the specified LoopInfo object as being in the current basic block.  It
448   /// is not valid to replace the loop header with this method.
449   ///
450   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT> &LI);
451
452   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
453   /// the OldChild entry in our children list with NewChild, and updates the
454   /// parent pointer of OldChild to be null and the NewChild to be this loop.
455   /// This updates the loop depth of the new child.
456   void replaceChildLoopWith(LoopBase<BlockT> *OldChild,
457                             LoopBase<BlockT> *NewChild) {
458     assert(OldChild->ParentLoop == this && "This loop is already broken!");
459     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
460     typename std::vector<LoopBase<BlockT>*>::iterator I =
461                           std::find(SubLoops.begin(), SubLoops.end(), OldChild);
462     assert(I != SubLoops.end() && "OldChild not in loop!");
463     *I = NewChild;
464     OldChild->ParentLoop = 0;
465     NewChild->ParentLoop = this;
466   }
467
468   /// addChildLoop - Add the specified loop to be a child of this loop.  This
469   /// updates the loop depth of the new child.
470   ///
471   void addChildLoop(LoopBase<BlockT> *NewChild) {
472     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
473     NewChild->ParentLoop = this;
474     SubLoops.push_back(NewChild);
475   }
476
477   /// removeChildLoop - This removes the specified child from being a subloop of
478   /// this loop.  The loop is not deleted, as it will presumably be inserted
479   /// into another loop.
480   LoopBase<BlockT> *removeChildLoop(iterator I) {
481     assert(I != SubLoops.end() && "Cannot remove end iterator!");
482     LoopBase<BlockT> *Child = *I;
483     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
484     SubLoops.erase(SubLoops.begin()+(I-begin()));
485     Child->ParentLoop = 0;
486     return Child;
487   }
488
489   /// addBlockEntry - This adds a basic block directly to the basic block list.
490   /// This should only be used by transformations that create new loops.  Other
491   /// transformations should use addBasicBlockToLoop.
492   void addBlockEntry(BlockT *BB) {
493     Blocks.push_back(BB);
494   }
495
496   /// moveToHeader - This method is used to move BB (which must be part of this
497   /// loop) to be the loop header of the loop (the block that dominates all
498   /// others).
499   void moveToHeader(BlockT *BB) {
500     if (Blocks[0] == BB) return;
501     for (unsigned i = 0; ; ++i) {
502       assert(i != Blocks.size() && "Loop does not contain BB!");
503       if (Blocks[i] == BB) {
504         Blocks[i] = Blocks[0];
505         Blocks[0] = BB;
506         return;
507       }
508     }
509   }
510
511   /// removeBlockFromLoop - This removes the specified basic block from the
512   /// current loop, updating the Blocks as appropriate.  This does not update
513   /// the mapping in the LoopInfo class.
514   void removeBlockFromLoop(BlockT *BB) {
515     RemoveFromVector(Blocks, BB);
516   }
517
518   /// verifyLoop - Verify loop structure
519   void verifyLoop() const {
520 #ifndef NDEBUG
521     assert (getHeader() && "Loop header is missing");
522     assert (getLoopPreheader() && "Loop preheader is missing");
523     assert (getLoopLatch() && "Loop latch is missing");
524     for (typename std::vector<LoopBase<BlockT>*>::const_iterator I =
525          SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
526       (*I)->verifyLoop();
527 #endif
528   }
529
530   void print(std::ostream &OS, unsigned Depth = 0) const {
531     OS << std::string(Depth*2, ' ') << "Loop Containing: ";
532
533     for (unsigned i = 0; i < getBlocks().size(); ++i) {
534       if (i) OS << ",";
535       WriteAsOperand(OS, getBlocks()[i], false);
536     }
537     OS << "\n";
538
539     for (iterator I = begin(), E = end(); I != E; ++I)
540       (*I)->print(OS, Depth+2);
541   }
542   
543   void print(std::ostream *O, unsigned Depth = 0) const {
544     if (O) print(*O, Depth);
545   }
546   
547   void dump() const {
548     print(cerr);
549   }
550   
551 private:
552   friend class LoopInfoBase<BlockT>;
553   LoopBase(BlockT *BB) : ParentLoop(0) {
554     Blocks.push_back(BB);
555   }
556 };
557
558
559 //===----------------------------------------------------------------------===//
560 /// LoopInfo - This class builds and contains all of the top level loop
561 /// structures in the specified function.
562 ///
563
564 template<class BlockT>
565 class LoopInfoBase {
566   // BBMap - Mapping of basic blocks to the inner most loop they occur in
567   std::map<BlockT*, LoopBase<BlockT>*> BBMap;
568   std::vector<LoopBase<BlockT>*> TopLevelLoops;
569   friend class LoopBase<BlockT>;
570   
571 public:
572   LoopInfoBase() { }
573   ~LoopInfoBase() { releaseMemory(); }
574   
575   void releaseMemory() {
576     for (typename std::vector<LoopBase<BlockT>* >::iterator I =
577          TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
578       delete *I;   // Delete all of the loops...
579
580     BBMap.clear();                           // Reset internal state of analysis
581     TopLevelLoops.clear();
582   }
583   
584   /// iterator/begin/end - The interface to the top-level loops in the current
585   /// function.
586   ///
587   typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
588   iterator begin() const { return TopLevelLoops.begin(); }
589   iterator end() const { return TopLevelLoops.end(); }
590   
591   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
592   /// block is in no loop (for example the entry node), null is returned.
593   ///
594   LoopBase<BlockT> *getLoopFor(const BlockT *BB) const {
595     typename std::map<BlockT *, LoopBase<BlockT>*>::const_iterator I=
596       BBMap.find(const_cast<BlockT*>(BB));
597     return I != BBMap.end() ? I->second : 0;
598   }
599   
600   /// operator[] - same as getLoopFor...
601   ///
602   const LoopBase<BlockT> *operator[](const BlockT *BB) const {
603     return getLoopFor(BB);
604   }
605   
606   /// getLoopDepth - Return the loop nesting level of the specified block...
607   ///
608   unsigned getLoopDepth(const BlockT *BB) const {
609     const LoopBase<BlockT> *L = getLoopFor(BB);
610     return L ? L->getLoopDepth() : 0;
611   }
612
613   // isLoopHeader - True if the block is a loop header node
614   bool isLoopHeader(BlockT *BB) const {
615     const LoopBase<BlockT> *L = getLoopFor(BB);
616     return L && L->getHeader() == BB;
617   }
618   
619   /// removeLoop - This removes the specified top-level loop from this loop info
620   /// object.  The loop is not deleted, as it will presumably be inserted into
621   /// another loop.
622   LoopBase<BlockT> *removeLoop(iterator I) {
623     assert(I != end() && "Cannot remove end iterator!");
624     LoopBase<BlockT> *L = *I;
625     assert(L->getParentLoop() == 0 && "Not a top-level loop!");
626     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
627     return L;
628   }
629   
630   /// changeLoopFor - Change the top-level loop that contains BB to the
631   /// specified loop.  This should be used by transformations that restructure
632   /// the loop hierarchy tree.
633   void changeLoopFor(BlockT *BB, LoopBase<BlockT> *L) {
634     LoopBase<BlockT> *&OldLoop = BBMap[BB];
635     assert(OldLoop && "Block not in a loop yet!");
636     OldLoop = L;
637   }
638   
639   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
640   /// list with the indicated loop.
641   void changeTopLevelLoop(LoopBase<BlockT> *OldLoop,
642                           LoopBase<BlockT> *NewLoop) {
643     typename std::vector<LoopBase<BlockT>*>::iterator I =
644                  std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
645     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
646     *I = NewLoop;
647     assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
648            "Loops already embedded into a subloop!");
649   }
650   
651   /// addTopLevelLoop - This adds the specified loop to the collection of
652   /// top-level loops.
653   void addTopLevelLoop(LoopBase<BlockT> *New) {
654     assert(New->getParentLoop() == 0 && "Loop already in subloop!");
655     TopLevelLoops.push_back(New);
656   }
657   
658   /// removeBlock - This method completely removes BB from all data structures,
659   /// including all of the Loop objects it is nested in and our mapping from
660   /// BasicBlocks to loops.
661   void removeBlock(BlockT *BB) {
662     typename std::map<BlockT *, LoopBase<BlockT>*>::iterator I = BBMap.find(BB);
663     if (I != BBMap.end()) {
664       for (LoopBase<BlockT> *L = I->second; L; L = L->getParentLoop())
665         L->removeBlockFromLoop(BB);
666
667       BBMap.erase(I);
668     }
669   }
670   
671   // Internals
672   
673   static bool isNotAlreadyContainedIn(LoopBase<BlockT> *SubLoop,
674                                       LoopBase<BlockT> *ParentLoop) {
675     if (SubLoop == 0) return true;
676     if (SubLoop == ParentLoop) return false;
677     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
678   }
679   
680   void Calculate(DominatorTreeBase<BlockT> &DT) {
681     BlockT *RootNode = DT.getRootNode()->getBlock();
682
683     for (df_iterator<BlockT*> NI = df_begin(RootNode),
684            NE = df_end(RootNode); NI != NE; ++NI)
685       if (LoopBase<BlockT> *L = ConsiderForLoop(*NI, DT))
686         TopLevelLoops.push_back(L);
687   }
688   
689   LoopBase<BlockT> *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
690     if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
691
692     std::vector<BlockT *> TodoStack;
693
694     // Scan the predecessors of BB, checking to see if BB dominates any of
695     // them.  This identifies backedges which target this node...
696     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
697     for (typename InvBlockTraits::ChildIteratorType I =
698          InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
699          I != E; ++I)
700       if (DT.dominates(BB, *I))   // If BB dominates it's predecessor...
701         TodoStack.push_back(*I);
702
703     if (TodoStack.empty()) return 0;  // No backedges to this block...
704
705     // Create a new loop to represent this basic block...
706     LoopBase<BlockT> *L = new LoopBase<BlockT>(BB);
707     BBMap[BB] = L;
708
709     BlockT *EntryBlock = BB->getParent()->begin();
710
711     while (!TodoStack.empty()) {  // Process all the nodes in the loop
712       BlockT *X = TodoStack.back();
713       TodoStack.pop_back();
714
715       if (!L->contains(X) &&         // As of yet unprocessed??
716           DT.dominates(EntryBlock, X)) {   // X is reachable from entry block?
717         // Check to see if this block already belongs to a loop.  If this occurs
718         // then we have a case where a loop that is supposed to be a child of
719         // the current loop was processed before the current loop.  When this
720         // occurs, this child loop gets added to a part of the current loop,
721         // making it a sibling to the current loop.  We have to reparent this
722         // loop.
723         if (LoopBase<BlockT> *SubLoop =
724             const_cast<LoopBase<BlockT>*>(getLoopFor(X)))
725           if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
726             // Remove the subloop from it's current parent...
727             assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
728             LoopBase<BlockT> *SLP = SubLoop->ParentLoop;  // SubLoopParent
729             typename std::vector<LoopBase<BlockT>*>::iterator I =
730               std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
731             assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
732             SLP->SubLoops.erase(I);   // Remove from parent...
733
734             // Add the subloop to THIS loop...
735             SubLoop->ParentLoop = L;
736             L->SubLoops.push_back(SubLoop);
737           }
738
739         // Normal case, add the block to our loop...
740         L->Blocks.push_back(X);
741         
742         typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
743         
744         // Add all of the predecessors of X to the end of the work stack...
745         TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
746                          InvBlockTraits::child_end(X));
747       }
748     }
749
750     // If there are any loops nested within this loop, create them now!
751     for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
752          E = L->Blocks.end(); I != E; ++I)
753       if (LoopBase<BlockT> *NewLoop = ConsiderForLoop(*I, DT)) {
754         L->SubLoops.push_back(NewLoop);
755         NewLoop->ParentLoop = L;
756       }
757
758     // Add the basic blocks that comprise this loop to the BBMap so that this
759     // loop can be found for them.
760     //
761     for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
762            E = L->Blocks.end(); I != E; ++I) {
763       typename std::map<BlockT*, LoopBase<BlockT>*>::iterator BBMI =
764                                                           BBMap.lower_bound(*I);
765       if (BBMI == BBMap.end() || BBMI->first != *I)  // Not in map yet...
766         BBMap.insert(BBMI, std::make_pair(*I, L));   // Must be at this level
767     }
768
769     // Now that we have a list of all of the child loops of this loop, check to
770     // see if any of them should actually be nested inside of each other.  We
771     // can accidentally pull loops our of their parents, so we must make sure to
772     // organize the loop nests correctly now.
773     {
774       std::map<BlockT*, LoopBase<BlockT>*> ContainingLoops;
775       for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
776         LoopBase<BlockT> *Child = L->SubLoops[i];
777         assert(Child->getParentLoop() == L && "Not proper child loop?");
778
779         if (LoopBase<BlockT> *ContainingLoop =
780                                           ContainingLoops[Child->getHeader()]) {
781           // If there is already a loop which contains this loop, move this loop
782           // into the containing loop.
783           MoveSiblingLoopInto(Child, ContainingLoop);
784           --i;  // The loop got removed from the SubLoops list.
785         } else {
786           // This is currently considered to be a top-level loop.  Check to see
787           // if any of the contained blocks are loop headers for subloops we
788           // have already processed.
789           for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
790             LoopBase<BlockT> *&BlockLoop = ContainingLoops[Child->Blocks[b]];
791             if (BlockLoop == 0) {   // Child block not processed yet...
792               BlockLoop = Child;
793             } else if (BlockLoop != Child) {
794               LoopBase<BlockT> *SubLoop = BlockLoop;
795               // Reparent all of the blocks which used to belong to BlockLoops
796               for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
797                 ContainingLoops[SubLoop->Blocks[j]] = Child;
798
799               // There is already a loop which contains this block, that means
800               // that we should reparent the loop which the block is currently
801               // considered to belong to to be a child of this loop.
802               MoveSiblingLoopInto(SubLoop, Child);
803               --i;  // We just shrunk the SubLoops list.
804             }
805           }
806         }
807       }
808     }
809
810     return L;
811   }
812   
813   /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
814   /// of the NewParent Loop, instead of being a sibling of it.
815   void MoveSiblingLoopInto(LoopBase<BlockT> *NewChild,
816                            LoopBase<BlockT> *NewParent) {
817     LoopBase<BlockT> *OldParent = NewChild->getParentLoop();
818     assert(OldParent && OldParent == NewParent->getParentLoop() &&
819            NewChild != NewParent && "Not sibling loops!");
820
821     // Remove NewChild from being a child of OldParent
822     typename std::vector<LoopBase<BlockT>*>::iterator I =
823       std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
824                 NewChild);
825     assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
826     OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
827     NewChild->ParentLoop = 0;
828
829     InsertLoopInto(NewChild, NewParent);
830   }
831   
832   /// InsertLoopInto - This inserts loop L into the specified parent loop.  If
833   /// the parent loop contains a loop which should contain L, the loop gets
834   /// inserted into L instead.
835   void InsertLoopInto(LoopBase<BlockT> *L, LoopBase<BlockT> *Parent) {
836     BlockT *LHeader = L->getHeader();
837     assert(Parent->contains(LHeader) &&
838            "This loop should not be inserted here!");
839
840     // Check to see if it belongs in a child loop...
841     for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
842       if (Parent->SubLoops[i]->contains(LHeader)) {
843         InsertLoopInto(L, Parent->SubLoops[i]);
844         return;
845       }
846
847     // If not, insert it here!
848     Parent->SubLoops.push_back(L);
849     L->ParentLoop = Parent;
850   }
851   
852   // Debugging
853   
854   void print(std::ostream &OS, const Module* ) const {
855     for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
856       TopLevelLoops[i]->print(OS);
857   #if 0
858     for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
859            E = BBMap.end(); I != E; ++I)
860       OS << "BB '" << I->first->getName() << "' level = "
861          << I->second->getLoopDepth() << "\n";
862   #endif
863   }
864 };
865
866 class LoopInfo : public FunctionPass {
867   LoopInfoBase<BasicBlock>* LI;
868   friend class LoopBase<BasicBlock>;
869   
870 public:
871   static char ID; // Pass identification, replacement for typeid
872
873   LoopInfo() : FunctionPass(intptr_t(&ID)) {
874     LI = new LoopInfoBase<BasicBlock>();
875   }
876   
877   ~LoopInfo() { delete LI; }
878
879   LoopInfoBase<BasicBlock>& getBase() { return *LI; }
880
881   /// iterator/begin/end - The interface to the top-level loops in the current
882   /// function.
883   ///
884   typedef std::vector<Loop*>::const_iterator iterator;
885   inline iterator begin() const { return LI->begin(); }
886   inline iterator end() const { return LI->end(); }
887
888   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
889   /// block is in no loop (for example the entry node), null is returned.
890   ///
891   inline Loop *getLoopFor(const BasicBlock *BB) const {
892     return LI->getLoopFor(BB);
893   }
894
895   /// operator[] - same as getLoopFor...
896   ///
897   inline const Loop *operator[](const BasicBlock *BB) const {
898     return LI->getLoopFor(BB);
899   }
900
901   /// getLoopDepth - Return the loop nesting level of the specified block...
902   ///
903   inline unsigned getLoopDepth(const BasicBlock *BB) const {
904     return LI->getLoopDepth(BB);
905   }
906
907   // isLoopHeader - True if the block is a loop header node
908   inline bool isLoopHeader(BasicBlock *BB) const {
909     return LI->isLoopHeader(BB);
910   }
911
912   /// runOnFunction - Calculate the natural loop information.
913   ///
914   virtual bool runOnFunction(Function &F);
915
916   virtual void releaseMemory() { LI->releaseMemory(); }
917
918   virtual void print(std::ostream &O, const Module* M = 0) const {
919     if (O) LI->print(O, M);
920   }
921
922   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
923
924   /// removeLoop - This removes the specified top-level loop from this loop info
925   /// object.  The loop is not deleted, as it will presumably be inserted into
926   /// another loop.
927   inline Loop *removeLoop(iterator I) { return LI->removeLoop(I); }
928
929   /// changeLoopFor - Change the top-level loop that contains BB to the
930   /// specified loop.  This should be used by transformations that restructure
931   /// the loop hierarchy tree.
932   inline void changeLoopFor(BasicBlock *BB, Loop *L) {
933     LI->changeLoopFor(BB, L);
934   }
935
936   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
937   /// list with the indicated loop.
938   inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
939     LI->changeTopLevelLoop(OldLoop, NewLoop);
940   }
941
942   /// addTopLevelLoop - This adds the specified loop to the collection of
943   /// top-level loops.
944   inline void addTopLevelLoop(Loop *New) {
945     LI->addTopLevelLoop(New);
946   }
947
948   /// removeBlock - This method completely removes BB from all data structures,
949   /// including all of the Loop objects it is nested in and our mapping from
950   /// BasicBlocks to loops.
951   void removeBlock(BasicBlock *BB) {
952     LI->removeBlock(BB);
953   }
954 };
955
956
957 // Allow clients to walk the list of nested loops...
958 template <> struct GraphTraits<const Loop*> {
959   typedef const Loop NodeType;
960   typedef std::vector<Loop*>::const_iterator ChildIteratorType;
961
962   static NodeType *getEntryNode(const Loop *L) { return L; }
963   static inline ChildIteratorType child_begin(NodeType *N) {
964     return N->begin();
965   }
966   static inline ChildIteratorType child_end(NodeType *N) {
967     return N->end();
968   }
969 };
970
971 template <> struct GraphTraits<Loop*> {
972   typedef Loop NodeType;
973   typedef std::vector<Loop*>::const_iterator ChildIteratorType;
974
975   static NodeType *getEntryNode(Loop *L) { return L; }
976   static inline ChildIteratorType child_begin(NodeType *N) {
977     return N->begin();
978   }
979   static inline ChildIteratorType child_end(NodeType *N) {
980     return N->end();
981   }
982 };
983
984 template<class BlockT>
985 void LoopBase<BlockT>::addBasicBlockToLoop(BlockT *NewBB,
986                                            LoopInfoBase<BlockT> &LIB) {
987   assert((Blocks.empty() || LIB[getHeader()] == this) &&
988          "Incorrect LI specified for this loop!");
989   assert(NewBB && "Cannot add a null basic block to the loop!");
990   assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
991
992   // Add the loop mapping to the LoopInfo object...
993   LIB.BBMap[NewBB] = this;
994
995   // Add the basic block to this loop and all parent loops...
996   LoopBase<BlockT> *L = this;
997   while (L) {
998     L->Blocks.push_back(NewBB);
999     L = L->getParentLoop();
1000   }
1001 }
1002
1003 } // End llvm namespace
1004
1005 // Make sure that any clients of this file link in LoopInfo.cpp
1006 FORCE_DEFINING_FILE_TO_BE_LINKED(LoopInfo)
1007
1008 #endif