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