LoopInfo.h revision 29521a0fb9ba7ed6a2fc50d2c958151f86963ead
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//  * etc...
27//
28//===----------------------------------------------------------------------===//
29
30#ifndef LLVM_ANALYSIS_LOOPINFO_H
31#define LLVM_ANALYSIS_LOOPINFO_H
32
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/DenseSet.h"
35#include "llvm/ADT/GraphTraits.h"
36#include "llvm/ADT/SmallVector.h"
37#include "llvm/Analysis/Dominators.h"
38#include "llvm/Pass.h"
39#include "llvm/Support/raw_ostream.h"
40#include <algorithm>
41
42namespace llvm {
43
44template<typename T>
45inline 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;
54class PHINode;
55template<class N, class M> class LoopInfoBase;
56template<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///
62template<class BlockT, class LoopT>
63class 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  LoopBase(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
72  const LoopBase<BlockT, LoopT>&
73    operator=(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
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  /// setParentLoop is a raw interface for bypassing addChildLoop.
96  void setParentLoop(LoopT *L) { ParentLoop = L; }
97
98  /// contains - Return true if the specified loop is contained within in
99  /// this loop.
100  ///
101  bool contains(const LoopT *L) const {
102    if (L == this) return true;
103    if (L == 0)    return false;
104    return contains(L->getParentLoop());
105  }
106
107  /// contains - Return true if the specified basic block is in this loop.
108  ///
109  bool contains(const BlockT *BB) const {
110    return std::find(block_begin(), block_end(), BB) != block_end();
111  }
112
113  /// contains - Return true if the specified instruction is in this loop.
114  ///
115  template<class InstT>
116  bool contains(const InstT *Inst) const {
117    return contains(Inst->getParent());
118  }
119
120  /// iterator/begin/end - Return the loops contained entirely within this loop.
121  ///
122  const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
123  std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
124  typedef typename std::vector<LoopT *>::const_iterator iterator;
125  typedef typename std::vector<LoopT *>::const_reverse_iterator
126    reverse_iterator;
127  iterator begin() const { return SubLoops.begin(); }
128  iterator end() const { return SubLoops.end(); }
129  reverse_iterator rbegin() const { return SubLoops.rbegin(); }
130  reverse_iterator rend() const { return SubLoops.rend(); }
131  bool empty() const { return SubLoops.empty(); }
132
133  /// getBlocks - Get a list of the basic blocks which make up this loop.
134  ///
135  const std::vector<BlockT*> &getBlocks() const { return Blocks; }
136  std::vector<BlockT*> &getBlocksVector() { return Blocks; }
137  typedef typename std::vector<BlockT*>::const_iterator block_iterator;
138  block_iterator block_begin() const { return Blocks.begin(); }
139  block_iterator block_end() const { return Blocks.end(); }
140
141  /// getNumBlocks - Get the number of blocks in this loop in constant time.
142  unsigned getNumBlocks() const {
143    return Blocks.size();
144  }
145
146  /// isLoopExiting - True if terminator in the block can branch to another
147  /// block that is outside of the current loop.
148  ///
149  bool isLoopExiting(const BlockT *BB) const {
150    typedef GraphTraits<BlockT*> BlockTraits;
151    for (typename BlockTraits::ChildIteratorType SI =
152         BlockTraits::child_begin(const_cast<BlockT*>(BB)),
153         SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
154      if (!contains(*SI))
155        return true;
156    }
157    return false;
158  }
159
160  /// getNumBackEdges - Calculate the number of back edges to the loop header
161  ///
162  unsigned getNumBackEdges() const {
163    unsigned NumBackEdges = 0;
164    BlockT *H = getHeader();
165
166    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
167    for (typename InvBlockTraits::ChildIteratorType I =
168         InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
169         E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
170      if (contains(*I))
171        ++NumBackEdges;
172
173    return NumBackEdges;
174  }
175
176  //===--------------------------------------------------------------------===//
177  // APIs for simple analysis of the loop.
178  //
179  // Note that all of these methods can fail on general loops (ie, there may not
180  // be a preheader, etc).  For best success, the loop simplification and
181  // induction variable canonicalization pass should be used to normalize loops
182  // for easy analysis.  These methods assume canonical loops.
183
184  /// getExitingBlocks - Return all blocks inside the loop that have successors
185  /// outside of the loop.  These are the blocks _inside of the current loop_
186  /// which branch out.  The returned list is always unique.
187  ///
188  void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
189
190  /// getExitingBlock - If getExitingBlocks would return exactly one block,
191  /// return that block. Otherwise return null.
192  BlockT *getExitingBlock() const;
193
194  /// getExitBlocks - Return all of the successor blocks of this loop.  These
195  /// are the blocks _outside of the current loop_ which are branched to.
196  ///
197  void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
198
199  /// getExitBlock - If getExitBlocks would return exactly one block,
200  /// return that block. Otherwise return null.
201  BlockT *getExitBlock() const;
202
203  /// Edge type.
204  typedef std::pair<const BlockT*, const BlockT*> Edge;
205
206  /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
207  void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
208
209  /// getLoopPreheader - If there is a preheader for this loop, return it.  A
210  /// loop has a preheader if there is only one edge to the header of the loop
211  /// from outside of the loop.  If this is the case, the block branching to the
212  /// header of the loop is the preheader node.
213  ///
214  /// This method returns null if there is no preheader for the loop.
215  ///
216  BlockT *getLoopPreheader() const;
217
218  /// getLoopPredecessor - If the given loop's header has exactly one unique
219  /// predecessor outside the loop, return it. Otherwise return null.
220  /// This is less strict that the loop "preheader" concept, which requires
221  /// the predecessor to have exactly one successor.
222  ///
223  BlockT *getLoopPredecessor() const;
224
225  /// getLoopLatch - If there is a single latch block for this loop, return it.
226  /// A latch block is a block that contains a branch back to the header.
227  BlockT *getLoopLatch() const;
228
229  //===--------------------------------------------------------------------===//
230  // APIs for updating loop information after changing the CFG
231  //
232
233  /// addBasicBlockToLoop - This method is used by other analyses to update loop
234  /// information.  NewBB is set to be a new member of the current loop.
235  /// Because of this, it is added as a member of all parent loops, and is added
236  /// to the specified LoopInfo object as being in the current basic block.  It
237  /// is not valid to replace the loop header with this method.
238  ///
239  void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
240
241  /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
242  /// the OldChild entry in our children list with NewChild, and updates the
243  /// parent pointer of OldChild to be null and the NewChild to be this loop.
244  /// This updates the loop depth of the new child.
245  void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
246
247  /// addChildLoop - Add the specified loop to be a child of this loop.  This
248  /// updates the loop depth of the new child.
249  ///
250  void addChildLoop(LoopT *NewChild) {
251    assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
252    NewChild->ParentLoop = static_cast<LoopT *>(this);
253    SubLoops.push_back(NewChild);
254  }
255
256  /// removeChildLoop - This removes the specified child from being a subloop of
257  /// this loop.  The loop is not deleted, as it will presumably be inserted
258  /// into another loop.
259  LoopT *removeChildLoop(iterator I) {
260    assert(I != SubLoops.end() && "Cannot remove end iterator!");
261    LoopT *Child = *I;
262    assert(Child->ParentLoop == this && "Child is not a child of this loop!");
263    SubLoops.erase(SubLoops.begin()+(I-begin()));
264    Child->ParentLoop = 0;
265    return Child;
266  }
267
268  /// addBlockEntry - This adds a basic block directly to the basic block list.
269  /// This should only be used by transformations that create new loops.  Other
270  /// transformations should use addBasicBlockToLoop.
271  void addBlockEntry(BlockT *BB) {
272    Blocks.push_back(BB);
273  }
274
275  /// moveToHeader - This method is used to move BB (which must be part of this
276  /// loop) to be the loop header of the loop (the block that dominates all
277  /// others).
278  void moveToHeader(BlockT *BB) {
279    if (Blocks[0] == BB) return;
280    for (unsigned i = 0; ; ++i) {
281      assert(i != Blocks.size() && "Loop does not contain BB!");
282      if (Blocks[i] == BB) {
283        Blocks[i] = Blocks[0];
284        Blocks[0] = BB;
285        return;
286      }
287    }
288  }
289
290  /// removeBlockFromLoop - This removes the specified basic block from the
291  /// current loop, updating the Blocks as appropriate.  This does not update
292  /// the mapping in the LoopInfo class.
293  void removeBlockFromLoop(BlockT *BB) {
294    RemoveFromVector(Blocks, BB);
295  }
296
297  /// verifyLoop - Verify loop structure
298  void verifyLoop() const;
299
300  /// verifyLoop - Verify loop structure of this loop and all nested loops.
301  void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
302
303  void print(raw_ostream &OS, unsigned Depth = 0) const;
304
305protected:
306  friend class LoopInfoBase<BlockT, LoopT>;
307  explicit LoopBase(BlockT *BB) : ParentLoop(0) {
308    Blocks.push_back(BB);
309  }
310};
311
312template<class BlockT, class LoopT>
313raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
314  Loop.print(OS);
315  return OS;
316}
317
318// Implementation in LoopInfoImpl.h
319#ifdef __GNUC__
320__extension__ extern template class LoopBase<BasicBlock, Loop>;
321#endif
322
323class Loop : public LoopBase<BasicBlock, Loop> {
324public:
325  Loop() {}
326
327  /// isLoopInvariant - Return true if the specified value is loop invariant
328  ///
329  bool isLoopInvariant(Value *V) const;
330
331  /// hasLoopInvariantOperands - Return true if all the operands of the
332  /// specified instruction are loop invariant.
333  bool hasLoopInvariantOperands(Instruction *I) const;
334
335  /// makeLoopInvariant - If the given value is an instruction inside of the
336  /// loop and it can be hoisted, do so to make it trivially loop-invariant.
337  /// Return true if the value after any hoisting is loop invariant. This
338  /// function can be used as a slightly more aggressive replacement for
339  /// isLoopInvariant.
340  ///
341  /// If InsertPt is specified, it is the point to hoist instructions to.
342  /// If null, the terminator of the loop preheader is used.
343  ///
344  bool makeLoopInvariant(Value *V, bool &Changed,
345                         Instruction *InsertPt = 0) const;
346
347  /// makeLoopInvariant - If the given instruction is inside of the
348  /// loop and it can be hoisted, do so to make it trivially loop-invariant.
349  /// Return true if the instruction after any hoisting is loop invariant. This
350  /// function can be used as a slightly more aggressive replacement for
351  /// isLoopInvariant.
352  ///
353  /// If InsertPt is specified, it is the point to hoist instructions to.
354  /// If null, the terminator of the loop preheader is used.
355  ///
356  bool makeLoopInvariant(Instruction *I, bool &Changed,
357                         Instruction *InsertPt = 0) const;
358
359  /// getCanonicalInductionVariable - Check to see if the loop has a canonical
360  /// induction variable: an integer recurrence that starts at 0 and increments
361  /// by one each time through the loop.  If so, return the phi node that
362  /// corresponds to it.
363  ///
364  /// The IndVarSimplify pass transforms loops to have a canonical induction
365  /// variable.
366  ///
367  PHINode *getCanonicalInductionVariable() const;
368
369  /// isLCSSAForm - Return true if the Loop is in LCSSA form
370  bool isLCSSAForm(DominatorTree &DT) const;
371
372  /// isLoopSimplifyForm - Return true if the Loop is in the form that
373  /// the LoopSimplify form transforms loops to, which is sometimes called
374  /// normal form.
375  bool isLoopSimplifyForm() const;
376
377  /// isSafeToClone - Return true if the loop body is safe to clone in practice.
378  bool isSafeToClone() const;
379
380  /// hasDedicatedExits - Return true if no exit block for the loop
381  /// has a predecessor that is outside the loop.
382  bool hasDedicatedExits() const;
383
384  /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
385  /// These are the blocks _outside of the current loop_ which are branched to.
386  /// This assumes that loop exits are in canonical form.
387  ///
388  void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
389
390  /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
391  /// block, return that block. Otherwise return null.
392  BasicBlock *getUniqueExitBlock() const;
393
394  void dump() const;
395
396private:
397  friend class LoopInfoBase<BasicBlock, Loop>;
398  explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
399};
400
401//===----------------------------------------------------------------------===//
402/// LoopInfo - This class builds and contains all of the top level loop
403/// structures in the specified function.
404///
405
406template<class BlockT, class LoopT>
407class LoopInfoBase {
408  // BBMap - Mapping of basic blocks to the inner most loop they occur in
409  DenseMap<BlockT *, LoopT *> BBMap;
410  std::vector<LoopT *> TopLevelLoops;
411  friend class LoopBase<BlockT, LoopT>;
412  friend class LoopInfo;
413
414  void operator=(const LoopInfoBase &) LLVM_DELETED_FUNCTION;
415  LoopInfoBase(const LoopInfo &) LLVM_DELETED_FUNCTION;
416public:
417  LoopInfoBase() { }
418  ~LoopInfoBase() { releaseMemory(); }
419
420  void releaseMemory() {
421    for (typename std::vector<LoopT *>::iterator I =
422         TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
423      delete *I;   // Delete all of the loops...
424
425    BBMap.clear();                           // Reset internal state of analysis
426    TopLevelLoops.clear();
427  }
428
429  /// iterator/begin/end - The interface to the top-level loops in the current
430  /// function.
431  ///
432  typedef typename std::vector<LoopT *>::const_iterator iterator;
433  typedef typename std::vector<LoopT *>::const_reverse_iterator
434    reverse_iterator;
435  iterator begin() const { return TopLevelLoops.begin(); }
436  iterator end() const { return TopLevelLoops.end(); }
437  reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
438  reverse_iterator rend() const { return TopLevelLoops.rend(); }
439  bool empty() const { return TopLevelLoops.empty(); }
440
441  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
442  /// block is in no loop (for example the entry node), null is returned.
443  ///
444  LoopT *getLoopFor(const BlockT *BB) const {
445    return BBMap.lookup(const_cast<BlockT*>(BB));
446  }
447
448  /// operator[] - same as getLoopFor...
449  ///
450  const LoopT *operator[](const BlockT *BB) const {
451    return getLoopFor(BB);
452  }
453
454  /// getLoopDepth - Return the loop nesting level of the specified block.  A
455  /// depth of 0 means the block is not inside any loop.
456  ///
457  unsigned getLoopDepth(const BlockT *BB) const {
458    const LoopT *L = getLoopFor(BB);
459    return L ? L->getLoopDepth() : 0;
460  }
461
462  // isLoopHeader - True if the block is a loop header node
463  bool isLoopHeader(BlockT *BB) const {
464    const LoopT *L = getLoopFor(BB);
465    return L && L->getHeader() == BB;
466  }
467
468  /// removeLoop - This removes the specified top-level loop from this loop info
469  /// object.  The loop is not deleted, as it will presumably be inserted into
470  /// another loop.
471  LoopT *removeLoop(iterator I) {
472    assert(I != end() && "Cannot remove end iterator!");
473    LoopT *L = *I;
474    assert(L->getParentLoop() == 0 && "Not a top-level loop!");
475    TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
476    return L;
477  }
478
479  /// changeLoopFor - Change the top-level loop that contains BB to the
480  /// specified loop.  This should be used by transformations that restructure
481  /// the loop hierarchy tree.
482  void changeLoopFor(BlockT *BB, LoopT *L) {
483    if (!L) {
484      BBMap.erase(BB);
485      return;
486    }
487    BBMap[BB] = L;
488  }
489
490  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
491  /// list with the indicated loop.
492  void changeTopLevelLoop(LoopT *OldLoop,
493                          LoopT *NewLoop) {
494    typename std::vector<LoopT *>::iterator I =
495                 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
496    assert(I != TopLevelLoops.end() && "Old loop not at top level!");
497    *I = NewLoop;
498    assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
499           "Loops already embedded into a subloop!");
500  }
501
502  /// addTopLevelLoop - This adds the specified loop to the collection of
503  /// top-level loops.
504  void addTopLevelLoop(LoopT *New) {
505    assert(New->getParentLoop() == 0 && "Loop already in subloop!");
506    TopLevelLoops.push_back(New);
507  }
508
509  /// removeBlock - This method completely removes BB from all data structures,
510  /// including all of the Loop objects it is nested in and our mapping from
511  /// BasicBlocks to loops.
512  void removeBlock(BlockT *BB) {
513    typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
514    if (I != BBMap.end()) {
515      for (LoopT *L = I->second; L; L = L->getParentLoop())
516        L->removeBlockFromLoop(BB);
517
518      BBMap.erase(I);
519    }
520  }
521
522  // Internals
523
524  static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
525                                      const LoopT *ParentLoop) {
526    if (SubLoop == 0) return true;
527    if (SubLoop == ParentLoop) return false;
528    return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
529  }
530
531  /// Create the loop forest using a stable algorithm.
532  void Analyze(DominatorTreeBase<BlockT> &DomTree);
533
534  // Debugging
535
536  void print(raw_ostream &OS) const;
537};
538
539// Implementation in LoopInfoImpl.h
540#ifdef __GNUC__
541__extension__ extern template class LoopInfoBase<BasicBlock, Loop>;
542#endif
543
544class LoopInfo : public FunctionPass {
545  LoopInfoBase<BasicBlock, Loop> LI;
546  friend class LoopBase<BasicBlock, Loop>;
547
548  void operator=(const LoopInfo &) LLVM_DELETED_FUNCTION;
549  LoopInfo(const LoopInfo &) LLVM_DELETED_FUNCTION;
550public:
551  static char ID; // Pass identification, replacement for typeid
552
553  LoopInfo() : FunctionPass(ID) {
554    initializeLoopInfoPass(*PassRegistry::getPassRegistry());
555  }
556
557  LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
558
559  /// iterator/begin/end - The interface to the top-level loops in the current
560  /// function.
561  ///
562  typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
563  typedef LoopInfoBase<BasicBlock, Loop>::reverse_iterator reverse_iterator;
564  inline iterator begin() const { return LI.begin(); }
565  inline iterator end() const { return LI.end(); }
566  inline reverse_iterator rbegin() const { return LI.rbegin(); }
567  inline reverse_iterator rend() const { return LI.rend(); }
568  bool empty() const { return LI.empty(); }
569
570  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
571  /// block is in no loop (for example the entry node), null is returned.
572  ///
573  inline Loop *getLoopFor(const BasicBlock *BB) const {
574    return LI.getLoopFor(BB);
575  }
576
577  /// operator[] - same as getLoopFor...
578  ///
579  inline const Loop *operator[](const BasicBlock *BB) const {
580    return LI.getLoopFor(BB);
581  }
582
583  /// getLoopDepth - Return the loop nesting level of the specified block.  A
584  /// depth of 0 means the block is not inside any loop.
585  ///
586  inline unsigned getLoopDepth(const BasicBlock *BB) const {
587    return LI.getLoopDepth(BB);
588  }
589
590  // isLoopHeader - True if the block is a loop header node
591  inline bool isLoopHeader(BasicBlock *BB) const {
592    return LI.isLoopHeader(BB);
593  }
594
595  /// runOnFunction - Calculate the natural loop information.
596  ///
597  virtual bool runOnFunction(Function &F);
598
599  virtual void verifyAnalysis() const;
600
601  virtual void releaseMemory() { LI.releaseMemory(); }
602
603  virtual void print(raw_ostream &O, const Module* M = 0) const;
604
605  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
606
607  /// removeLoop - This removes the specified top-level loop from this loop info
608  /// object.  The loop is not deleted, as it will presumably be inserted into
609  /// another loop.
610  inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
611
612  /// changeLoopFor - Change the top-level loop that contains BB to the
613  /// specified loop.  This should be used by transformations that restructure
614  /// the loop hierarchy tree.
615  inline void changeLoopFor(BasicBlock *BB, Loop *L) {
616    LI.changeLoopFor(BB, L);
617  }
618
619  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
620  /// list with the indicated loop.
621  inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
622    LI.changeTopLevelLoop(OldLoop, NewLoop);
623  }
624
625  /// addTopLevelLoop - This adds the specified loop to the collection of
626  /// top-level loops.
627  inline void addTopLevelLoop(Loop *New) {
628    LI.addTopLevelLoop(New);
629  }
630
631  /// removeBlock - This method completely removes BB from all data structures,
632  /// including all of the Loop objects it is nested in and our mapping from
633  /// BasicBlocks to loops.
634  void removeBlock(BasicBlock *BB) {
635    LI.removeBlock(BB);
636  }
637
638  /// updateUnloop - Update LoopInfo after removing the last backedge from a
639  /// loop--now the "unloop". This updates the loop forest and parent loops for
640  /// each block so that Unloop is no longer referenced, but the caller must
641  /// actually delete the Unloop object.
642  void updateUnloop(Loop *Unloop);
643
644  /// replacementPreservesLCSSAForm - Returns true if replacing From with To
645  /// everywhere is guaranteed to preserve LCSSA form.
646  bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
647    // Preserving LCSSA form is only problematic if the replacing value is an
648    // instruction.
649    Instruction *I = dyn_cast<Instruction>(To);
650    if (!I) return true;
651    // If both instructions are defined in the same basic block then replacement
652    // cannot break LCSSA form.
653    if (I->getParent() == From->getParent())
654      return true;
655    // If the instruction is not defined in a loop then it can safely replace
656    // anything.
657    Loop *ToLoop = getLoopFor(I->getParent());
658    if (!ToLoop) return true;
659    // If the replacing instruction is defined in the same loop as the original
660    // instruction, or in a loop that contains it as an inner loop, then using
661    // it as a replacement will not break LCSSA form.
662    return ToLoop->contains(getLoopFor(From->getParent()));
663  }
664};
665
666
667// Allow clients to walk the list of nested loops...
668template <> struct GraphTraits<const Loop*> {
669  typedef const Loop NodeType;
670  typedef LoopInfo::iterator ChildIteratorType;
671
672  static NodeType *getEntryNode(const Loop *L) { return L; }
673  static inline ChildIteratorType child_begin(NodeType *N) {
674    return N->begin();
675  }
676  static inline ChildIteratorType child_end(NodeType *N) {
677    return N->end();
678  }
679};
680
681template <> struct GraphTraits<Loop*> {
682  typedef Loop NodeType;
683  typedef LoopInfo::iterator ChildIteratorType;
684
685  static NodeType *getEntryNode(Loop *L) { return L; }
686  static inline ChildIteratorType child_begin(NodeType *N) {
687    return N->begin();
688  }
689  static inline ChildIteratorType child_end(NodeType *N) {
690    return N->end();
691  }
692};
693
694} // End llvm namespace
695
696#endif
697