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