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