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