ac0a4b02f4458bb027a0413faea7eeacd198f1f6
[oota-llvm.git] / include / llvm / Analysis / LoopInfo.h
1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the LoopInfo class that is used to identify natural loops
11 // and determine the loop depth of various nodes of the CFG.  A natural loop
12 // has exactly one entry-point, which is called the header. Note that natural
13 // loops may actually be several loops that share the same header node.
14 //
15 // This analysis calculates the nesting structure of loops in a function.  For
16 // each natural loop identified, this analysis identifies natural loops
17 // contained entirely within the loop and the basic blocks the make up the loop.
18 //
19 // It can calculate on the fly various bits of information, for example:
20 //
21 //  * whether there is a preheader for the loop
22 //  * the number of back edges to the header
23 //  * whether or not a particular block branches out of the loop
24 //  * the successor blocks of the loop
25 //  * the loop depth
26 //  * 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/SmallPtrSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/Pass.h"
41 #include <algorithm>
42
43 namespace llvm {
44
45 // FIXME: Replace this brittle forward declaration with the include of the new
46 // PassManager.h when doing so doesn't break the PassManagerBuilder.
47 template <typename IRUnitT> class AnalysisManager;
48 class PreservedAnalyses;
49
50 class DominatorTree;
51 class LoopInfo;
52 class Loop;
53 class MDNode;
54 class PHINode;
55 class raw_ostream;
56 template<class N> class DominatorTreeBase;
57 template<class N, class M> class LoopInfoBase;
58 template<class N, class M> class LoopBase;
59
60 //===----------------------------------------------------------------------===//
61 /// LoopBase class - Instances of this class are used to represent loops that
62 /// are detected in the flow graph
63 ///
64 template<class BlockT, class LoopT>
65 class LoopBase {
66   LoopT *ParentLoop;
67   // SubLoops - Loops contained entirely within this one.
68   std::vector<LoopT *> SubLoops;
69
70   // Blocks - The list of blocks in this loop.  First entry is the header node.
71   std::vector<BlockT*> Blocks;
72
73   SmallPtrSet<const BlockT*, 8> DenseBlockSet;
74
75   LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
76   const LoopBase<BlockT, LoopT>&
77     operator=(const LoopBase<BlockT, LoopT> &) = delete;
78 public:
79   /// Loop ctor - This creates an empty loop.
80   LoopBase() : ParentLoop(nullptr) {}
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)        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 DenseBlockSet.count(BB);
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   typedef typename std::vector<BlockT*>::const_iterator block_iterator;
141   block_iterator block_begin() const { return Blocks.begin(); }
142   block_iterator block_end() const { return Blocks.end(); }
143   inline iterator_range<block_iterator> blocks() const {
144     return iterator_range<block_iterator>(block_begin(), block_end());
145   }
146
147   /// getNumBlocks - Get the number of blocks in this loop in constant time.
148   unsigned getNumBlocks() const {
149     return Blocks.size();
150   }
151
152   /// isLoopExiting - True if terminator in the block can branch to another
153   /// block that is outside of the current loop.
154   ///
155   bool isLoopExiting(const BlockT *BB) const {
156     typedef GraphTraits<const BlockT*> BlockTraits;
157     for (typename BlockTraits::ChildIteratorType SI =
158          BlockTraits::child_begin(BB),
159          SE = BlockTraits::child_end(BB); SI != SE; ++SI) {
160       if (!contains(*SI))
161         return true;
162     }
163     return false;
164   }
165
166   /// getNumBackEdges - Calculate the number of back edges to the loop header
167   ///
168   unsigned getNumBackEdges() const {
169     unsigned NumBackEdges = 0;
170     BlockT *H = getHeader();
171
172     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
173     for (typename InvBlockTraits::ChildIteratorType I =
174          InvBlockTraits::child_begin(H),
175          E = InvBlockTraits::child_end(H); I != E; ++I)
176       if (contains(*I))
177         ++NumBackEdges;
178
179     return NumBackEdges;
180   }
181
182   //===--------------------------------------------------------------------===//
183   // APIs for simple analysis of the loop.
184   //
185   // Note that all of these methods can fail on general loops (ie, there may not
186   // be a preheader, etc).  For best success, the loop simplification and
187   // induction variable canonicalization pass should be used to normalize loops
188   // for easy analysis.  These methods assume canonical loops.
189
190   /// getExitingBlocks - Return all blocks inside the loop that have successors
191   /// outside of the loop.  These are the blocks _inside of the current loop_
192   /// which branch out.  The returned list is always unique.
193   ///
194   void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
195
196   /// getExitingBlock - If getExitingBlocks would return exactly one block,
197   /// return that block. Otherwise return null.
198   BlockT *getExitingBlock() const;
199
200   /// getExitBlocks - Return all of the successor blocks of this loop.  These
201   /// are the blocks _outside of the current loop_ which are branched to.
202   ///
203   void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
204
205   /// getExitBlock - If getExitBlocks would return exactly one block,
206   /// return that block. Otherwise return null.
207   BlockT *getExitBlock() const;
208
209   /// Edge type.
210   typedef std::pair<const BlockT*, const BlockT*> Edge;
211
212   /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
213   void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
214
215   /// getLoopPreheader - If there is a preheader for this loop, return it.  A
216   /// loop has a preheader if there is only one edge to the header of the loop
217   /// from outside of the loop.  If this is the case, the block branching to the
218   /// header of the loop is the preheader node.
219   ///
220   /// This method returns null if there is no preheader for the loop.
221   ///
222   BlockT *getLoopPreheader() const;
223
224   /// getLoopPredecessor - If the given loop's header has exactly one unique
225   /// predecessor outside the loop, return it. Otherwise return null.
226   /// This is less strict that the loop "preheader" concept, which requires
227   /// the predecessor to have exactly one successor.
228   ///
229   BlockT *getLoopPredecessor() const;
230
231   /// getLoopLatch - If there is a single latch block for this loop, return it.
232   /// A latch block is a block that contains a branch back to the header.
233   BlockT *getLoopLatch() const;
234
235   /// getLoopLatches - Return all loop latch blocks of this loop. A latch block
236   /// is a block that contains a branch back to the header.
237   void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
238     BlockT *H = getHeader();
239     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
240     for (typename InvBlockTraits::ChildIteratorType I =
241          InvBlockTraits::child_begin(H),
242          E = InvBlockTraits::child_end(H); I != E; ++I)
243       if (contains(*I))
244         LoopLatches.push_back(*I);
245   }
246
247   //===--------------------------------------------------------------------===//
248   // APIs for updating loop information after changing the CFG
249   //
250
251   /// addBasicBlockToLoop - This method is used by other analyses to update loop
252   /// information.  NewBB is set to be a new member of the current loop.
253   /// Because of this, it is added as a member of all parent loops, and is added
254   /// to the specified LoopInfo object as being in the current basic block.  It
255   /// is not valid to replace the loop header with this method.
256   ///
257   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
258
259   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
260   /// the OldChild entry in our children list with NewChild, and updates the
261   /// parent pointer of OldChild to be null and the NewChild to be this loop.
262   /// This updates the loop depth of the new child.
263   void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
264
265   /// addChildLoop - Add the specified loop to be a child of this loop.  This
266   /// updates the loop depth of the new child.
267   ///
268   void addChildLoop(LoopT *NewChild) {
269     assert(!NewChild->ParentLoop && "NewChild already has a parent!");
270     NewChild->ParentLoop = static_cast<LoopT *>(this);
271     SubLoops.push_back(NewChild);
272   }
273
274   /// removeChildLoop - This removes the specified child from being a subloop of
275   /// this loop.  The loop is not deleted, as it will presumably be inserted
276   /// into another loop.
277   LoopT *removeChildLoop(iterator I) {
278     assert(I != SubLoops.end() && "Cannot remove end iterator!");
279     LoopT *Child = *I;
280     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
281     SubLoops.erase(SubLoops.begin()+(I-begin()));
282     Child->ParentLoop = nullptr;
283     return Child;
284   }
285
286   /// addBlockEntry - This adds a basic block directly to the basic block list.
287   /// This should only be used by transformations that create new loops.  Other
288   /// transformations should use addBasicBlockToLoop.
289   void addBlockEntry(BlockT *BB) {
290     Blocks.push_back(BB);
291     DenseBlockSet.insert(BB);
292   }
293
294   /// reverseBlocks - interface to reverse Blocks[from, end of loop] in this loop
295   void reverseBlock(unsigned from) {
296     std::reverse(Blocks.begin() + from, Blocks.end());
297   }
298
299   /// reserveBlocks- interface to do reserve() for Blocks
300   void reserveBlocks(unsigned size) {
301     Blocks.reserve(size);
302   }
303
304   /// moveToHeader - This method is used to move BB (which must be part of this
305   /// loop) to be the loop header of the loop (the block that dominates all
306   /// others).
307   void moveToHeader(BlockT *BB) {
308     if (Blocks[0] == BB) return;
309     for (unsigned i = 0; ; ++i) {
310       assert(i != Blocks.size() && "Loop does not contain BB!");
311       if (Blocks[i] == BB) {
312         Blocks[i] = Blocks[0];
313         Blocks[0] = BB;
314         return;
315       }
316     }
317   }
318
319   /// removeBlockFromLoop - This removes the specified basic block from the
320   /// current loop, updating the Blocks as appropriate.  This does not update
321   /// the mapping in the LoopInfo class.
322   void removeBlockFromLoop(BlockT *BB) {
323     auto I = std::find(Blocks.begin(), Blocks.end(), BB);
324     assert(I != Blocks.end() && "N is not in this list!");
325     Blocks.erase(I);
326
327     DenseBlockSet.erase(BB);
328   }
329
330   /// verifyLoop - Verify loop structure
331   void verifyLoop() const;
332
333   /// verifyLoop - Verify loop structure of this loop and all nested loops.
334   void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
335
336   void print(raw_ostream &OS, unsigned Depth = 0) const;
337
338 protected:
339   friend class LoopInfoBase<BlockT, LoopT>;
340   explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
341     Blocks.push_back(BB);
342     DenseBlockSet.insert(BB);
343   }
344 };
345
346 template<class BlockT, class LoopT>
347 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
348   Loop.print(OS);
349   return OS;
350 }
351
352 // Implementation in LoopInfoImpl.h
353 extern template class LoopBase<BasicBlock, Loop>;
354
355 class Loop : public LoopBase<BasicBlock, Loop> {
356 public:
357   Loop() {}
358
359   /// isLoopInvariant - Return true if the specified value is loop invariant
360   ///
361   bool isLoopInvariant(const Value *V) const;
362
363   /// hasLoopInvariantOperands - Return true if all the operands of the
364   /// specified instruction are loop invariant.
365   bool hasLoopInvariantOperands(const Instruction *I) const;
366
367   /// makeLoopInvariant - If the given value is an instruction inside of the
368   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
369   /// Return true if the value after any hoisting is loop invariant. This
370   /// function can be used as a slightly more aggressive replacement for
371   /// isLoopInvariant.
372   ///
373   /// If InsertPt is specified, it is the point to hoist instructions to.
374   /// If null, the terminator of the loop preheader is used.
375   ///
376   bool makeLoopInvariant(Value *V, bool &Changed,
377                          Instruction *InsertPt = nullptr) const;
378
379   /// makeLoopInvariant - If the given instruction is inside of the
380   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
381   /// Return true if the instruction after any hoisting is loop invariant. This
382   /// function can be used as a slightly more aggressive replacement for
383   /// isLoopInvariant.
384   ///
385   /// If InsertPt is specified, it is the point to hoist instructions to.
386   /// If null, the terminator of the loop preheader is used.
387   ///
388   bool makeLoopInvariant(Instruction *I, bool &Changed,
389                          Instruction *InsertPt = nullptr) const;
390
391   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
392   /// induction variable: an integer recurrence that starts at 0 and increments
393   /// by one each time through the loop.  If so, return the phi node that
394   /// corresponds to it.
395   ///
396   /// The IndVarSimplify pass transforms loops to have a canonical induction
397   /// variable.
398   ///
399   PHINode *getCanonicalInductionVariable() const;
400
401   /// isLCSSAForm - Return true if the Loop is in LCSSA form
402   bool isLCSSAForm(DominatorTree &DT) const;
403
404   /// isLoopSimplifyForm - Return true if the Loop is in the form that
405   /// the LoopSimplify form transforms loops to, which is sometimes called
406   /// normal form.
407   bool isLoopSimplifyForm() const;
408
409   /// isSafeToClone - Return true if the loop body is safe to clone in practice.
410   bool isSafeToClone() const;
411
412   /// Returns true if the loop is annotated parallel.
413   ///
414   /// A parallel loop can be assumed to not contain any dependencies between
415   /// iterations by the compiler. That is, any loop-carried dependency checking
416   /// can be skipped completely when parallelizing the loop on the target
417   /// machine. Thus, if the parallel loop information originates from the
418   /// programmer, e.g. via the OpenMP parallel for pragma, it is the
419   /// programmer's responsibility to ensure there are no loop-carried
420   /// dependencies. The final execution order of the instructions across
421   /// iterations is not guaranteed, thus, the end result might or might not
422   /// implement actual concurrent execution of instructions across multiple
423   /// iterations.
424   bool isAnnotatedParallel() const;
425
426   /// Return the llvm.loop loop id metadata node for this loop if it is present.
427   ///
428   /// If this loop contains the same llvm.loop metadata on each branch to the
429   /// header then the node is returned. If any latch instruction does not
430   /// contain llvm.loop or or if multiple latches contain different nodes then
431   /// 0 is returned.
432   MDNode *getLoopID() const;
433   /// Set the llvm.loop loop id metadata for this loop.
434   ///
435   /// The LoopID metadata node will be added to each terminator instruction in
436   /// the loop that branches to the loop header.
437   ///
438   /// The LoopID metadata node should have one or more operands and the first
439   /// operand should should be the node itself.
440   void setLoopID(MDNode *LoopID) const;
441
442   /// hasDedicatedExits - Return true if no exit block for the loop
443   /// has a predecessor that is outside the loop.
444   bool hasDedicatedExits() const;
445
446   /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
447   /// These are the blocks _outside of the current loop_ which are branched to.
448   /// This assumes that loop exits are in canonical form.
449   ///
450   void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
451
452   /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
453   /// block, return that block. Otherwise return null.
454   BasicBlock *getUniqueExitBlock() const;
455
456   void dump() const;
457
458   /// \brief Return the debug location of the start of this loop.
459   /// This looks for a BB terminating instruction with a known debug
460   /// location by looking at the preheader and header blocks. If it
461   /// cannot find a terminating instruction with location information,
462   /// it returns an unknown location.
463   DebugLoc getStartLoc() const {
464     BasicBlock *HeadBB;
465
466     // Try the pre-header first.
467     if ((HeadBB = getLoopPreheader()) != nullptr)
468       if (DebugLoc DL = HeadBB->getTerminator()->getDebugLoc())
469         return DL;
470
471     // If we have no pre-header or there are no instructions with debug
472     // info in it, try the header.
473     HeadBB = getHeader();
474     if (HeadBB)
475       return HeadBB->getTerminator()->getDebugLoc();
476
477     return DebugLoc();
478   }
479
480 private:
481   friend class LoopInfoBase<BasicBlock, Loop>;
482   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
483 };
484
485 //===----------------------------------------------------------------------===//
486 /// LoopInfo - This class builds and contains all of the top level loop
487 /// structures in the specified function.
488 ///
489
490 template<class BlockT, class LoopT>
491 class LoopInfoBase {
492   // BBMap - Mapping of basic blocks to the inner most loop they occur in
493   DenseMap<const BlockT *, LoopT *> BBMap;
494   std::vector<LoopT *> TopLevelLoops;
495   friend class LoopBase<BlockT, LoopT>;
496   friend class LoopInfo;
497
498   void operator=(const LoopInfoBase &) = delete;
499   LoopInfoBase(const LoopInfoBase &) = delete;
500 public:
501   LoopInfoBase() { }
502   ~LoopInfoBase() { releaseMemory(); }
503
504   LoopInfoBase(LoopInfoBase &&Arg)
505       : BBMap(std::move(Arg.BBMap)),
506         TopLevelLoops(std::move(Arg.TopLevelLoops)) {
507     // We have to clear the arguments top level loops as we've taken ownership.
508     Arg.TopLevelLoops.clear();
509   }
510   LoopInfoBase &operator=(LoopInfoBase &&RHS) {
511     BBMap = std::move(RHS.BBMap);
512
513     for (auto *L : TopLevelLoops)
514       delete L;
515     TopLevelLoops = std::move(RHS.TopLevelLoops);
516     RHS.TopLevelLoops.clear();
517     return *this;
518   }
519
520   void releaseMemory() {
521     BBMap.clear();
522
523     for (auto *L : TopLevelLoops)
524       delete L;
525     TopLevelLoops.clear();
526   }
527
528   /// iterator/begin/end - The interface to the top-level loops in the current
529   /// function.
530   ///
531   typedef typename std::vector<LoopT *>::const_iterator iterator;
532   typedef typename std::vector<LoopT *>::const_reverse_iterator
533     reverse_iterator;
534   iterator begin() const { return TopLevelLoops.begin(); }
535   iterator end() const { return TopLevelLoops.end(); }
536   reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
537   reverse_iterator rend() const { return TopLevelLoops.rend(); }
538   bool empty() const { return TopLevelLoops.empty(); }
539
540   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
541   /// block is in no loop (for example the entry node), null is returned.
542   ///
543   LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
544
545   /// operator[] - same as getLoopFor...
546   ///
547   const LoopT *operator[](const BlockT *BB) const {
548     return getLoopFor(BB);
549   }
550
551   /// getLoopDepth - Return the loop nesting level of the specified block.  A
552   /// depth of 0 means the block is not inside any loop.
553   ///
554   unsigned getLoopDepth(const BlockT *BB) const {
555     const LoopT *L = getLoopFor(BB);
556     return L ? L->getLoopDepth() : 0;
557   }
558
559   // isLoopHeader - True if the block is a loop header node
560   bool isLoopHeader(const BlockT *BB) const {
561     const LoopT *L = getLoopFor(BB);
562     return L && L->getHeader() == BB;
563   }
564
565   /// removeLoop - This removes the specified top-level loop from this loop info
566   /// object.  The loop is not deleted, as it will presumably be inserted into
567   /// another loop.
568   LoopT *removeLoop(iterator I) {
569     assert(I != end() && "Cannot remove end iterator!");
570     LoopT *L = *I;
571     assert(!L->getParentLoop() && "Not a top-level loop!");
572     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
573     return L;
574   }
575
576   /// changeLoopFor - Change the top-level loop that contains BB to the
577   /// specified loop.  This should be used by transformations that restructure
578   /// the loop hierarchy tree.
579   void changeLoopFor(BlockT *BB, LoopT *L) {
580     if (!L) {
581       BBMap.erase(BB);
582       return;
583     }
584     BBMap[BB] = L;
585   }
586
587   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
588   /// list with the indicated loop.
589   void changeTopLevelLoop(LoopT *OldLoop,
590                           LoopT *NewLoop) {
591     auto I = std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
592     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
593     *I = NewLoop;
594     assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
595            "Loops already embedded into a subloop!");
596   }
597
598   /// addTopLevelLoop - This adds the specified loop to the collection of
599   /// top-level loops.
600   void addTopLevelLoop(LoopT *New) {
601     assert(!New->getParentLoop() && "Loop already in subloop!");
602     TopLevelLoops.push_back(New);
603   }
604
605   /// removeBlock - This method completely removes BB from all data structures,
606   /// including all of the Loop objects it is nested in and our mapping from
607   /// BasicBlocks to loops.
608   void removeBlock(BlockT *BB) {
609     auto I = BBMap.find(BB);
610     if (I != BBMap.end()) {
611       for (LoopT *L = I->second; L; L = L->getParentLoop())
612         L->removeBlockFromLoop(BB);
613
614       BBMap.erase(I);
615     }
616   }
617
618   // Internals
619
620   static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
621                                       const LoopT *ParentLoop) {
622     if (!SubLoop) return true;
623     if (SubLoop == ParentLoop) return false;
624     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
625   }
626
627   /// Create the loop forest using a stable algorithm.
628   void analyze(const DominatorTreeBase<BlockT> &DomTree);
629
630   // Debugging
631   void print(raw_ostream &OS) const;
632
633   void verify() const;
634 };
635
636 // Implementation in LoopInfoImpl.h
637 extern template class LoopInfoBase<BasicBlock, Loop>;
638
639 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
640   typedef LoopInfoBase<BasicBlock, Loop> BaseT;
641
642   friend class LoopBase<BasicBlock, Loop>;
643
644   void operator=(const LoopInfo &) = delete;
645   LoopInfo(const LoopInfo &) = delete;
646 public:
647   LoopInfo() {}
648   explicit LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree);
649
650   LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
651   LoopInfo &operator=(LoopInfo &&RHS) {
652     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
653     return *this;
654   }
655
656   // Most of the public interface is provided via LoopInfoBase.
657
658   /// updateUnloop - Update LoopInfo after removing the last backedge from a
659   /// loop--now the "unloop". This updates the loop forest and parent loops for
660   /// each block so that Unloop is no longer referenced, but the caller must
661   /// actually delete the Unloop object.
662   void updateUnloop(Loop *Unloop);
663
664   /// replacementPreservesLCSSAForm - Returns true if replacing From with To
665   /// everywhere is guaranteed to preserve LCSSA form.
666   bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
667     // Preserving LCSSA form is only problematic if the replacing value is an
668     // instruction.
669     Instruction *I = dyn_cast<Instruction>(To);
670     if (!I) return true;
671     // If both instructions are defined in the same basic block then replacement
672     // cannot break LCSSA form.
673     if (I->getParent() == From->getParent())
674       return true;
675     // If the instruction is not defined in a loop then it can safely replace
676     // anything.
677     Loop *ToLoop = getLoopFor(I->getParent());
678     if (!ToLoop) return true;
679     // If the replacing instruction is defined in the same loop as the original
680     // instruction, or in a loop that contains it as an inner loop, then using
681     // it as a replacement will not break LCSSA form.
682     return ToLoop->contains(getLoopFor(From->getParent()));
683   }
684 };
685
686 // Allow clients to walk the list of nested loops...
687 template <> struct GraphTraits<const Loop*> {
688   typedef const Loop NodeType;
689   typedef LoopInfo::iterator ChildIteratorType;
690
691   static NodeType *getEntryNode(const Loop *L) { return L; }
692   static inline ChildIteratorType child_begin(NodeType *N) {
693     return N->begin();
694   }
695   static inline ChildIteratorType child_end(NodeType *N) {
696     return N->end();
697   }
698 };
699
700 template <> struct GraphTraits<Loop*> {
701   typedef Loop NodeType;
702   typedef LoopInfo::iterator ChildIteratorType;
703
704   static NodeType *getEntryNode(Loop *L) { return L; }
705   static inline ChildIteratorType child_begin(NodeType *N) {
706     return N->begin();
707   }
708   static inline ChildIteratorType child_end(NodeType *N) {
709     return N->end();
710   }
711 };
712
713 /// \brief Analysis pass that exposes the \c LoopInfo for a function.
714 class LoopAnalysis {
715   static char PassID;
716
717 public:
718   typedef LoopInfo Result;
719
720   /// \brief Opaque, unique identifier for this analysis pass.
721   static void *ID() { return (void *)&PassID; }
722
723   /// \brief Provide a name for the analysis for debugging and logging.
724   static StringRef name() { return "LoopAnalysis"; }
725
726   LoopInfo run(Function &F, AnalysisManager<Function> *AM);
727 };
728
729 /// \brief Printer pass for the \c LoopAnalysis results.
730 class LoopPrinterPass {
731   raw_ostream &OS;
732
733 public:
734   explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
735   PreservedAnalyses run(Function &F, AnalysisManager<Function> *AM);
736
737   static StringRef name() { return "LoopPrinterPass"; }
738 };
739
740 /// \brief The legacy pass manager's analysis pass to compute loop information.
741 class LoopInfoWrapperPass : public FunctionPass {
742   LoopInfo LI;
743
744 public:
745   static char ID; // Pass identification, replacement for typeid
746
747   LoopInfoWrapperPass() : FunctionPass(ID) {
748     initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
749   }
750
751   LoopInfo &getLoopInfo() { return LI; }
752   const LoopInfo &getLoopInfo() const { return LI; }
753
754   /// \brief Calculate the natural loop information for a given function.
755   bool runOnFunction(Function &F) override;
756
757   void verifyAnalysis() const override;
758
759   void releaseMemory() override { LI.releaseMemory(); }
760
761   void print(raw_ostream &O, const Module *M = nullptr) const override;
762
763   void getAnalysisUsage(AnalysisUsage &AU) const override;
764 };
765
766 /// \brief Pass for printing a loop's contents as LLVM's text IR assembly.
767 class PrintLoopPass {
768   raw_ostream &OS;
769   std::string Banner;
770
771 public:
772   PrintLoopPass();
773   PrintLoopPass(raw_ostream &OS, const std::string &Banner = "");
774
775   PreservedAnalyses run(Loop &L);
776   static StringRef name() { return "PrintLoopPass"; }
777 };
778
779 } // End llvm namespace
780
781 #endif