LLVM  9.0.0svn
LoopInfo.h
Go to the documentation of this file.
1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the LoopInfo class that is used to identify natural loops
10 // and determine the loop depth of various nodes of the CFG. A natural loop
11 // has exactly one entry-point, which is called the header. Note that natural
12 // loops may actually be several loops that share the same header node.
13 //
14 // This analysis calculates the nesting structure of loops in a function. For
15 // each natural loop identified, this analysis identifies natural loops
16 // contained entirely within the loop and the basic blocks the make up the loop.
17 //
18 // It can calculate on the fly various bits of information, for example:
19 //
20 // * whether there is a preheader for the loop
21 // * the number of back edges to the header
22 // * whether or not a particular block branches out of the loop
23 // * the successor blocks of the loop
24 // * the loop depth
25 // * etc...
26 //
27 // Note that this analysis specifically identifies *Loops* not cycles or SCCs
28 // in the CFG. There can be strongly connected components in the CFG which
29 // this analysis will not recognize and that will not be represented by a Loop
30 // instance. In particular, a Loop might be inside such a non-loop SCC, or a
31 // non-loop SCC might contain a sub-SCC which is a Loop.
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #ifndef LLVM_ANALYSIS_LOOPINFO_H
36 #define LLVM_ANALYSIS_LOOPINFO_H
37 
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/DenseSet.h"
40 #include "llvm/ADT/GraphTraits.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/PassManager.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/Allocator.h"
49 #include <algorithm>
50 #include <utility>
51 
52 namespace llvm {
53 
54 class DominatorTree;
55 class LoopInfo;
56 class Loop;
57 class MDNode;
58 class MemorySSAUpdater;
59 class PHINode;
60 class raw_ostream;
61 template <class N, bool IsPostDom> class DominatorTreeBase;
62 template <class N, class M> class LoopInfoBase;
63 template <class N, class M> class LoopBase;
64 
65 //===----------------------------------------------------------------------===//
66 /// Instances of this class are used to represent loops that are detected in the
67 /// flow graph.
68 ///
69 template <class BlockT, class LoopT> class LoopBase {
70  LoopT *ParentLoop;
71  // Loops contained entirely within this one.
72  std::vector<LoopT *> SubLoops;
73 
74  // The list of blocks in this loop. First entry is the header node.
75  std::vector<BlockT *> Blocks;
76 
77  SmallPtrSet<const BlockT *, 8> DenseBlockSet;
78 
79 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
80  /// Indicator that this loop is no longer a valid loop.
81  bool IsInvalid = false;
82 #endif
83 
84  LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
86  operator=(const LoopBase<BlockT, LoopT> &) = delete;
87 
88 public:
89  /// Return the nesting level of this loop. An outer-most loop has depth 1,
90  /// for consistency with loop depth values used for basic blocks, where depth
91  /// 0 is used for blocks not inside any loops.
92  unsigned getLoopDepth() const {
93  assert(!isInvalid() && "Loop not in a valid state!");
94  unsigned D = 1;
95  for (const LoopT *CurLoop = ParentLoop; CurLoop;
96  CurLoop = CurLoop->ParentLoop)
97  ++D;
98  return D;
99  }
100  BlockT *getHeader() const { return getBlocks().front(); }
101  LoopT *getParentLoop() const { return ParentLoop; }
102 
103  /// This is a raw interface for bypassing addChildLoop.
104  void setParentLoop(LoopT *L) {
105  assert(!isInvalid() && "Loop not in a valid state!");
106  ParentLoop = L;
107  }
108 
109  /// Return true if the specified loop is contained within in this loop.
110  bool contains(const LoopT *L) const {
111  assert(!isInvalid() && "Loop not in a valid state!");
112  if (L == this)
113  return true;
114  if (!L)
115  return false;
116  return contains(L->getParentLoop());
117  }
118 
119  /// Return true if the specified basic block is in this loop.
120  bool contains(const BlockT *BB) const {
121  assert(!isInvalid() && "Loop not in a valid state!");
122  return DenseBlockSet.count(BB);
123  }
124 
125  /// Return true if the specified instruction is in this loop.
126  template <class InstT> bool contains(const InstT *Inst) const {
127  return contains(Inst->getParent());
128  }
129 
130  /// Return the loops contained entirely within this loop.
131  const std::vector<LoopT *> &getSubLoops() const {
132  assert(!isInvalid() && "Loop not in a valid state!");
133  return SubLoops;
134  }
135  std::vector<LoopT *> &getSubLoopsVector() {
136  assert(!isInvalid() && "Loop not in a valid state!");
137  return SubLoops;
138  }
139  typedef typename std::vector<LoopT *>::const_iterator iterator;
140  typedef
141  typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
142  iterator begin() const { return getSubLoops().begin(); }
143  iterator end() const { return getSubLoops().end(); }
144  reverse_iterator rbegin() const { return getSubLoops().rbegin(); }
145  reverse_iterator rend() const { return getSubLoops().rend(); }
146  bool empty() const { return getSubLoops().empty(); }
147 
148  /// Get a list of the basic blocks which make up this loop.
150  assert(!isInvalid() && "Loop not in a valid state!");
151  return Blocks;
152  }
154  block_iterator block_begin() const { return getBlocks().begin(); }
155  block_iterator block_end() const { return getBlocks().end(); }
157  assert(!isInvalid() && "Loop not in a valid state!");
158  return make_range(block_begin(), block_end());
159  }
160 
161  /// Get the number of blocks in this loop in constant time.
162  /// Invalidate the loop, indicating that it is no longer a loop.
163  unsigned getNumBlocks() const {
164  assert(!isInvalid() && "Loop not in a valid state!");
165  return Blocks.size();
166  }
167 
168  /// Return a direct, mutable handle to the blocks vector so that we can
169  /// mutate it efficiently with techniques like `std::remove`.
170  std::vector<BlockT *> &getBlocksVector() {
171  assert(!isInvalid() && "Loop not in a valid state!");
172  return Blocks;
173  }
174  /// Return a direct, mutable handle to the blocks set so that we can
175  /// mutate it efficiently.
177  assert(!isInvalid() && "Loop not in a valid state!");
178  return DenseBlockSet;
179  }
180 
181  /// Return a direct, immutable handle to the blocks set.
183  assert(!isInvalid() && "Loop not in a valid state!");
184  return DenseBlockSet;
185  }
186 
187  /// Return true if this loop is no longer valid. The only valid use of this
188  /// helper is "assert(L.isInvalid())" or equivalent, since IsInvalid is set to
189  /// true by the destructor. In other words, if this accessor returns true,
190  /// the caller has already triggered UB by calling this accessor; and so it
191  /// can only be called in a context where a return value of true indicates a
192  /// programmer error.
193  bool isInvalid() const {
194 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
195  return IsInvalid;
196 #else
197  return false;
198 #endif
199  }
200 
201  /// True if terminator in the block can branch to another block that is
202  /// outside of the current loop.
203  bool isLoopExiting(const BlockT *BB) const {
204  assert(!isInvalid() && "Loop not in a valid state!");
205  for (const auto &Succ : children<const BlockT *>(BB)) {
206  if (!contains(Succ))
207  return true;
208  }
209  return false;
210  }
211 
212  /// Returns true if \p BB is a loop-latch.
213  /// A latch block is a block that contains a branch back to the header.
214  /// This function is useful when there are multiple latches in a loop
215  /// because \fn getLoopLatch will return nullptr in that case.
216  bool isLoopLatch(const BlockT *BB) const {
217  assert(!isInvalid() && "Loop not in a valid state!");
218  assert(contains(BB) && "block does not belong to the loop");
219 
220  BlockT *Header = getHeader();
221  auto PredBegin = GraphTraits<Inverse<BlockT *>>::child_begin(Header);
222  auto PredEnd = GraphTraits<Inverse<BlockT *>>::child_end(Header);
223  return std::find(PredBegin, PredEnd, BB) != PredEnd;
224  }
225 
226  /// Calculate the number of back edges to the loop header.
227  unsigned getNumBackEdges() const {
228  assert(!isInvalid() && "Loop not in a valid state!");
229  unsigned NumBackEdges = 0;
230  BlockT *H = getHeader();
231 
232  for (const auto Pred : children<Inverse<BlockT *>>(H))
233  if (contains(Pred))
234  ++NumBackEdges;
235 
236  return NumBackEdges;
237  }
238 
239  //===--------------------------------------------------------------------===//
240  // APIs for simple analysis of the loop.
241  //
242  // Note that all of these methods can fail on general loops (ie, there may not
243  // be a preheader, etc). For best success, the loop simplification and
244  // induction variable canonicalization pass should be used to normalize loops
245  // for easy analysis. These methods assume canonical loops.
246 
247  /// Return all blocks inside the loop that have successors outside of the
248  /// loop. These are the blocks _inside of the current loop_ which branch out.
249  /// The returned list is always unique.
250  void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
251 
252  /// If getExitingBlocks would return exactly one block, return that block.
253  /// Otherwise return null.
254  BlockT *getExitingBlock() const;
255 
256  /// Return all of the successor blocks of this loop. These are the blocks
257  /// _outside of the current loop_ which are branched to.
258  void getExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
259 
260  /// If getExitBlocks would return exactly one block, return that block.
261  /// Otherwise return null.
262  BlockT *getExitBlock() const;
263 
264  /// Return true if no exit block for the loop has a predecessor that is
265  /// outside the loop.
266  bool hasDedicatedExits() const;
267 
268  /// Return all unique successor blocks of this loop.
269  /// These are the blocks _outside of the current loop_ which are branched to.
270  /// This assumes that loop exits are in canonical form, i.e. all exits are
271  /// dedicated exits.
272  void getUniqueExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
273 
274  /// If getUniqueExitBlocks would return exactly one block, return that block.
275  /// Otherwise return null.
276  BlockT *getUniqueExitBlock() const;
277 
278  /// Edge type.
279  typedef std::pair<const BlockT *, const BlockT *> Edge;
280 
281  /// Return all pairs of (_inside_block_,_outside_block_).
282  void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
283 
284  /// If there is a preheader for this loop, return it. A loop has a preheader
285  /// if there is only one edge to the header of the loop from outside of the
286  /// loop. If this is the case, the block branching to the header of the loop
287  /// is the preheader node.
288  ///
289  /// This method returns null if there is no preheader for the loop.
290  BlockT *getLoopPreheader() const;
291 
292  /// If the given loop's header has exactly one unique predecessor outside the
293  /// loop, return it. Otherwise return null.
294  /// This is less strict that the loop "preheader" concept, which requires
295  /// the predecessor to have exactly one successor.
296  BlockT *getLoopPredecessor() const;
297 
298  /// If there is a single latch block for this loop, return it.
299  /// A latch block is a block that contains a branch back to the header.
300  BlockT *getLoopLatch() const;
301 
302  /// Return all loop latch blocks of this loop. A latch block is a block that
303  /// contains a branch back to the header.
304  void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
305  assert(!isInvalid() && "Loop not in a valid state!");
306  BlockT *H = getHeader();
307  for (const auto Pred : children<Inverse<BlockT *>>(H))
308  if (contains(Pred))
309  LoopLatches.push_back(Pred);
310  }
311 
312  //===--------------------------------------------------------------------===//
313  // APIs for updating loop information after changing the CFG
314  //
315 
316  /// This method is used by other analyses to update loop information.
317  /// NewBB is set to be a new member of the current loop.
318  /// Because of this, it is added as a member of all parent loops, and is added
319  /// to the specified LoopInfo object as being in the current basic block. It
320  /// is not valid to replace the loop header with this method.
321  void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
322 
323  /// This is used when splitting loops up. It replaces the OldChild entry in
324  /// our children list with NewChild, and updates the parent pointer of
325  /// OldChild to be null and the NewChild to be this loop.
326  /// This updates the loop depth of the new child.
327  void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
328 
329  /// Add the specified loop to be a child of this loop.
330  /// This updates the loop depth of the new child.
331  void addChildLoop(LoopT *NewChild) {
332  assert(!isInvalid() && "Loop not in a valid state!");
333  assert(!NewChild->ParentLoop && "NewChild already has a parent!");
334  NewChild->ParentLoop = static_cast<LoopT *>(this);
335  SubLoops.push_back(NewChild);
336  }
337 
338  /// This removes the specified child from being a subloop of this loop. The
339  /// loop is not deleted, as it will presumably be inserted into another loop.
340  LoopT *removeChildLoop(iterator I) {
341  assert(!isInvalid() && "Loop not in a valid state!");
342  assert(I != SubLoops.end() && "Cannot remove end iterator!");
343  LoopT *Child = *I;
344  assert(Child->ParentLoop == this && "Child is not a child of this loop!");
345  SubLoops.erase(SubLoops.begin() + (I - begin()));
346  Child->ParentLoop = nullptr;
347  return Child;
348  }
349 
350  /// This removes the specified child from being a subloop of this loop. The
351  /// loop is not deleted, as it will presumably be inserted into another loop.
352  LoopT *removeChildLoop(LoopT *Child) {
353  return removeChildLoop(llvm::find(*this, Child));
354  }
355 
356  /// This adds a basic block directly to the basic block list.
357  /// This should only be used by transformations that create new loops. Other
358  /// transformations should use addBasicBlockToLoop.
359  void addBlockEntry(BlockT *BB) {
360  assert(!isInvalid() && "Loop not in a valid state!");
361  Blocks.push_back(BB);
362  DenseBlockSet.insert(BB);
363  }
364 
365  /// interface to reverse Blocks[from, end of loop] in this loop
366  void reverseBlock(unsigned from) {
367  assert(!isInvalid() && "Loop not in a valid state!");
368  std::reverse(Blocks.begin() + from, Blocks.end());
369  }
370 
371  /// interface to do reserve() for Blocks
372  void reserveBlocks(unsigned size) {
373  assert(!isInvalid() && "Loop not in a valid state!");
374  Blocks.reserve(size);
375  }
376 
377  /// This method is used to move BB (which must be part of this loop) to be the
378  /// loop header of the loop (the block that dominates all others).
379  void moveToHeader(BlockT *BB) {
380  assert(!isInvalid() && "Loop not in a valid state!");
381  if (Blocks[0] == BB)
382  return;
383  for (unsigned i = 0;; ++i) {
384  assert(i != Blocks.size() && "Loop does not contain BB!");
385  if (Blocks[i] == BB) {
386  Blocks[i] = Blocks[0];
387  Blocks[0] = BB;
388  return;
389  }
390  }
391  }
392 
393  /// This removes the specified basic block from the current loop, updating the
394  /// Blocks as appropriate. This does not update the mapping in the LoopInfo
395  /// class.
396  void removeBlockFromLoop(BlockT *BB) {
397  assert(!isInvalid() && "Loop not in a valid state!");
398  auto I = find(Blocks, BB);
399  assert(I != Blocks.end() && "N is not in this list!");
400  Blocks.erase(I);
401 
402  DenseBlockSet.erase(BB);
403  }
404 
405  /// Verify loop structure
406  void verifyLoop() const;
407 
408  /// Verify loop structure of this loop and all nested loops.
410 
411  /// Returns true if the loop is annotated parallel.
412  ///
413  /// Derived classes can override this method using static template
414  /// polymorphism.
415  bool isAnnotatedParallel() const { return false; }
416 
417  /// Print loop with all the BBs inside it.
418  void print(raw_ostream &OS, unsigned Depth = 0, bool Verbose = false) const;
419 
420 protected:
421  friend class LoopInfoBase<BlockT, LoopT>;
422 
423  /// This creates an empty loop.
424  LoopBase() : ParentLoop(nullptr) {}
425 
426  explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
427  Blocks.push_back(BB);
428  DenseBlockSet.insert(BB);
429  }
430 
431  // Since loop passes like SCEV are allowed to key analysis results off of
432  // `Loop` pointers, we cannot re-use pointers within a loop pass manager.
433  // This means loop passes should not be `delete` ing `Loop` objects directly
434  // (and risk a later `Loop` allocation re-using the address of a previous one)
435  // but should be using LoopInfo::markAsRemoved, which keeps around the `Loop`
436  // pointer till the end of the lifetime of the `LoopInfo` object.
437  //
438  // To make it easier to follow this rule, we mark the destructor as
439  // non-public.
441  for (auto *SubLoop : SubLoops)
442  SubLoop->~LoopT();
443 
444 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
445  IsInvalid = true;
446 #endif
447  SubLoops.clear();
448  Blocks.clear();
449  DenseBlockSet.clear();
450  ParentLoop = nullptr;
451  }
452 };
453 
454 template <class BlockT, class LoopT>
455 raw_ostream &operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
456  Loop.print(OS);
457  return OS;
458 }
459 
460 // Implementation in LoopInfoImpl.h
461 extern template class LoopBase<BasicBlock, Loop>;
462 
463 /// Represents a single loop in the control flow graph. Note that not all SCCs
464 /// in the CFG are necessarily loops.
466 public:
467  /// A range representing the start and end location of a loop.
468  class LocRange {
469  DebugLoc Start;
470  DebugLoc End;
471 
472  public:
473  LocRange() {}
474  LocRange(DebugLoc Start) : Start(Start), End(Start) {}
476  : Start(std::move(Start)), End(std::move(End)) {}
477 
478  const DebugLoc &getStart() const { return Start; }
479  const DebugLoc &getEnd() const { return End; }
480 
481  /// Check for null.
482  ///
483  explicit operator bool() const { return Start && End; }
484  };
485 
486  /// Return true if the specified value is loop invariant.
487  bool isLoopInvariant(const Value *V) const;
488 
489  /// Return true if all the operands of the specified instruction are loop
490  /// invariant.
491  bool hasLoopInvariantOperands(const Instruction *I) const;
492 
493  /// If the given value is an instruction inside of the loop and it can be
494  /// hoisted, do so to make it trivially loop-invariant.
495  /// Return true if the value after any hoisting is loop invariant. This
496  /// function can be used as a slightly more aggressive replacement for
497  /// isLoopInvariant.
498  ///
499  /// If InsertPt is specified, it is the point to hoist instructions to.
500  /// If null, the terminator of the loop preheader is used.
501  bool makeLoopInvariant(Value *V, bool &Changed,
502  Instruction *InsertPt = nullptr,
503  MemorySSAUpdater *MSSAU = nullptr) const;
504 
505  /// If the given instruction is inside of the loop and it can be hoisted, do
506  /// so to make it trivially loop-invariant.
507  /// Return true if the instruction after any hoisting is loop invariant. This
508  /// function can be used as a slightly more aggressive replacement for
509  /// isLoopInvariant.
510  ///
511  /// If InsertPt is specified, it is the point to hoist instructions to.
512  /// If null, the terminator of the loop preheader is used.
513  ///
514  bool makeLoopInvariant(Instruction *I, bool &Changed,
515  Instruction *InsertPt = nullptr,
516  MemorySSAUpdater *MSSAU = nullptr) const;
517 
518  /// Check to see if the loop has a canonical induction variable: an integer
519  /// recurrence that starts at 0 and increments by one each time through the
520  /// loop. If so, return the phi node that corresponds to it.
521  ///
522  /// The IndVarSimplify pass transforms loops to have a canonical induction
523  /// variable.
524  ///
525  PHINode *getCanonicalInductionVariable() const;
526 
527  /// Obtain the unique incoming and back edge. Return false if they are
528  /// non-unique or the loop is dead; otherwise, return true.
529  bool getIncomingAndBackEdge(BasicBlock *&Incoming,
530  BasicBlock *&Backedge) const;
531 
532  /// Return true if the Loop is in LCSSA form.
533  bool isLCSSAForm(DominatorTree &DT) const;
534 
535  /// Return true if this Loop and all inner subloops are in LCSSA form.
536  bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const;
537 
538  /// Return true if the Loop is in the form that the LoopSimplify form
539  /// transforms loops to, which is sometimes called normal form.
540  bool isLoopSimplifyForm() const;
541 
542  /// Return true if the loop body is safe to clone in practice.
543  bool isSafeToClone() const;
544 
545  /// Returns true if the loop is annotated parallel.
546  ///
547  /// A parallel loop can be assumed to not contain any dependencies between
548  /// iterations by the compiler. That is, any loop-carried dependency checking
549  /// can be skipped completely when parallelizing the loop on the target
550  /// machine. Thus, if the parallel loop information originates from the
551  /// programmer, e.g. via the OpenMP parallel for pragma, it is the
552  /// programmer's responsibility to ensure there are no loop-carried
553  /// dependencies. The final execution order of the instructions across
554  /// iterations is not guaranteed, thus, the end result might or might not
555  /// implement actual concurrent execution of instructions across multiple
556  /// iterations.
557  bool isAnnotatedParallel() const;
558 
559  /// Return the llvm.loop loop id metadata node for this loop if it is present.
560  ///
561  /// If this loop contains the same llvm.loop metadata on each branch to the
562  /// header then the node is returned. If any latch instruction does not
563  /// contain llvm.loop or if multiple latches contain different nodes then
564  /// 0 is returned.
565  MDNode *getLoopID() const;
566  /// Set the llvm.loop loop id metadata for this loop.
567  ///
568  /// The LoopID metadata node will be added to each terminator instruction in
569  /// the loop that branches to the loop header.
570  ///
571  /// The LoopID metadata node should have one or more operands and the first
572  /// operand should be the node itself.
573  void setLoopID(MDNode *LoopID) const;
574 
575  /// Add llvm.loop.unroll.disable to this loop's loop id metadata.
576  ///
577  /// Remove existing unroll metadata and add unroll disable metadata to
578  /// indicate the loop has already been unrolled. This prevents a loop
579  /// from being unrolled more than is directed by a pragma if the loop
580  /// unrolling pass is run more than once (which it generally is).
581  void setLoopAlreadyUnrolled();
582 
583  void dump() const;
584  void dumpVerbose() const;
585 
586  /// Return the debug location of the start of this loop.
587  /// This looks for a BB terminating instruction with a known debug
588  /// location by looking at the preheader and header blocks. If it
589  /// cannot find a terminating instruction with location information,
590  /// it returns an unknown location.
591  DebugLoc getStartLoc() const;
592 
593  /// Return the source code span of the loop.
594  LocRange getLocRange() const;
595 
596  StringRef getName() const {
597  if (BasicBlock *Header = getHeader())
598  if (Header->hasName())
599  return Header->getName();
600  return "<unnamed loop>";
601  }
602 
603 private:
604  Loop() = default;
605 
608  explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
609  ~Loop() = default;
610 };
611 
612 //===----------------------------------------------------------------------===//
613 /// This class builds and contains all of the top-level loop
614 /// structures in the specified function.
615 ///
616 
617 template <class BlockT, class LoopT> class LoopInfoBase {
618  // BBMap - Mapping of basic blocks to the inner most loop they occur in
620  std::vector<LoopT *> TopLevelLoops;
621  BumpPtrAllocator LoopAllocator;
622 
624  friend class LoopInfo;
625 
626  void operator=(const LoopInfoBase &) = delete;
627  LoopInfoBase(const LoopInfoBase &) = delete;
628 
629 public:
631  ~LoopInfoBase() { releaseMemory(); }
632 
634  : BBMap(std::move(Arg.BBMap)),
635  TopLevelLoops(std::move(Arg.TopLevelLoops)),
636  LoopAllocator(std::move(Arg.LoopAllocator)) {
637  // We have to clear the arguments top level loops as we've taken ownership.
638  Arg.TopLevelLoops.clear();
639  }
641  BBMap = std::move(RHS.BBMap);
642 
643  for (auto *L : TopLevelLoops)
644  L->~LoopT();
645 
646  TopLevelLoops = std::move(RHS.TopLevelLoops);
647  LoopAllocator = std::move(RHS.LoopAllocator);
648  RHS.TopLevelLoops.clear();
649  return *this;
650  }
651 
652  void releaseMemory() {
653  BBMap.clear();
654 
655  for (auto *L : TopLevelLoops)
656  L->~LoopT();
657  TopLevelLoops.clear();
658  LoopAllocator.Reset();
659  }
660 
661  template <typename... ArgsTy> LoopT *AllocateLoop(ArgsTy &&... Args) {
662  LoopT *Storage = LoopAllocator.Allocate<LoopT>();
663  return new (Storage) LoopT(std::forward<ArgsTy>(Args)...);
664  }
665 
666  /// iterator/begin/end - The interface to the top-level loops in the current
667  /// function.
668  ///
669  typedef typename std::vector<LoopT *>::const_iterator iterator;
670  typedef
671  typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
672  iterator begin() const { return TopLevelLoops.begin(); }
673  iterator end() const { return TopLevelLoops.end(); }
674  reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
675  reverse_iterator rend() const { return TopLevelLoops.rend(); }
676  bool empty() const { return TopLevelLoops.empty(); }
677 
678  /// Return all of the loops in the function in preorder across the loop
679  /// nests, with siblings in forward program order.
680  ///
681  /// Note that because loops form a forest of trees, preorder is equivalent to
682  /// reverse postorder.
683  SmallVector<LoopT *, 4> getLoopsInPreorder();
684 
685  /// Return all of the loops in the function in preorder across the loop
686  /// nests, with siblings in *reverse* program order.
687  ///
688  /// Note that because loops form a forest of trees, preorder is equivalent to
689  /// reverse postorder.
690  ///
691  /// Also note that this is *not* a reverse preorder. Only the siblings are in
692  /// reverse program order.
693  SmallVector<LoopT *, 4> getLoopsInReverseSiblingPreorder();
694 
695  /// Return the inner most loop that BB lives in. If a basic block is in no
696  /// loop (for example the entry node), null is returned.
697  LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
698 
699  /// Same as getLoopFor.
700  const LoopT *operator[](const BlockT *BB) const { return getLoopFor(BB); }
701 
702  /// Return the loop nesting level of the specified block. A depth of 0 means
703  /// the block is not inside any loop.
704  unsigned getLoopDepth(const BlockT *BB) const {
705  const LoopT *L = getLoopFor(BB);
706  return L ? L->getLoopDepth() : 0;
707  }
708 
709  // True if the block is a loop header node
710  bool isLoopHeader(const BlockT *BB) const {
711  const LoopT *L = getLoopFor(BB);
712  return L && L->getHeader() == BB;
713  }
714 
715  /// This removes the specified top-level loop from this loop info object.
716  /// The loop is not deleted, as it will presumably be inserted into
717  /// another loop.
718  LoopT *removeLoop(iterator I) {
719  assert(I != end() && "Cannot remove end iterator!");
720  LoopT *L = *I;
721  assert(!L->getParentLoop() && "Not a top-level loop!");
722  TopLevelLoops.erase(TopLevelLoops.begin() + (I - begin()));
723  return L;
724  }
725 
726  /// Change the top-level loop that contains BB to the specified loop.
727  /// This should be used by transformations that restructure the loop hierarchy
728  /// tree.
729  void changeLoopFor(BlockT *BB, LoopT *L) {
730  if (!L) {
731  BBMap.erase(BB);
732  return;
733  }
734  BBMap[BB] = L;
735  }
736 
737  /// Replace the specified loop in the top-level loops list with the indicated
738  /// loop.
739  void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop) {
740  auto I = find(TopLevelLoops, OldLoop);
741  assert(I != TopLevelLoops.end() && "Old loop not at top level!");
742  *I = NewLoop;
743  assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
744  "Loops already embedded into a subloop!");
745  }
746 
747  /// This adds the specified loop to the collection of top-level loops.
748  void addTopLevelLoop(LoopT *New) {
749  assert(!New->getParentLoop() && "Loop already in subloop!");
750  TopLevelLoops.push_back(New);
751  }
752 
753  /// This method completely removes BB from all data structures,
754  /// including all of the Loop objects it is nested in and our mapping from
755  /// BasicBlocks to loops.
756  void removeBlock(BlockT *BB) {
757  auto I = BBMap.find(BB);
758  if (I != BBMap.end()) {
759  for (LoopT *L = I->second; L; L = L->getParentLoop())
760  L->removeBlockFromLoop(BB);
761 
762  BBMap.erase(I);
763  }
764  }
765 
766  // Internals
767 
768  static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
769  const LoopT *ParentLoop) {
770  if (!SubLoop)
771  return true;
772  if (SubLoop == ParentLoop)
773  return false;
774  return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
775  }
776 
777  /// Create the loop forest using a stable algorithm.
778  void analyze(const DominatorTreeBase<BlockT, false> &DomTree);
779 
780  // Debugging
781  void print(raw_ostream &OS) const;
782 
783  void verify(const DominatorTreeBase<BlockT, false> &DomTree) const;
784 
785  /// Destroy a loop that has been removed from the `LoopInfo` nest.
786  ///
787  /// This runs the destructor of the loop object making it invalid to
788  /// reference afterward. The memory is retained so that the *pointer* to the
789  /// loop remains valid.
790  ///
791  /// The caller is responsible for removing this loop from the loop nest and
792  /// otherwise disconnecting it from the broader `LoopInfo` data structures.
793  /// Callers that don't naturally handle this themselves should probably call
794  /// `erase' instead.
795  void destroy(LoopT *L) {
796  L->~LoopT();
797 
798  // Since LoopAllocator is a BumpPtrAllocator, this Deallocate only poisons
799  // \c L, but the pointer remains valid for non-dereferencing uses.
800  LoopAllocator.Deallocate(L);
801  }
802 };
803 
804 // Implementation in LoopInfoImpl.h
805 extern template class LoopInfoBase<BasicBlock, Loop>;
806 
809 
811 
812  void operator=(const LoopInfo &) = delete;
813  LoopInfo(const LoopInfo &) = delete;
814 
815 public:
816  LoopInfo() {}
817  explicit LoopInfo(const DominatorTreeBase<BasicBlock, false> &DomTree);
818 
819  LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
821  BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
822  return *this;
823  }
824 
825  /// Handle invalidation explicitly.
826  bool invalidate(Function &F, const PreservedAnalyses &PA,
828 
829  // Most of the public interface is provided via LoopInfoBase.
830 
831  /// Update LoopInfo after removing the last backedge from a loop. This updates
832  /// the loop forest and parent loops for each block so that \c L is no longer
833  /// referenced, but does not actually delete \c L immediately. The pointer
834  /// will remain valid until this LoopInfo's memory is released.
835  void erase(Loop *L);
836 
837  /// Returns true if replacing From with To everywhere is guaranteed to
838  /// preserve LCSSA form.
840  // Preserving LCSSA form is only problematic if the replacing value is an
841  // instruction.
843  if (!I)
844  return true;
845  // If both instructions are defined in the same basic block then replacement
846  // cannot break LCSSA form.
847  if (I->getParent() == From->getParent())
848  return true;
849  // If the instruction is not defined in a loop then it can safely replace
850  // anything.
851  Loop *ToLoop = getLoopFor(I->getParent());
852  if (!ToLoop)
853  return true;
854  // If the replacing instruction is defined in the same loop as the original
855  // instruction, or in a loop that contains it as an inner loop, then using
856  // it as a replacement will not break LCSSA form.
857  return ToLoop->contains(getLoopFor(From->getParent()));
858  }
859 
860  /// Checks if moving a specific instruction can break LCSSA in any loop.
861  ///
862  /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
863  /// assuming that the function containing \p Inst and \p NewLoc is currently
864  /// in LCSSA form.
866  assert(Inst->getFunction() == NewLoc->getFunction() &&
867  "Can't reason about IPO!");
868 
869  auto *OldBB = Inst->getParent();
870  auto *NewBB = NewLoc->getParent();
871 
872  // Movement within the same loop does not break LCSSA (the equality check is
873  // to avoid doing a hashtable lookup in case of intra-block movement).
874  if (OldBB == NewBB)
875  return true;
876 
877  auto *OldLoop = getLoopFor(OldBB);
878  auto *NewLoop = getLoopFor(NewBB);
879 
880  if (OldLoop == NewLoop)
881  return true;
882 
883  // Check if Outer contains Inner; with the null loop counting as the
884  // "outermost" loop.
885  auto Contains = [](const Loop *Outer, const Loop *Inner) {
886  return !Outer || Outer->contains(Inner);
887  };
888 
889  // To check that the movement of Inst to before NewLoc does not break LCSSA,
890  // we need to check two sets of uses for possible LCSSA violations at
891  // NewLoc: the users of NewInst, and the operands of NewInst.
892 
893  // If we know we're hoisting Inst out of an inner loop to an outer loop,
894  // then the uses *of* Inst don't need to be checked.
895 
896  if (!Contains(NewLoop, OldLoop)) {
897  for (Use &U : Inst->uses()) {
898  auto *UI = cast<Instruction>(U.getUser());
899  auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
900  : UI->getParent();
901  if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
902  return false;
903  }
904  }
905 
906  // If we know we're sinking Inst from an outer loop into an inner loop, then
907  // the *operands* of Inst don't need to be checked.
908 
909  if (!Contains(OldLoop, NewLoop)) {
910  // See below on why we can't handle phi nodes here.
911  if (isa<PHINode>(Inst))
912  return false;
913 
914  for (Use &U : Inst->operands()) {
915  auto *DefI = dyn_cast<Instruction>(U.get());
916  if (!DefI)
917  return false;
918 
919  // This would need adjustment if we allow Inst to be a phi node -- the
920  // new use block won't simply be NewBB.
921 
922  auto *DefBlock = DefI->getParent();
923  if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
924  return false;
925  }
926  }
927 
928  return true;
929  }
930 };
931 
932 // Allow clients to walk the list of nested loops...
933 template <> struct GraphTraits<const Loop *> {
934  typedef const Loop *NodeRef;
936 
937  static NodeRef getEntryNode(const Loop *L) { return L; }
938  static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
939  static ChildIteratorType child_end(NodeRef N) { return N->end(); }
940 };
941 
942 template <> struct GraphTraits<Loop *> {
943  typedef Loop *NodeRef;
945 
946  static NodeRef getEntryNode(Loop *L) { return L; }
947  static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
948  static ChildIteratorType child_end(NodeRef N) { return N->end(); }
949 };
950 
951 /// Analysis pass that exposes the \c LoopInfo for a function.
952 class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> {
954  static AnalysisKey Key;
955 
956 public:
957  typedef LoopInfo Result;
958 
960 };
961 
962 /// Printer pass for the \c LoopAnalysis results.
963 class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> {
964  raw_ostream &OS;
965 
966 public:
967  explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
969 };
970 
971 /// Verifier pass for the \c LoopAnalysis results.
972 struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> {
974 };
975 
976 /// The legacy pass manager's analysis pass to compute loop information.
978  LoopInfo LI;
979 
980 public:
981  static char ID; // Pass identification, replacement for typeid
982 
985  }
986 
987  LoopInfo &getLoopInfo() { return LI; }
988  const LoopInfo &getLoopInfo() const { return LI; }
989 
990  /// Calculate the natural loop information for a given function.
991  bool runOnFunction(Function &F) override;
992 
993  void verifyAnalysis() const override;
994 
995  void releaseMemory() override { LI.releaseMemory(); }
996 
997  void print(raw_ostream &O, const Module *M = nullptr) const override;
998 
999  void getAnalysisUsage(AnalysisUsage &AU) const override;
1000 };
1001 
1002 /// Function to print a loop's contents as LLVM's text IR assembly.
1003 void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner = "");
1004 
1005 /// Find and return the loop attribute node for the attribute @p Name in
1006 /// @p LoopID. Return nullptr if there is no such attribute.
1008 
1009 /// Find string metadata for a loop.
1010 ///
1011 /// Returns the MDNode where the first operand is the metadata's name. The
1012 /// following operands are the metadata's values. If no metadata with @p Name is
1013 /// found, return nullptr.
1014 MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name);
1015 
1016 /// Return whether an MDNode might represent an access group.
1017 ///
1018 /// Access group metadata nodes have to be distinct and empty. Being
1019 /// always-empty ensures that it never needs to be changed (which -- because
1020 /// MDNodes are designed immutable -- would require creating a new MDNode). Note
1021 /// that this is not a sufficient condition: not every distinct and empty NDNode
1022 /// is representing an access group.
1023 bool isValidAsAccessGroup(MDNode *AccGroup);
1024 
1025 /// Create a new LoopID after the loop has been transformed.
1026 ///
1027 /// This can be used when no follow-up loop attributes are defined
1028 /// (llvm::makeFollowupLoopID returning None) to stop transformations to be
1029 /// applied again.
1030 ///
1031 /// @param Context The LLVMContext in which to create the new LoopID.
1032 /// @param OrigLoopID The original LoopID; can be nullptr if the original
1033 /// loop has no LoopID.
1034 /// @param RemovePrefixes Remove all loop attributes that have these prefixes.
1035 /// Use to remove metadata of the transformation that has
1036 /// been applied.
1037 /// @param AddAttrs Add these loop attributes to the new LoopID.
1038 ///
1039 /// @return A new LoopID that can be applied using Loop::setLoopID().
1040 llvm::MDNode *
1042  llvm::ArrayRef<llvm::StringRef> RemovePrefixes,
1044 
1045 } // End llvm namespace
1046 
1047 #endif
LoopInfo::iterator ChildIteratorType
Definition: LoopInfo.h:935
void destroy(LoopT *L)
Destroy a loop that has been removed from the LoopInfo nest.
Definition: LoopInfo.h:795
LoopInfo Result
Definition: LoopInfo.h:957
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
Definition: GraphTraits.h:121
iterator_range< use_iterator > uses()
Definition: Value.h:354
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:224
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
std::vector< BlockT * > & getBlocksVector()
Return a direct, mutable handle to the blocks vector so that we can mutate it efficiently with techni...
Definition: LoopInfo.h:170
LLVMContext & Context
bool empty() const
Definition: LoopInfo.h:676
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void setParentLoop(LoopT *L)
This is a raw interface for bypassing addChildLoop.
Definition: LoopInfo.h:104
ArrayRef< BlockT * >::const_iterator block_iterator
Definition: LoopInfo.h:153
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Definition: LoopInfoImpl.h:85
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
Definition: LoopInfo.h:704
Implements a dense probed hash-table based set.
Definition: DenseSet.h:249
unsigned getLoopDepth() const
Return the nesting level of this loop.
Definition: LoopInfo.h:92
void push_back(const T &Elt)
Definition: SmallVector.h:211
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
Definition: LoopInfo.h:379
llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode *> AddAttrs)
Create a new LoopID after the loop has been transformed.
Definition: LoopInfo.cpp:754
void reserveBlocks(unsigned size)
interface to do reserve() for Blocks
Definition: LoopInfo.h:372
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
Definition: LoopInfo.h:340
std::pair< const BlockT *, const BlockT * > Edge
Edge type.
Definition: LoopInfo.h:279
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:173
void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild)
This is used when splitting loops up.
Definition: LoopInfoImpl.h:280
std::vector< LoopT * > & getSubLoopsVector()
Definition: LoopInfo.h:135
A debug info location.
Definition: DebugLoc.h:33
Metadata node.
Definition: Metadata.h:863
F(f)
const SmallPtrSetImpl< const BlockT * > & getBlocksSet() const
Return a direct, immutable handle to the blocks set.
Definition: LoopInfo.h:182
LoopBase()
This creates an empty loop.
Definition: LoopInfo.h:424
Instances of this class are used to represent loops that are detected in the flow graph...
Definition: LoopInfo.h:63
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
bool isInvalid() const
Return true if this loop is no longer valid.
Definition: LoopInfo.h:193
void print(raw_ostream &OS, unsigned Depth=0, bool Verbose=false) const
Print loop with all the BBs inside it.
Definition: LoopInfoImpl.h:392
Hexagon Hardware Loops
Definition: BitVector.h:937
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
Definition: LoopInfo.h:227
void initializeLoopInfoWrapperPassPass(PassRegistry &)
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it...
Definition: Allocator.h:194
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Definition: LoopInfo.h:697
SmallPtrSetImpl< const BlockT * > & getBlocksSet()
Return a direct, mutable handle to the blocks set so that we can mutate it efficiently.
Definition: LoopInfo.h:176
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
Definition: LoopInfo.h:359
static bool isNotAlreadyContainedIn(const LoopT *SubLoop, const LoopT *ParentLoop)
Definition: LoopInfo.h:768
std::vector< LoopT * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
Definition: LoopInfo.h:669
void getLoopLatches(SmallVectorImpl< BlockT *> &LoopLatches) const
Return all loop latch blocks of this loop.
Definition: LoopInfo.h:304
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
Definition: LoopInfo.h:415
Printer pass for the LoopAnalysis results.
Definition: LoopInfo.h:963
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:952
void Deallocate(const void *Ptr, size_t Size)
Definition: Allocator.h:277
BlockT * getHeader() const
Definition: LoopInfo.h:100
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
Definition: LoopInfoImpl.h:62
const LoopInfo & getLoopInfo() const
Definition: LoopInfo.h:988
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:266
std::vector< LoopT * >::const_iterator iterator
Definition: LoopInfo.h:139
Key
PAL metadata keys.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
Definition: LoopInfoImpl.h:250
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:372
MDNode * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a loop.
Definition: LoopInfo.cpp:746
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
Definition: LoopInfo.h:748
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
LoopInfo & operator=(LoopInfo &&RHS)
Definition: LoopInfo.h:820
LocRange(DebugLoc Start, DebugLoc End)
Definition: LoopInfo.h:475
const DebugLoc & getEnd() const
Definition: LoopInfo.h:479
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
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:995
Core dominator tree base class.
Definition: LoopInfo.h:61
static bool runOnFunction(Function &F, bool PostInlining)
reverse_iterator rend() const
Definition: LoopInfo.h:145
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
reverse_iterator rbegin() const
Definition: LoopInfo.h:144
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
Definition: LoopInfo.h:203
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:140
static ChildIteratorType child_begin(NodeRef N)
Definition: LoopInfo.h:938
iterator end() const
Definition: LoopInfo.h:673
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:214
#define H(x, y, z)
Definition: MD5.cpp:57
LoopPrinterPass(raw_ostream &OS)
Definition: LoopInfo.h:967
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:370
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:389
Represent the analysis usage information of a pass.
bool contains(const BlockT *BB) const
Return true if the specified basic block is in this loop.
Definition: LoopInfo.h:120
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
op_range operands()
Definition: User.h:237
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:59
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:75
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
Definition: LoopInfoImpl.h:34
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:144
A range representing the start and end location of a loop.
Definition: LoopInfo.h:468
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1206
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
void getExitEdges(SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
Definition: LoopInfoImpl.h:154
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LoopInfoBase & operator=(LoopInfoBase &&RHS)
Definition: LoopInfo.h:640
BlockT * getLoopPredecessor() const
If the given loop&#39;s header has exactly one unique predecessor outside the loop, return it...
Definition: LoopInfoImpl.h:201
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:110
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1166
BlockVerifier::State From
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Definition: SmallPtrSet.h:377
bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc)
Checks if moving a specific instruction can break LCSSA in any loop.
Definition: LoopInfo.h:865
reverse_iterator rend() const
Definition: LoopInfo.h:675
Verifier pass for the LoopAnalysis results.
Definition: LoopInfo.h:972
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
const T * const_iterator
Definition: ArrayRef.h:44
iterator begin() const
Definition: LoopInfo.h:142
LoopInfo & getLoopInfo()
Definition: LoopInfo.h:987
LoopT * removeLoop(iterator I)
This removes the specified top-level loop from this loop info object.
Definition: LoopInfo.h:718
bool contains(const InstT *Inst) const
Return true if the specified instruction is in this loop.
Definition: LoopInfo.h:126
MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
Definition: LoopInfo.cpp:720
static NodeRef getEntryNode(const Loop *L)
Definition: LoopInfo.h:937
LoopT * AllocateLoop(ArgsTy &&... Args)
Definition: LoopInfo.h:661
LoopInfo(LoopInfo &&Arg)
Definition: LoopInfo.h:819
static ChildIteratorType child_end(NodeRef N)
Definition: LoopInfo.h:939
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
std::vector< LoopT * >::const_reverse_iterator reverse_iterator
Definition: LoopInfo.h:141
bool isLoopLatch(const BlockT *BB) const
Definition: LoopInfo.h:216
iterator begin() const
Definition: LoopInfo.h:672
A range adaptor for a pair of iterators.
LoopInfo::iterator ChildIteratorType
Definition: LoopInfo.h:944
bool isLoopHeader(const BlockT *BB) const
Definition: LoopInfo.h:710
reverse_iterator rbegin() const
Definition: LoopInfo.h:674
LoopT * getParentLoop() const
Definition: LoopInfo.h:101
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
Definition: LoopInfo.h:131
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
Definition: LoopInfo.h:163
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
void verifyLoopNest(DenseSet< const LoopT *> *Loops) const
Verify loop structure of this loop and all nested loops.
Definition: LoopInfoImpl.h:380
static NodeRef getEntryNode(Loop *L)
Definition: LoopInfo.h:946
const DebugLoc & getStart() const
Definition: LoopInfo.h:478
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
Definition: LoopInfo.h:331
StringRef getName() const
Definition: LoopInfo.h:596
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:465
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
Definition: LoopInfo.h:149
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
static ChildIteratorType child_end(NodeRef N)
Definition: LoopInfo.h:948
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
Replace the specified loop in the top-level loops list with the indicated loop.
Definition: LoopInfo.h:739
iterator end() const
Definition: LoopInfo.h:143
LLVM_NODISCARD 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:332
block_iterator block_end() const
Definition: LoopInfo.h:155
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
Definition: LoopInfo.h:729
friend class LoopInfo
Definition: LoopInfo.h:624
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate...
Definition: LoopInfo.h:396
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:211
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:648
bool empty() const
Definition: LoopInfo.h:146
LoopT * removeChildLoop(LoopT *Child)
This removes the specified child from being a subloop of this loop.
Definition: LoopInfo.h:352
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:72
const LoopT * operator[](const BlockT *BB) const
Same as getLoopFor.
Definition: LoopInfo.h:700
void reverseBlock(unsigned from)
interface to reverse Blocks[from, end of loop] in this loop
Definition: LoopInfo.h:366
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
The legacy pass manager&#39;s analysis pass to compute loop information.
Definition: LoopInfo.h:977
void verifyLoop() const
Verify loop structure.
Definition: LoopInfoImpl.h:294
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
Definition: LoopInfoImpl.h:99
LoopInfoBase(LoopInfoBase &&Arg)
Definition: LoopInfo.h:633
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
A container for analyses that lazily runs them and caches their results.
void releaseMemory()
Definition: LoopInfo.h:652
std::vector< LoopT * >::const_reverse_iterator reverse_iterator
Definition: LoopInfo.h:671
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
Definition: LoopInfo.h:839
This header defines various interfaces for pass management in LLVM.
iterator_range< block_iterator > blocks() const
Definition: LoopInfo.h:156
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop&#39;s contents as LLVM&#39;s text IR assembly.
Definition: LoopInfo.cpp:680
block_iterator block_begin() const
Definition: LoopInfo.h:154
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:49
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
static ChildIteratorType child_begin(NodeRef N)
Definition: LoopInfo.h:947
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
Definition: LoopInfo.h:756
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
Definition: LoopInfo.cpp:750
const BasicBlock * getParent() const
Definition: Instruction.h:66
LoopBase(BlockT *BB)
Definition: LoopInfo.h:426
LocRange(DebugLoc Start)
Definition: LoopInfo.h:474
This class builds and contains all of the top-level loop structures in the specified function...
Definition: LoopInfo.h:62