1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
19 // It can calculate on the fly various bits of information, for example:
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
28 //===----------------------------------------------------------------------===//
30 #ifndef LLVM_ANALYSIS_LOOPINFO_H
31 #define LLVM_ANALYSIS_LOOPINFO_H
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/IR/Instructions.h"
41 #include "llvm/Pass.h"
46 // FIXME: Replace this brittle forward declaration with the include of the new
47 // PassManager.h when doing so doesn't break the PassManagerBuilder.
48 template <typename IRUnitT> class AnalysisManager;
49 class PreservedAnalyses;
57 template<class N> class DominatorTreeBase;
58 template<class N, class M> class LoopInfoBase;
59 template<class N, class M> class LoopBase;
61 //===----------------------------------------------------------------------===//
62 /// Instances of this class are used to represent loops that are detected in the
65 template<class BlockT, class LoopT>
68 // Loops contained entirely within this one.
69 std::vector<LoopT *> SubLoops;
71 // The list of blocks in this loop. First entry is the header node.
72 std::vector<BlockT*> Blocks;
74 SmallPtrSet<const BlockT*, 8> DenseBlockSet;
76 /// Indicator that this loop is no longer a valid loop.
77 bool IsInvalid = false;
79 LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
80 const LoopBase<BlockT, LoopT>&
81 operator=(const LoopBase<BlockT, LoopT> &) = delete;
83 /// This creates an empty loop.
84 LoopBase() : ParentLoop(nullptr) {}
86 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
90 /// Return the nesting level of this loop. An outer-most loop has depth 1,
91 /// for consistency with loop depth values used for basic blocks, where depth
92 /// 0 is used for blocks not inside any loops.
93 unsigned getLoopDepth() const {
95 for (const LoopT *CurLoop = ParentLoop; CurLoop;
96 CurLoop = CurLoop->ParentLoop)
100 BlockT *getHeader() const { return Blocks.front(); }
101 LoopT *getParentLoop() const { return ParentLoop; }
103 /// This is a raw interface for bypassing addChildLoop.
104 void setParentLoop(LoopT *L) { ParentLoop = L; }
106 /// Return true if the specified loop is contained within in this loop.
107 bool contains(const LoopT *L) const {
108 if (L == this) return true;
109 if (!L) return false;
110 return contains(L->getParentLoop());
113 /// Return true if the specified basic block is in this loop.
114 bool contains(const BlockT *BB) const {
115 return DenseBlockSet.count(BB);
118 /// Return true if the specified instruction is in this loop.
119 template<class InstT>
120 bool contains(const InstT *Inst) const {
121 return contains(Inst->getParent());
124 /// Return the loops contained entirely within this loop.
125 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
126 std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
127 typedef typename std::vector<LoopT *>::const_iterator iterator;
128 typedef typename std::vector<LoopT *>::const_reverse_iterator
130 iterator begin() const { return SubLoops.begin(); }
131 iterator end() const { return SubLoops.end(); }
132 reverse_iterator rbegin() const { return SubLoops.rbegin(); }
133 reverse_iterator rend() const { return SubLoops.rend(); }
134 bool empty() const { return SubLoops.empty(); }
136 /// Get a list of the basic blocks which make up this loop.
137 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
138 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
139 block_iterator block_begin() const { return Blocks.begin(); }
140 block_iterator block_end() const { return Blocks.end(); }
141 inline iterator_range<block_iterator> blocks() const {
142 return make_range(block_begin(), block_end());
145 /// Get the number of blocks in this loop in constant time.
146 unsigned getNumBlocks() const {
147 return Blocks.size();
150 /// Invalidate the loop, indicating that it is no longer a loop.
151 void invalidate() { IsInvalid = true; }
153 /// Return true if this loop is no longer valid.
154 bool isInvalid() { return IsInvalid; }
156 /// True if terminator in the block can branch to another block that is
157 /// outside of the current loop.
158 bool isLoopExiting(const BlockT *BB) const {
159 typedef GraphTraits<const BlockT*> BlockTraits;
160 for (typename BlockTraits::ChildIteratorType SI =
161 BlockTraits::child_begin(BB),
162 SE = BlockTraits::child_end(BB); SI != SE; ++SI) {
169 /// Calculate the number of back edges to the loop header.
170 unsigned getNumBackEdges() const {
171 unsigned NumBackEdges = 0;
172 BlockT *H = getHeader();
174 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
175 for (typename InvBlockTraits::ChildIteratorType I =
176 InvBlockTraits::child_begin(H),
177 E = InvBlockTraits::child_end(H); I != E; ++I)
184 //===--------------------------------------------------------------------===//
185 // APIs for simple analysis of the loop.
187 // Note that all of these methods can fail on general loops (ie, there may not
188 // be a preheader, etc). For best success, the loop simplification and
189 // induction variable canonicalization pass should be used to normalize loops
190 // for easy analysis. These methods assume canonical loops.
192 /// Return all blocks inside the loop that have successors outside of the
193 /// loop. These are the blocks _inside of the current loop_ which branch out.
194 /// The returned list is always unique.
195 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
197 /// If getExitingBlocks would return exactly one block, return that block.
198 /// Otherwise return null.
199 BlockT *getExitingBlock() const;
201 /// Return all of the successor blocks of this loop. These are the blocks
202 /// _outside of the current loop_ which are branched to.
203 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
205 /// If getExitBlocks would return exactly one block, return that block.
206 /// Otherwise return null.
207 BlockT *getExitBlock() const;
210 typedef std::pair<const BlockT*, const BlockT*> Edge;
212 /// Return all pairs of (_inside_block_,_outside_block_).
213 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
215 /// If there is a preheader for this loop, return it. A loop has a preheader
216 /// if there is only one edge to the header of the loop from outside of the
217 /// loop. If this is the case, the block branching to the header of the loop
218 /// is the preheader node.
220 /// This method returns null if there is no preheader for the loop.
221 BlockT *getLoopPreheader() const;
223 /// If the given loop's header has exactly one unique predecessor outside the
224 /// loop, return it. Otherwise return null.
225 /// This is less strict that the loop "preheader" concept, which requires
226 /// the predecessor to have exactly one successor.
227 BlockT *getLoopPredecessor() const;
229 /// If there is a single latch block for this loop, return it.
230 /// A latch block is a block that contains a branch back to the header.
231 BlockT *getLoopLatch() const;
233 /// Return all loop latch blocks of this loop. A latch block is a block that
234 /// contains a branch back to the header.
235 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
236 BlockT *H = getHeader();
237 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
238 for (typename InvBlockTraits::ChildIteratorType I =
239 InvBlockTraits::child_begin(H),
240 E = InvBlockTraits::child_end(H); I != E; ++I)
242 LoopLatches.push_back(*I);
245 //===--------------------------------------------------------------------===//
246 // APIs for updating loop information after changing the CFG
249 /// This method is used by other analyses to update loop information.
250 /// NewBB is set to be a new member of the current loop.
251 /// Because of this, it is added as a member of all parent loops, and is added
252 /// to the specified LoopInfo object as being in the current basic block. It
253 /// is not valid to replace the loop header with this method.
254 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
256 /// This is used when splitting loops up. It replaces the OldChild entry in
257 /// our children list with NewChild, and updates the parent pointer of
258 /// 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);
262 /// Add the specified loop to be a child of this loop.
263 /// This updates the loop depth of the new child.
264 void addChildLoop(LoopT *NewChild) {
265 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
266 NewChild->ParentLoop = static_cast<LoopT *>(this);
267 SubLoops.push_back(NewChild);
270 /// This removes the specified child from being a subloop of this loop. The
271 /// loop is not deleted, as it will presumably be inserted into another loop.
272 LoopT *removeChildLoop(iterator I) {
273 assert(I != SubLoops.end() && "Cannot remove end iterator!");
275 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
276 SubLoops.erase(SubLoops.begin()+(I-begin()));
277 Child->ParentLoop = nullptr;
281 /// This adds a basic block directly to the basic block list.
282 /// This should only be used by transformations that create new loops. Other
283 /// transformations should use addBasicBlockToLoop.
284 void addBlockEntry(BlockT *BB) {
285 Blocks.push_back(BB);
286 DenseBlockSet.insert(BB);
289 /// interface to reverse Blocks[from, end of loop] in this loop
290 void reverseBlock(unsigned from) {
291 std::reverse(Blocks.begin() + from, Blocks.end());
294 /// interface to do reserve() for Blocks
295 void reserveBlocks(unsigned size) {
296 Blocks.reserve(size);
299 /// This method is used to move BB (which must be part of this loop) to be the
300 /// loop header of the loop (the block that dominates all others).
301 void moveToHeader(BlockT *BB) {
302 if (Blocks[0] == BB) return;
303 for (unsigned i = 0; ; ++i) {
304 assert(i != Blocks.size() && "Loop does not contain BB!");
305 if (Blocks[i] == BB) {
306 Blocks[i] = Blocks[0];
313 /// This removes the specified basic block from the current loop, updating the
314 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
316 void removeBlockFromLoop(BlockT *BB) {
317 auto I = std::find(Blocks.begin(), Blocks.end(), BB);
318 assert(I != Blocks.end() && "N is not in this list!");
321 DenseBlockSet.erase(BB);
324 /// Verify loop structure
325 void verifyLoop() const;
327 /// Verify loop structure of this loop and all nested loops.
328 void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
330 void print(raw_ostream &OS, unsigned Depth = 0) const;
333 friend class LoopInfoBase<BlockT, LoopT>;
334 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
335 Blocks.push_back(BB);
336 DenseBlockSet.insert(BB);
340 template<class BlockT, class LoopT>
341 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
346 // Implementation in LoopInfoImpl.h
347 extern template class LoopBase<BasicBlock, Loop>;
349 class Loop : public LoopBase<BasicBlock, Loop> {
353 /// Return true if the specified value is loop invariant.
354 bool isLoopInvariant(const Value *V) const;
356 /// Return true if all the operands of the specified instruction are loop
358 bool hasLoopInvariantOperands(const Instruction *I) const;
360 /// If the given value is an instruction inside of the loop and it can be
361 /// hoisted, do so to make it trivially loop-invariant.
362 /// Return true if the value after any hoisting is loop invariant. This
363 /// function can be used as a slightly more aggressive replacement for
366 /// If InsertPt is specified, it is the point to hoist instructions to.
367 /// If null, the terminator of the loop preheader is used.
368 bool makeLoopInvariant(Value *V, bool &Changed,
369 Instruction *InsertPt = nullptr) const;
371 /// If the given instruction is inside of the loop and it can be hoisted, do
372 /// so to make it trivially loop-invariant.
373 /// Return true if the instruction after any hoisting is loop invariant. This
374 /// function can be used as a slightly more aggressive replacement for
377 /// If InsertPt is specified, it is the point to hoist instructions to.
378 /// If null, the terminator of the loop preheader is used.
380 bool makeLoopInvariant(Instruction *I, bool &Changed,
381 Instruction *InsertPt = nullptr) const;
383 /// Check to see if the loop has a canonical induction variable: an integer
384 /// recurrence that starts at 0 and increments by one each time through the
385 /// loop. If so, return the phi node that corresponds to it.
387 /// The IndVarSimplify pass transforms loops to have a canonical induction
390 PHINode *getCanonicalInductionVariable() const;
392 /// Return true if the Loop is in LCSSA form.
393 bool isLCSSAForm(DominatorTree &DT) const;
395 /// Return true if this Loop and all inner subloops are in LCSSA form.
396 bool isRecursivelyLCSSAForm(DominatorTree &DT) const;
398 /// Return true if the Loop is in the form that the LoopSimplify form
399 /// transforms loops to, which is sometimes called normal form.
400 bool isLoopSimplifyForm() const;
402 /// Return true if the loop body is safe to clone in practice.
403 bool isSafeToClone() const;
405 /// Returns true if the loop is annotated parallel.
407 /// A parallel loop can be assumed to not contain any dependencies between
408 /// iterations by the compiler. That is, any loop-carried dependency checking
409 /// can be skipped completely when parallelizing the loop on the target
410 /// machine. Thus, if the parallel loop information originates from the
411 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
412 /// programmer's responsibility to ensure there are no loop-carried
413 /// dependencies. The final execution order of the instructions across
414 /// iterations is not guaranteed, thus, the end result might or might not
415 /// implement actual concurrent execution of instructions across multiple
417 bool isAnnotatedParallel() const;
419 /// Return the llvm.loop loop id metadata node for this loop if it is present.
421 /// If this loop contains the same llvm.loop metadata on each branch to the
422 /// header then the node is returned. If any latch instruction does not
423 /// contain llvm.loop or or if multiple latches contain different nodes then
425 MDNode *getLoopID() const;
426 /// Set the llvm.loop loop id metadata for this loop.
428 /// The LoopID metadata node will be added to each terminator instruction in
429 /// the loop that branches to the loop header.
431 /// The LoopID metadata node should have one or more operands and the first
432 /// operand should should be the node itself.
433 void setLoopID(MDNode *LoopID) const;
435 /// Return true if no exit block for the loop has a predecessor that is
436 /// outside the loop.
437 bool hasDedicatedExits() const;
439 /// Return all unique successor blocks of this loop.
440 /// These are the blocks _outside of the current loop_ which are branched to.
441 /// This assumes that loop exits are in canonical form.
442 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
444 /// If getUniqueExitBlocks would return exactly one block, return that block.
445 /// Otherwise return null.
446 BasicBlock *getUniqueExitBlock() const;
450 /// Return the debug location of the start of this loop.
451 /// This looks for a BB terminating instruction with a known debug
452 /// location by looking at the preheader and header blocks. If it
453 /// cannot find a terminating instruction with location information,
454 /// it returns an unknown location.
455 DebugLoc getStartLoc() const {
458 // Try the pre-header first.
459 if ((HeadBB = getLoopPreheader()) != nullptr)
460 if (DebugLoc DL = HeadBB->getTerminator()->getDebugLoc())
463 // If we have no pre-header or there are no instructions with debug
464 // info in it, try the header.
465 HeadBB = getHeader();
467 return HeadBB->getTerminator()->getDebugLoc();
473 friend class LoopInfoBase<BasicBlock, Loop>;
474 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
477 //===----------------------------------------------------------------------===//
478 /// This class builds and contains all of the top-level loop
479 /// structures in the specified function.
482 template<class BlockT, class LoopT>
484 // BBMap - Mapping of basic blocks to the inner most loop they occur in
485 DenseMap<const BlockT *, LoopT *> BBMap;
486 std::vector<LoopT *> TopLevelLoops;
487 std::vector<LoopT *> RemovedLoops;
489 friend class LoopBase<BlockT, LoopT>;
490 friend class LoopInfo;
492 void operator=(const LoopInfoBase &) = delete;
493 LoopInfoBase(const LoopInfoBase &) = delete;
496 ~LoopInfoBase() { releaseMemory(); }
498 LoopInfoBase(LoopInfoBase &&Arg)
499 : BBMap(std::move(Arg.BBMap)),
500 TopLevelLoops(std::move(Arg.TopLevelLoops)) {
501 // We have to clear the arguments top level loops as we've taken ownership.
502 Arg.TopLevelLoops.clear();
504 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
505 BBMap = std::move(RHS.BBMap);
507 for (auto *L : TopLevelLoops)
509 TopLevelLoops = std::move(RHS.TopLevelLoops);
510 RHS.TopLevelLoops.clear();
514 void releaseMemory() {
517 for (auto *L : TopLevelLoops)
519 TopLevelLoops.clear();
520 for (auto *L : RemovedLoops)
522 RemovedLoops.clear();
525 /// iterator/begin/end - The interface to the top-level loops in the current
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(); }
537 /// Return the inner most loop that BB lives in. If a basic block is in no
538 /// loop (for example the entry node), null is returned.
539 LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
541 /// Same as getLoopFor.
542 const LoopT *operator[](const BlockT *BB) const {
543 return getLoopFor(BB);
546 /// Return the loop nesting level of the specified block. A depth of 0 means
547 /// the block is not inside any loop.
548 unsigned getLoopDepth(const BlockT *BB) const {
549 const LoopT *L = getLoopFor(BB);
550 return L ? L->getLoopDepth() : 0;
553 // True if the block is a loop header node
554 bool isLoopHeader(const BlockT *BB) const {
555 const LoopT *L = getLoopFor(BB);
556 return L && L->getHeader() == BB;
559 /// This removes the specified top-level loop from this loop info object.
560 /// The loop is not deleted, as it will presumably be inserted into
562 LoopT *removeLoop(iterator I) {
563 assert(I != end() && "Cannot remove end iterator!");
565 assert(!L->getParentLoop() && "Not a top-level loop!");
566 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
570 /// Change the top-level loop that contains BB to the specified loop.
571 /// This should be used by transformations that restructure the loop hierarchy
573 void changeLoopFor(BlockT *BB, LoopT *L) {
581 /// Replace the specified loop in the top-level loops list with the indicated
583 void changeTopLevelLoop(LoopT *OldLoop,
585 auto I = std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
586 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
588 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
589 "Loops already embedded into a subloop!");
592 /// This adds the specified loop to the collection of top-level loops.
593 void addTopLevelLoop(LoopT *New) {
594 assert(!New->getParentLoop() && "Loop already in subloop!");
595 TopLevelLoops.push_back(New);
598 /// This method completely removes BB from all data structures,
599 /// including all of the Loop objects it is nested in and our mapping from
600 /// BasicBlocks to loops.
601 void removeBlock(BlockT *BB) {
602 auto I = BBMap.find(BB);
603 if (I != BBMap.end()) {
604 for (LoopT *L = I->second; L; L = L->getParentLoop())
605 L->removeBlockFromLoop(BB);
613 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
614 const LoopT *ParentLoop) {
615 if (!SubLoop) return true;
616 if (SubLoop == ParentLoop) return false;
617 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
620 /// Create the loop forest using a stable algorithm.
621 void analyze(const DominatorTreeBase<BlockT> &DomTree);
624 void print(raw_ostream &OS) const;
629 // Implementation in LoopInfoImpl.h
630 extern template class LoopInfoBase<BasicBlock, Loop>;
632 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
633 typedef LoopInfoBase<BasicBlock, Loop> BaseT;
635 friend class LoopBase<BasicBlock, Loop>;
637 void operator=(const LoopInfo &) = delete;
638 LoopInfo(const LoopInfo &) = delete;
641 explicit LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree);
643 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
644 LoopInfo &operator=(LoopInfo &&RHS) {
645 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
649 // Most of the public interface is provided via LoopInfoBase.
651 /// Update LoopInfo after removing the last backedge from a loop. This updates
652 /// the loop forest and parent loops for each block so that \c L is no longer
653 /// referenced, but does not actually delete \c L immediately. The pointer
654 /// will remain valid until this LoopInfo's memory is released.
655 void markAsRemoved(Loop *L);
657 /// Returns true if replacing From with To everywhere is guaranteed to
658 /// preserve LCSSA form.
659 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
660 // Preserving LCSSA form is only problematic if the replacing value is an
662 Instruction *I = dyn_cast<Instruction>(To);
664 // If both instructions are defined in the same basic block then replacement
665 // cannot break LCSSA form.
666 if (I->getParent() == From->getParent())
668 // If the instruction is not defined in a loop then it can safely replace
670 Loop *ToLoop = getLoopFor(I->getParent());
671 if (!ToLoop) return true;
672 // If the replacing instruction is defined in the same loop as the original
673 // instruction, or in a loop that contains it as an inner loop, then using
674 // it as a replacement will not break LCSSA form.
675 return ToLoop->contains(getLoopFor(From->getParent()));
678 /// Checks if moving a specific instruction can break LCSSA in any loop.
680 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
681 /// assuming that the function containing \p Inst and \p NewLoc is currently
683 bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
684 assert(Inst->getFunction() == NewLoc->getFunction() &&
685 "Can't reason about IPO!");
687 auto *OldBB = Inst->getParent();
688 auto *NewBB = NewLoc->getParent();
690 // Movement within the same loop does not break LCSSA (the equality check is
691 // to avoid doing a hashtable lookup in case of intra-block movement).
695 auto *OldLoop = getLoopFor(OldBB);
696 auto *NewLoop = getLoopFor(NewBB);
698 if (OldLoop == NewLoop)
701 // Check if Outer contains Inner; with the null loop counting as the
703 auto Contains = [](const Loop *Outer, const Loop *Inner) {
704 return !Outer || Outer->contains(Inner);
707 // To check that the movement of Inst to before NewLoc does not break LCSSA,
708 // we need to check two sets of uses for possible LCSSA violations at
709 // NewLoc: the users of NewInst, and the operands of NewInst.
711 // If we know we're hoisting Inst out of an inner loop to an outer loop,
712 // then the uses *of* Inst don't need to be checked.
714 if (!Contains(NewLoop, OldLoop)) {
715 for (Use &U : Inst->uses()) {
716 auto *UI = cast<Instruction>(U.getUser());
717 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
719 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
724 // If we know we're sinking Inst from an outer loop into an inner loop, then
725 // the *operands* of Inst don't need to be checked.
727 if (!Contains(OldLoop, NewLoop)) {
728 // See below on why we can't handle phi nodes here.
729 if (isa<PHINode>(Inst))
732 for (Use &U : Inst->operands()) {
733 auto *DefI = dyn_cast<Instruction>(U.get());
737 // This would need adjustment if we allow Inst to be a phi node -- the
738 // new use block won't simply be NewBB.
740 auto *DefBlock = DefI->getParent();
741 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
750 // Allow clients to walk the list of nested loops...
751 template <> struct GraphTraits<const Loop*> {
752 typedef const Loop NodeType;
753 typedef LoopInfo::iterator ChildIteratorType;
755 static NodeType *getEntryNode(const Loop *L) { return L; }
756 static inline ChildIteratorType child_begin(NodeType *N) {
759 static inline ChildIteratorType child_end(NodeType *N) {
764 template <> struct GraphTraits<Loop*> {
765 typedef Loop NodeType;
766 typedef LoopInfo::iterator ChildIteratorType;
768 static NodeType *getEntryNode(Loop *L) { return L; }
769 static inline ChildIteratorType child_begin(NodeType *N) {
772 static inline ChildIteratorType child_end(NodeType *N) {
777 /// \brief Analysis pass that exposes the \c LoopInfo for a function.
782 typedef LoopInfo Result;
784 /// \brief Opaque, unique identifier for this analysis pass.
785 static void *ID() { return (void *)&PassID; }
787 /// \brief Provide a name for the analysis for debugging and logging.
788 static StringRef name() { return "LoopAnalysis"; }
790 LoopInfo run(Function &F, AnalysisManager<Function> *AM);
793 /// \brief Printer pass for the \c LoopAnalysis results.
794 class LoopPrinterPass {
798 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
799 PreservedAnalyses run(Function &F, AnalysisManager<Function> *AM);
801 static StringRef name() { return "LoopPrinterPass"; }
804 /// \brief The legacy pass manager's analysis pass to compute loop information.
805 class LoopInfoWrapperPass : public FunctionPass {
809 static char ID; // Pass identification, replacement for typeid
811 LoopInfoWrapperPass() : FunctionPass(ID) {
812 initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
815 LoopInfo &getLoopInfo() { return LI; }
816 const LoopInfo &getLoopInfo() const { return LI; }
818 /// \brief Calculate the natural loop information for a given function.
819 bool runOnFunction(Function &F) override;
821 void verifyAnalysis() const override;
823 void releaseMemory() override { LI.releaseMemory(); }
825 void print(raw_ostream &O, const Module *M = nullptr) const override;
827 void getAnalysisUsage(AnalysisUsage &AU) const override;
830 /// \brief Pass for printing a loop's contents as LLVM's text IR assembly.
831 class PrintLoopPass {
837 PrintLoopPass(raw_ostream &OS, const std::string &Banner = "");
839 PreservedAnalyses run(Loop &L);
840 static StringRef name() { return "PrintLoopPass"; }
843 } // End llvm namespace