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