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