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