Simplify, no functionality change.
[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/ADT/STLExtras.h"
39 #include "llvm/Analysis/Dominators.h"
40 #include "llvm/Support/CFG.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   /// Edge type.
234   typedef std::pair<BlockT*, BlockT*> Edge;
235
236   /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
237   template <typename EdgeT>
238   void getExitEdges(SmallVectorImpl<EdgeT> &ExitEdges) const {
239     // Sort the blocks vector so that we can use binary search to do quick
240     // lookups.
241     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
242     array_pod_sort(LoopBBs.begin(), LoopBBs.end());
243
244     typedef GraphTraits<BlockT*> BlockTraits;
245     for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
246       for (typename BlockTraits::ChildIteratorType I =
247            BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
248            I != E; ++I)
249         if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
250           // Not in current loop? It must be an exit block.
251           ExitEdges.push_back(EdgeT(*BI, *I));
252   }
253
254   /// getLoopPreheader - If there is a preheader for this loop, return it.  A
255   /// loop has a preheader if there is only one edge to the header of the loop
256   /// from outside of the loop.  If this is the case, the block branching to the
257   /// header of the loop is the preheader node.
258   ///
259   /// This method returns null if there is no preheader for the loop.
260   ///
261   BlockT *getLoopPreheader() const {
262     // Keep track of nodes outside the loop branching to the header...
263     BlockT *Out = getLoopPredecessor();
264     if (!Out) return 0;
265
266     // Make sure there is only one exit out of the preheader.
267     typedef GraphTraits<BlockT*> BlockTraits;
268     typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
269     ++SI;
270     if (SI != BlockTraits::child_end(Out))
271       return 0;  // Multiple exits from the block, must not be a preheader.
272
273     // The predecessor has exactly one successor, so it is a preheader.
274     return Out;
275   }
276
277   /// getLoopPredecessor - If the given loop's header has exactly one unique
278   /// predecessor outside the loop, return it. Otherwise return null.
279   /// This is less strict that the loop "preheader" concept, which requires
280   /// the predecessor to have exactly one successor.
281   ///
282   BlockT *getLoopPredecessor() const {
283     // Keep track of nodes outside the loop branching to the header...
284     BlockT *Out = 0;
285
286     // Loop over the predecessors of the header node...
287     BlockT *Header = getHeader();
288     typedef GraphTraits<BlockT*> BlockTraits;
289     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
290     for (typename InvBlockTraits::ChildIteratorType PI =
291          InvBlockTraits::child_begin(Header),
292          PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
293       typename InvBlockTraits::NodeType *N = *PI;
294       if (!contains(N)) {     // If the block is not in the loop...
295         if (Out && Out != N)
296           return 0;             // Multiple predecessors outside the loop
297         Out = N;
298       }
299     }
300
301     // Make sure there is only one exit out of the preheader.
302     assert(Out && "Header of loop has no predecessors from outside loop?");
303     return Out;
304   }
305
306   /// getLoopLatch - If there is a single latch block for this loop, return it.
307   /// A latch block is a block that contains a branch back to the header.
308   BlockT *getLoopLatch() const {
309     BlockT *Header = getHeader();
310     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
311     typename InvBlockTraits::ChildIteratorType PI =
312                                             InvBlockTraits::child_begin(Header);
313     typename InvBlockTraits::ChildIteratorType PE =
314                                               InvBlockTraits::child_end(Header);
315     BlockT *Latch = 0;
316     for (; PI != PE; ++PI) {
317       typename InvBlockTraits::NodeType *N = *PI;
318       if (contains(N)) {
319         if (Latch) return 0;
320         Latch = N;
321       }
322     }
323
324     return Latch;
325   }
326
327   //===--------------------------------------------------------------------===//
328   // APIs for updating loop information after changing the CFG
329   //
330
331   /// addBasicBlockToLoop - This method is used by other analyses to update loop
332   /// information.  NewBB is set to be a new member of the current loop.
333   /// Because of this, it is added as a member of all parent loops, and is added
334   /// to the specified LoopInfo object as being in the current basic block.  It
335   /// is not valid to replace the loop header with this method.
336   ///
337   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
338
339   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
340   /// the OldChild entry in our children list with NewChild, and updates the
341   /// parent pointer of OldChild to be null and the NewChild to be this loop.
342   /// This updates the loop depth of the new child.
343   void replaceChildLoopWith(LoopT *OldChild,
344                             LoopT *NewChild) {
345     assert(OldChild->ParentLoop == this && "This loop is already broken!");
346     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
347     typename std::vector<LoopT *>::iterator I =
348                           std::find(SubLoops.begin(), SubLoops.end(), OldChild);
349     assert(I != SubLoops.end() && "OldChild not in loop!");
350     *I = NewChild;
351     OldChild->ParentLoop = 0;
352     NewChild->ParentLoop = static_cast<LoopT *>(this);
353   }
354
355   /// addChildLoop - Add the specified loop to be a child of this loop.  This
356   /// updates the loop depth of the new child.
357   ///
358   void addChildLoop(LoopT *NewChild) {
359     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
360     NewChild->ParentLoop = static_cast<LoopT *>(this);
361     SubLoops.push_back(NewChild);
362   }
363
364   /// removeChildLoop - This removes the specified child from being a subloop of
365   /// this loop.  The loop is not deleted, as it will presumably be inserted
366   /// into another loop.
367   LoopT *removeChildLoop(iterator I) {
368     assert(I != SubLoops.end() && "Cannot remove end iterator!");
369     LoopT *Child = *I;
370     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
371     SubLoops.erase(SubLoops.begin()+(I-begin()));
372     Child->ParentLoop = 0;
373     return Child;
374   }
375
376   /// addBlockEntry - This adds a basic block directly to the basic block list.
377   /// This should only be used by transformations that create new loops.  Other
378   /// transformations should use addBasicBlockToLoop.
379   void addBlockEntry(BlockT *BB) {
380     Blocks.push_back(BB);
381   }
382
383   /// moveToHeader - This method is used to move BB (which must be part of this
384   /// loop) to be the loop header of the loop (the block that dominates all
385   /// others).
386   void moveToHeader(BlockT *BB) {
387     if (Blocks[0] == BB) return;
388     for (unsigned i = 0; ; ++i) {
389       assert(i != Blocks.size() && "Loop does not contain BB!");
390       if (Blocks[i] == BB) {
391         Blocks[i] = Blocks[0];
392         Blocks[0] = BB;
393         return;
394       }
395     }
396   }
397
398   /// removeBlockFromLoop - This removes the specified basic block from the
399   /// current loop, updating the Blocks as appropriate.  This does not update
400   /// the mapping in the LoopInfo class.
401   void removeBlockFromLoop(BlockT *BB) {
402     RemoveFromVector(Blocks, BB);
403   }
404
405   /// verifyLoop - Verify loop structure
406   void verifyLoop() const {
407 #ifndef NDEBUG
408     assert(!Blocks.empty() && "Loop header is missing");
409
410     // Sort the blocks vector so that we can use binary search to do quick
411     // lookups.
412     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
413     std::sort(LoopBBs.begin(), LoopBBs.end());
414
415     // Check the individual blocks.
416     for (block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
417       BlockT *BB = *I;
418       bool HasInsideLoopSuccs = false;
419       bool HasInsideLoopPreds = false;
420       SmallVector<BlockT *, 2> OutsideLoopPreds;
421
422       typedef GraphTraits<BlockT*> BlockTraits;
423       for (typename BlockTraits::ChildIteratorType SI =
424            BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
425            SI != SE; ++SI)
426         if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
427           HasInsideLoopSuccs = true;
428           break;
429         }
430       typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
431       for (typename InvBlockTraits::ChildIteratorType PI =
432            InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
433            PI != PE; ++PI) {
434         typename InvBlockTraits::NodeType *N = *PI;
435         if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), N))
436           HasInsideLoopPreds = true;
437         else
438           OutsideLoopPreds.push_back(N);
439       }
440
441       if (BB == getHeader()) {
442         assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
443       } else if (!OutsideLoopPreds.empty()) {
444         // A non-header loop shouldn't be reachable from outside the loop,
445         // though it is permitted if the predecessor is not itself actually
446         // reachable.
447         BlockT *EntryBB = BB->getParent()->begin();
448         for (df_iterator<BlockT *> NI = df_begin(EntryBB),
449              NE = df_end(EntryBB); NI != NE; ++NI)
450           for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
451             assert(*NI != OutsideLoopPreds[i] &&
452                    "Loop has multiple entry points!");
453       }
454       assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
455       assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
456       assert(BB != getHeader()->getParent()->begin() &&
457              "Loop contains function entry block!");
458     }
459
460     // Check the subloops.
461     for (iterator I = begin(), E = end(); I != E; ++I)
462       // Each block in each subloop should be contained within this loop.
463       for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
464            BI != BE; ++BI) {
465         assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
466                "Loop does not contain all the blocks of a subloop!");
467       }
468
469     // Check the parent loop pointer.
470     if (ParentLoop) {
471       assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
472                ParentLoop->end() &&
473              "Loop is not a subloop of its parent!");
474     }
475 #endif
476   }
477
478   /// verifyLoop - Verify loop structure of this loop and all nested loops.
479   void verifyLoopNest() const {
480     // Verify this loop.
481     verifyLoop();
482     // Verify the subloops.
483     for (iterator I = begin(), E = end(); I != E; ++I)
484       (*I)->verifyLoopNest();
485   }
486
487   void print(raw_ostream &OS, unsigned Depth = 0) const {
488     OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
489        << " containing: ";
490
491     for (unsigned i = 0; i < getBlocks().size(); ++i) {
492       if (i) OS << ",";
493       BlockT *BB = getBlocks()[i];
494       WriteAsOperand(OS, BB, false);
495       if (BB == getHeader())    OS << "<header>";
496       if (BB == getLoopLatch()) OS << "<latch>";
497       if (isLoopExiting(BB))    OS << "<exiting>";
498     }
499     OS << "\n";
500
501     for (iterator I = begin(), E = end(); I != E; ++I)
502       (*I)->print(OS, Depth+2);
503   }
504
505 protected:
506   friend class LoopInfoBase<BlockT, LoopT>;
507   explicit LoopBase(BlockT *BB) : ParentLoop(0) {
508     Blocks.push_back(BB);
509   }
510 };
511
512 template<class BlockT, class LoopT>
513 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
514   Loop.print(OS);
515   return OS;
516 }
517
518 class Loop : public LoopBase<BasicBlock, Loop> {
519 public:
520   Loop() {}
521
522   /// isLoopInvariant - Return true if the specified value is loop invariant
523   ///
524   bool isLoopInvariant(Value *V) const;
525
526   /// hasLoopInvariantOperands - Return true if all the operands of the
527   /// specified instruction are loop invariant. 
528   bool hasLoopInvariantOperands(Instruction *I) const;
529
530   /// makeLoopInvariant - If the given value is an instruction inside of the
531   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
532   /// Return true if the value after any hoisting is loop invariant. This
533   /// function can be used as a slightly more aggressive replacement for
534   /// isLoopInvariant.
535   ///
536   /// If InsertPt is specified, it is the point to hoist instructions to.
537   /// If null, the terminator of the loop preheader is used.
538   ///
539   bool makeLoopInvariant(Value *V, bool &Changed,
540                          Instruction *InsertPt = 0) const;
541
542   /// makeLoopInvariant - If the given instruction is inside of the
543   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
544   /// Return true if the instruction after any hoisting is loop invariant. This
545   /// function can be used as a slightly more aggressive replacement for
546   /// isLoopInvariant.
547   ///
548   /// If InsertPt is specified, it is the point to hoist instructions to.
549   /// If null, the terminator of the loop preheader is used.
550   ///
551   bool makeLoopInvariant(Instruction *I, bool &Changed,
552                          Instruction *InsertPt = 0) const;
553
554   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
555   /// induction variable: an integer recurrence that starts at 0 and increments
556   /// by one each time through the loop.  If so, return the phi node that
557   /// corresponds to it.
558   ///
559   /// The IndVarSimplify pass transforms loops to have a canonical induction
560   /// variable.
561   ///
562   PHINode *getCanonicalInductionVariable() const;
563
564   /// getTripCount - Return a loop-invariant LLVM value indicating the number of
565   /// times the loop will be executed.  Note that this means that the backedge
566   /// of the loop executes N-1 times.  If the trip-count cannot be determined,
567   /// this returns null.
568   ///
569   /// The IndVarSimplify pass transforms loops to have a form that this
570   /// function easily understands.
571   ///
572   Value *getTripCount() const;
573
574   /// getSmallConstantTripCount - Returns the trip count of this loop as a
575   /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
576   /// of not constant. Will also return 0 if the trip count is very large
577   /// (>= 2^32)
578   ///
579   /// The IndVarSimplify pass transforms loops to have a form that this
580   /// function easily understands.
581   ///
582   unsigned getSmallConstantTripCount() const;
583
584   /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
585   /// trip count of this loop as a normal unsigned value, if possible. This
586   /// means that the actual trip count is always a multiple of the returned
587   /// value (don't forget the trip count could very well be zero as well!).
588   ///
589   /// Returns 1 if the trip count is unknown or not guaranteed to be the
590   /// multiple of a constant (which is also the case if the trip count is simply
591   /// constant, use getSmallConstantTripCount for that case), Will also return 1
592   /// if the trip count is very large (>= 2^32).
593   unsigned getSmallConstantTripMultiple() const;
594
595   /// isLCSSAForm - Return true if the Loop is in LCSSA form
596   bool isLCSSAForm(DominatorTree &DT) const;
597
598   /// isLoopSimplifyForm - Return true if the Loop is in the form that
599   /// the LoopSimplify form transforms loops to, which is sometimes called
600   /// normal form.
601   bool isLoopSimplifyForm() const;
602
603   /// hasDedicatedExits - Return true if no exit block for the loop
604   /// has a predecessor that is outside the loop.
605   bool hasDedicatedExits() const;
606
607   /// getUniqueExitBlocks - Return all unique successor blocks of this loop. 
608   /// These are the blocks _outside of the current loop_ which are branched to.
609   /// This assumes that loop exits are in canonical form.
610   ///
611   void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
612
613   /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
614   /// block, return that block. Otherwise return null.
615   BasicBlock *getUniqueExitBlock() const;
616
617   void dump() const;
618   
619 private:
620   friend class LoopInfoBase<BasicBlock, Loop>;
621   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
622 };
623
624 //===----------------------------------------------------------------------===//
625 /// LoopInfo - This class builds and contains all of the top level loop
626 /// structures in the specified function.
627 ///
628
629 template<class BlockT, class LoopT>
630 class LoopInfoBase {
631   // BBMap - Mapping of basic blocks to the inner most loop they occur in
632   std::map<BlockT *, LoopT *> BBMap;
633   std::vector<LoopT *> TopLevelLoops;
634   friend class LoopBase<BlockT, LoopT>;
635
636   void operator=(const LoopInfoBase &); // do not implement
637   LoopInfoBase(const LoopInfo &);       // do not implement
638 public:
639   LoopInfoBase() { }
640   ~LoopInfoBase() { releaseMemory(); }
641   
642   void releaseMemory() {
643     for (typename std::vector<LoopT *>::iterator I =
644          TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
645       delete *I;   // Delete all of the loops...
646
647     BBMap.clear();                           // Reset internal state of analysis
648     TopLevelLoops.clear();
649   }
650   
651   /// iterator/begin/end - The interface to the top-level loops in the current
652   /// function.
653   ///
654   typedef typename std::vector<LoopT *>::const_iterator iterator;
655   iterator begin() const { return TopLevelLoops.begin(); }
656   iterator end() const { return TopLevelLoops.end(); }
657   bool empty() const { return TopLevelLoops.empty(); }
658   
659   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
660   /// block is in no loop (for example the entry node), null is returned.
661   ///
662   LoopT *getLoopFor(const BlockT *BB) const {
663     typename std::map<BlockT *, LoopT *>::const_iterator I=
664       BBMap.find(const_cast<BlockT*>(BB));
665     return I != BBMap.end() ? I->second : 0;
666   }
667   
668   /// operator[] - same as getLoopFor...
669   ///
670   const LoopT *operator[](const BlockT *BB) const {
671     return getLoopFor(BB);
672   }
673   
674   /// getLoopDepth - Return the loop nesting level of the specified block.  A
675   /// depth of 0 means the block is not inside any loop.
676   ///
677   unsigned getLoopDepth(const BlockT *BB) const {
678     const LoopT *L = getLoopFor(BB);
679     return L ? L->getLoopDepth() : 0;
680   }
681
682   // isLoopHeader - True if the block is a loop header node
683   bool isLoopHeader(BlockT *BB) const {
684     const LoopT *L = getLoopFor(BB);
685     return L && L->getHeader() == BB;
686   }
687   
688   /// removeLoop - This removes the specified top-level loop from this loop info
689   /// object.  The loop is not deleted, as it will presumably be inserted into
690   /// another loop.
691   LoopT *removeLoop(iterator I) {
692     assert(I != end() && "Cannot remove end iterator!");
693     LoopT *L = *I;
694     assert(L->getParentLoop() == 0 && "Not a top-level loop!");
695     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
696     return L;
697   }
698   
699   /// changeLoopFor - Change the top-level loop that contains BB to the
700   /// specified loop.  This should be used by transformations that restructure
701   /// the loop hierarchy tree.
702   void changeLoopFor(BlockT *BB, LoopT *L) {
703     LoopT *&OldLoop = BBMap[BB];
704     assert(OldLoop && "Block not in a loop yet!");
705     OldLoop = L;
706   }
707   
708   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
709   /// list with the indicated loop.
710   void changeTopLevelLoop(LoopT *OldLoop,
711                           LoopT *NewLoop) {
712     typename std::vector<LoopT *>::iterator I =
713                  std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
714     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
715     *I = NewLoop;
716     assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
717            "Loops already embedded into a subloop!");
718   }
719   
720   /// addTopLevelLoop - This adds the specified loop to the collection of
721   /// top-level loops.
722   void addTopLevelLoop(LoopT *New) {
723     assert(New->getParentLoop() == 0 && "Loop already in subloop!");
724     TopLevelLoops.push_back(New);
725   }
726   
727   /// removeBlock - This method completely removes BB from all data structures,
728   /// including all of the Loop objects it is nested in and our mapping from
729   /// BasicBlocks to loops.
730   void removeBlock(BlockT *BB) {
731     typename std::map<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
732     if (I != BBMap.end()) {
733       for (LoopT *L = I->second; L; L = L->getParentLoop())
734         L->removeBlockFromLoop(BB);
735
736       BBMap.erase(I);
737     }
738   }
739   
740   // Internals
741   
742   static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
743                                       const LoopT *ParentLoop) {
744     if (SubLoop == 0) return true;
745     if (SubLoop == ParentLoop) return false;
746     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
747   }
748   
749   void Calculate(DominatorTreeBase<BlockT> &DT) {
750     BlockT *RootNode = DT.getRootNode()->getBlock();
751
752     for (df_iterator<BlockT*> NI = df_begin(RootNode),
753            NE = df_end(RootNode); NI != NE; ++NI)
754       if (LoopT *L = ConsiderForLoop(*NI, DT))
755         TopLevelLoops.push_back(L);
756   }
757   
758   LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
759     if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
760
761     std::vector<BlockT *> TodoStack;
762
763     // Scan the predecessors of BB, checking to see if BB dominates any of
764     // them.  This identifies backedges which target this node...
765     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
766     for (typename InvBlockTraits::ChildIteratorType I =
767          InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
768          I != E; ++I) {
769       typename InvBlockTraits::NodeType *N = *I;
770       if (DT.dominates(BB, N))   // If BB dominates its predecessor...
771           TodoStack.push_back(N);
772     }
773
774     if (TodoStack.empty()) return 0;  // No backedges to this block...
775
776     // Create a new loop to represent this basic block...
777     LoopT *L = new LoopT(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 (LoopT *SubLoop =
795             const_cast<LoopT *>(getLoopFor(X)))
796           if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
797             // Remove the subloop from its current parent...
798             assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
799             LoopT *SLP = SubLoop->ParentLoop;  // SubLoopParent
800             typename std::vector<LoopT *>::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 (LoopT *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       BBMap.insert(std::make_pair(*I, L));
835
836     // Now that we have a list of all of the child loops of this loop, check to
837     // see if any of them should actually be nested inside of each other.  We
838     // can accidentally pull loops our of their parents, so we must make sure to
839     // organize the loop nests correctly now.
840     {
841       std::map<BlockT *, LoopT *> ContainingLoops;
842       for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
843         LoopT *Child = L->SubLoops[i];
844         assert(Child->getParentLoop() == L && "Not proper child loop?");
845
846         if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
847           // If there is already a loop which contains this loop, move this loop
848           // into the containing loop.
849           MoveSiblingLoopInto(Child, ContainingLoop);
850           --i;  // The loop got removed from the SubLoops list.
851         } else {
852           // This is currently considered to be a top-level loop.  Check to see
853           // if any of the contained blocks are loop headers for subloops we
854           // have already processed.
855           for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
856             LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
857             if (BlockLoop == 0) {   // Child block not processed yet...
858               BlockLoop = Child;
859             } else if (BlockLoop != Child) {
860               LoopT *SubLoop = BlockLoop;
861               // Reparent all of the blocks which used to belong to BlockLoops
862               for (unsigned j = 0, f = SubLoop->Blocks.size(); j != f; ++j)
863                 ContainingLoops[SubLoop->Blocks[j]] = Child;
864
865               // There is already a loop which contains this block, that means
866               // that we should reparent the loop which the block is currently
867               // considered to belong to to be a child of this loop.
868               MoveSiblingLoopInto(SubLoop, Child);
869               --i;  // We just shrunk the SubLoops list.
870             }
871           }
872         }
873       }
874     }
875
876     return L;
877   }
878   
879   /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
880   /// of the NewParent Loop, instead of being a sibling of it.
881   void MoveSiblingLoopInto(LoopT *NewChild,
882                            LoopT *NewParent) {
883     LoopT *OldParent = NewChild->getParentLoop();
884     assert(OldParent && OldParent == NewParent->getParentLoop() &&
885            NewChild != NewParent && "Not sibling loops!");
886
887     // Remove NewChild from being a child of OldParent
888     typename std::vector<LoopT *>::iterator I =
889       std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
890                 NewChild);
891     assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
892     OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
893     NewChild->ParentLoop = 0;
894
895     InsertLoopInto(NewChild, NewParent);
896   }
897   
898   /// InsertLoopInto - This inserts loop L into the specified parent loop.  If
899   /// the parent loop contains a loop which should contain L, the loop gets
900   /// inserted into L instead.
901   void InsertLoopInto(LoopT *L, LoopT *Parent) {
902     BlockT *LHeader = L->getHeader();
903     assert(Parent->contains(LHeader) &&
904            "This loop should not be inserted here!");
905
906     // Check to see if it belongs in a child loop...
907     for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
908          i != e; ++i)
909       if (Parent->SubLoops[i]->contains(LHeader)) {
910         InsertLoopInto(L, Parent->SubLoops[i]);
911         return;
912       }
913
914     // If not, insert it here!
915     Parent->SubLoops.push_back(L);
916     L->ParentLoop = Parent;
917   }
918   
919   // Debugging
920   
921   void print(raw_ostream &OS) const {
922     for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
923       TopLevelLoops[i]->print(OS);
924   #if 0
925     for (std::map<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
926            E = BBMap.end(); I != E; ++I)
927       OS << "BB '" << I->first->getName() << "' level = "
928          << I->second->getLoopDepth() << "\n";
929   #endif
930   }
931 };
932
933 class LoopInfo : public FunctionPass {
934   LoopInfoBase<BasicBlock, Loop> LI;
935   friend class LoopBase<BasicBlock, Loop>;
936
937   void operator=(const LoopInfo &); // do not implement
938   LoopInfo(const LoopInfo &);       // do not implement
939 public:
940   static char ID; // Pass identification, replacement for typeid
941
942   LoopInfo() : FunctionPass(ID) {
943     initializeLoopInfoPass(*PassRegistry::getPassRegistry());
944   }
945
946   LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
947
948   /// iterator/begin/end - The interface to the top-level loops in the current
949   /// function.
950   ///
951   typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
952   inline iterator begin() const { return LI.begin(); }
953   inline iterator end() const { return LI.end(); }
954   bool empty() const { return LI.empty(); }
955
956   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
957   /// block is in no loop (for example the entry node), null is returned.
958   ///
959   inline Loop *getLoopFor(const BasicBlock *BB) const {
960     return LI.getLoopFor(BB);
961   }
962
963   /// operator[] - same as getLoopFor...
964   ///
965   inline const Loop *operator[](const BasicBlock *BB) const {
966     return LI.getLoopFor(BB);
967   }
968
969   /// getLoopDepth - Return the loop nesting level of the specified block.  A
970   /// depth of 0 means the block is not inside any loop.
971   ///
972   inline unsigned getLoopDepth(const BasicBlock *BB) const {
973     return LI.getLoopDepth(BB);
974   }
975
976   // isLoopHeader - True if the block is a loop header node
977   inline bool isLoopHeader(BasicBlock *BB) const {
978     return LI.isLoopHeader(BB);
979   }
980
981   /// runOnFunction - Calculate the natural loop information.
982   ///
983   virtual bool runOnFunction(Function &F);
984
985   virtual void verifyAnalysis() const;
986
987   virtual void releaseMemory() { LI.releaseMemory(); }
988
989   virtual void print(raw_ostream &O, const Module* M = 0) const;
990   
991   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
992
993   /// removeLoop - This removes the specified top-level loop from this loop info
994   /// object.  The loop is not deleted, as it will presumably be inserted into
995   /// another loop.
996   inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
997
998   /// changeLoopFor - Change the top-level loop that contains BB to the
999   /// specified loop.  This should be used by transformations that restructure
1000   /// the loop hierarchy tree.
1001   inline void changeLoopFor(BasicBlock *BB, Loop *L) {
1002     LI.changeLoopFor(BB, L);
1003   }
1004
1005   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
1006   /// list with the indicated loop.
1007   inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
1008     LI.changeTopLevelLoop(OldLoop, NewLoop);
1009   }
1010
1011   /// addTopLevelLoop - This adds the specified loop to the collection of
1012   /// top-level loops.
1013   inline void addTopLevelLoop(Loop *New) {
1014     LI.addTopLevelLoop(New);
1015   }
1016
1017   /// removeBlock - This method completely removes BB from all data structures,
1018   /// including all of the Loop objects it is nested in and our mapping from
1019   /// BasicBlocks to loops.
1020   void removeBlock(BasicBlock *BB) {
1021     LI.removeBlock(BB);
1022   }
1023
1024   /// replacementPreservesLCSSAForm - Returns true if replacing From with To
1025   /// everywhere is guaranteed to preserve LCSSA form.
1026   bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
1027     // Preserving LCSSA form is only problematic if the replacing value is an
1028     // instruction.
1029     Instruction *I = dyn_cast<Instruction>(To);
1030     if (!I) return true;
1031     // If the instruction is not defined in a loop then it can safely replace
1032     // anything.
1033     Loop *ToLoop = getLoopFor(I->getParent());
1034     if (!ToLoop) return true;
1035     // If the replacing instruction is defined in the same loop as the original
1036     // instruction, or in a loop that contains it as an inner loop, then using
1037     // it as a replacement will not break LCSSA form.
1038     return ToLoop->contains(getLoopFor(From->getParent()));
1039   }
1040 };
1041
1042
1043 // Allow clients to walk the list of nested loops...
1044 template <> struct GraphTraits<const Loop*> {
1045   typedef const Loop NodeType;
1046   typedef LoopInfo::iterator ChildIteratorType;
1047
1048   static NodeType *getEntryNode(const Loop *L) { return L; }
1049   static inline ChildIteratorType child_begin(NodeType *N) {
1050     return N->begin();
1051   }
1052   static inline ChildIteratorType child_end(NodeType *N) {
1053     return N->end();
1054   }
1055 };
1056
1057 template <> struct GraphTraits<Loop*> {
1058   typedef Loop NodeType;
1059   typedef LoopInfo::iterator ChildIteratorType;
1060
1061   static NodeType *getEntryNode(Loop *L) { return L; }
1062   static inline ChildIteratorType child_begin(NodeType *N) {
1063     return N->begin();
1064   }
1065   static inline ChildIteratorType child_end(NodeType *N) {
1066     return N->end();
1067   }
1068 };
1069
1070 template<class BlockT, class LoopT>
1071 void
1072 LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1073                                              LoopInfoBase<BlockT, LoopT> &LIB) {
1074   assert((Blocks.empty() || LIB[getHeader()] == this) &&
1075          "Incorrect LI specified for this loop!");
1076   assert(NewBB && "Cannot add a null basic block to the loop!");
1077   assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1078
1079   LoopT *L = static_cast<LoopT *>(this);
1080
1081   // Add the loop mapping to the LoopInfo object...
1082   LIB.BBMap[NewBB] = L;
1083
1084   // Add the basic block to this loop and all parent loops...
1085   while (L) {
1086     L->Blocks.push_back(NewBB);
1087     L = L->getParentLoop();
1088   }
1089 }
1090
1091 } // End llvm namespace
1092
1093 #endif