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