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 // Note that this analysis specifically identifies *Loops* not cycles or SCCs
29 // in the CFG. There can be strongly connected components in the CFG which
30 // this analysis will not recognize and that will not be represented by a Loop
31 // instance. In particular, a Loop might be inside such a non-loop SCC, or a
32 // non-loop SCC might contain a sub-SCC which is a Loop.
34 //===----------------------------------------------------------------------===//
36 #ifndef LLVM_ANALYSIS_LOOPINFO_H
37 #define LLVM_ANALYSIS_LOOPINFO_H
39 #include "llvm/ADT/DenseMap.h"
40 #include "llvm/ADT/DenseSet.h"
41 #include "llvm/ADT/GraphTraits.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/IR/CFG.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/PassManager.h"
48 #include "llvm/Pass.h"
59 template<class N> class DominatorTreeBase;
60 template<class N, class M> class LoopInfoBase;
61 template<class N, class M> class LoopBase;
63 //===----------------------------------------------------------------------===//
64 /// Instances of this class are used to represent loops that are detected in the
67 template<class BlockT, class LoopT>
70 // Loops contained entirely within this one.
71 std::vector<LoopT *> SubLoops;
73 // The list of blocks in this loop. First entry is the header node.
74 std::vector<BlockT*> Blocks;
76 SmallPtrSet<const BlockT*, 8> DenseBlockSet;
78 /// Indicator that this loop is no longer a valid loop.
79 bool IsInvalid = false;
81 LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
82 const LoopBase<BlockT, LoopT>&
83 operator=(const LoopBase<BlockT, LoopT> &) = delete;
85 /// This creates an empty loop.
86 LoopBase() : ParentLoop(nullptr) {}
88 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
92 /// Return the nesting level of this loop. An outer-most loop has depth 1,
93 /// for consistency with loop depth values used for basic blocks, where depth
94 /// 0 is used for blocks not inside any loops.
95 unsigned getLoopDepth() const {
97 for (const LoopT *CurLoop = ParentLoop; CurLoop;
98 CurLoop = CurLoop->ParentLoop)
102 BlockT *getHeader() const { return Blocks.front(); }
103 LoopT *getParentLoop() const { return ParentLoop; }
105 /// This is a raw interface for bypassing addChildLoop.
106 void setParentLoop(LoopT *L) { ParentLoop = L; }
108 /// Return true if the specified loop is contained within in this loop.
109 bool contains(const LoopT *L) const {
110 if (L == this) return true;
111 if (!L) return false;
112 return contains(L->getParentLoop());
115 /// Return true if the specified basic block is in this loop.
116 bool contains(const BlockT *BB) const {
117 return DenseBlockSet.count(BB);
120 /// Return true if the specified instruction is in this loop.
121 template<class InstT>
122 bool contains(const InstT *Inst) const {
123 return contains(Inst->getParent());
126 /// Return the loops contained entirely within this loop.
127 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
128 std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
129 typedef typename std::vector<LoopT *>::const_iterator iterator;
130 typedef typename std::vector<LoopT *>::const_reverse_iterator
132 iterator begin() const { return SubLoops.begin(); }
133 iterator end() const { return SubLoops.end(); }
134 reverse_iterator rbegin() const { return SubLoops.rbegin(); }
135 reverse_iterator rend() const { return SubLoops.rend(); }
136 bool empty() const { return SubLoops.empty(); }
138 /// Get a list of the basic blocks which make up this loop.
139 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
140 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
141 block_iterator block_begin() const { return Blocks.begin(); }
142 block_iterator block_end() const { return Blocks.end(); }
143 inline iterator_range<block_iterator> blocks() const {
144 return make_range(block_begin(), block_end());
147 /// Get the number of blocks in this loop in constant time.
148 unsigned getNumBlocks() const {
149 return Blocks.size();
152 /// Invalidate the loop, indicating that it is no longer a loop.
153 void invalidate() { IsInvalid = true; }
155 /// Return true if this loop is no longer valid.
156 bool isInvalid() { return IsInvalid; }
158 /// True if terminator in the block can branch to another block that is
159 /// outside of the current loop.
160 bool isLoopExiting(const BlockT *BB) const {
161 for (const auto &Succ : children<const BlockT*>(BB)) {
168 /// Returns true if \p BB is a loop-latch.
169 /// A latch block is a block that contains a branch back to the header.
170 /// This function is useful when there are multiple latches in a loop
171 /// because \fn getLoopLatch will return nullptr in that case.
172 bool isLoopLatch(const BlockT *BB) const {
173 assert(contains(BB) && "block does not belong to the loop");
175 BlockT *Header = getHeader();
176 auto PredBegin = GraphTraits<Inverse<BlockT*> >::child_begin(Header);
177 auto PredEnd = GraphTraits<Inverse<BlockT*> >::child_end(Header);
178 return std::find(PredBegin, PredEnd, BB) != PredEnd;
181 /// Calculate the number of back edges to the loop header.
182 unsigned getNumBackEdges() const {
183 unsigned NumBackEdges = 0;
184 BlockT *H = getHeader();
186 for (const auto Pred : children<Inverse<BlockT*> >(H))
193 //===--------------------------------------------------------------------===//
194 // APIs for simple analysis of the loop.
196 // Note that all of these methods can fail on general loops (ie, there may not
197 // be a preheader, etc). For best success, the loop simplification and
198 // induction variable canonicalization pass should be used to normalize loops
199 // for easy analysis. These methods assume canonical loops.
201 /// Return all blocks inside the loop that have successors outside of the
202 /// loop. These are the blocks _inside of the current loop_ which branch out.
203 /// The returned list is always unique.
204 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
206 /// If getExitingBlocks would return exactly one block, return that block.
207 /// Otherwise return null.
208 BlockT *getExitingBlock() const;
210 /// Return all of the successor blocks of this loop. These are the blocks
211 /// _outside of the current loop_ which are branched to.
212 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
214 /// If getExitBlocks would return exactly one block, return that block.
215 /// Otherwise return null.
216 BlockT *getExitBlock() const;
219 typedef std::pair<const BlockT*, const BlockT*> Edge;
221 /// Return all pairs of (_inside_block_,_outside_block_).
222 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
224 /// If there is a preheader for this loop, return it. A loop has a preheader
225 /// if there is only one edge to the header of the loop from outside of the
226 /// loop. If this is the case, the block branching to the header of the loop
227 /// is the preheader node.
229 /// This method returns null if there is no preheader for the loop.
230 BlockT *getLoopPreheader() const;
232 /// If the given loop's header has exactly one unique predecessor outside the
233 /// loop, return it. Otherwise return null.
234 /// This is less strict that the loop "preheader" concept, which requires
235 /// the predecessor to have exactly one successor.
236 BlockT *getLoopPredecessor() const;
238 /// If there is a single latch block for this loop, return it.
239 /// A latch block is a block that contains a branch back to the header.
240 BlockT *getLoopLatch() const;
242 /// Return all loop latch blocks of this loop. A latch block is a block that
243 /// contains a branch back to the header.
244 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
245 BlockT *H = getHeader();
246 for (const auto Pred : children<Inverse<BlockT*>>(H))
248 LoopLatches.push_back(Pred);
251 //===--------------------------------------------------------------------===//
252 // APIs for updating loop information after changing the CFG
255 /// This method is used by other analyses to update loop information.
256 /// NewBB is set to be a new member of the current loop.
257 /// Because of this, it is added as a member of all parent loops, and is added
258 /// to the specified LoopInfo object as being in the current basic block. It
259 /// is not valid to replace the loop header with this method.
260 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
262 /// This is used when splitting loops up. It replaces the OldChild entry in
263 /// our children list with NewChild, and updates the parent pointer of
264 /// OldChild to be null and the NewChild to be this loop.
265 /// This updates the loop depth of the new child.
266 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
268 /// Add the specified loop to be a child of this loop.
269 /// This updates the loop depth of the new child.
270 void addChildLoop(LoopT *NewChild) {
271 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
272 NewChild->ParentLoop = static_cast<LoopT *>(this);
273 SubLoops.push_back(NewChild);
276 /// This removes the specified child from being a subloop of this loop. The
277 /// loop is not deleted, as it will presumably be inserted into another loop.
278 LoopT *removeChildLoop(iterator I) {
279 assert(I != SubLoops.end() && "Cannot remove end iterator!");
281 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
282 SubLoops.erase(SubLoops.begin()+(I-begin()));
283 Child->ParentLoop = nullptr;
287 /// This adds a basic block directly to the basic block list.
288 /// This should only be used by transformations that create new loops. Other
289 /// transformations should use addBasicBlockToLoop.
290 void addBlockEntry(BlockT *BB) {
291 Blocks.push_back(BB);
292 DenseBlockSet.insert(BB);
295 /// interface to reverse Blocks[from, end of loop] in this loop
296 void reverseBlock(unsigned from) {
297 std::reverse(Blocks.begin() + from, Blocks.end());
300 /// interface to do reserve() for Blocks
301 void reserveBlocks(unsigned size) {
302 Blocks.reserve(size);
305 /// This method is used to move BB (which must be part of this loop) to be the
306 /// loop header of the loop (the block that dominates all others).
307 void moveToHeader(BlockT *BB) {
308 if (Blocks[0] == BB) return;
309 for (unsigned i = 0; ; ++i) {
310 assert(i != Blocks.size() && "Loop does not contain BB!");
311 if (Blocks[i] == BB) {
312 Blocks[i] = Blocks[0];
319 /// This removes the specified basic block from the current loop, updating the
320 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
322 void removeBlockFromLoop(BlockT *BB) {
323 auto I = find(Blocks, BB);
324 assert(I != Blocks.end() && "N is not in this list!");
327 DenseBlockSet.erase(BB);
330 /// Verify loop structure
331 void verifyLoop() const;
333 /// Verify loop structure of this loop and all nested loops.
334 void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
336 /// Print loop with all the BBs inside it.
337 void print(raw_ostream &OS, unsigned Depth = 0, bool Verbose = false) const;
340 friend class LoopInfoBase<BlockT, LoopT>;
341 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
342 Blocks.push_back(BB);
343 DenseBlockSet.insert(BB);
347 template<class BlockT, class LoopT>
348 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
353 // Implementation in LoopInfoImpl.h
354 extern template class LoopBase<BasicBlock, Loop>;
357 /// Represents a single loop in the control flow graph. Note that not all SCCs
358 /// in the CFG are necessarily loops.
359 class Loop : public LoopBase<BasicBlock, Loop> {
361 /// \brief A range representing the start and end location of a loop.
368 LocRange(DebugLoc Start) : Start(std::move(Start)), End(std::move(Start)) {}
369 LocRange(DebugLoc Start, DebugLoc End) : Start(std::move(Start)),
370 End(std::move(End)) {}
372 const DebugLoc &getStart() const { return Start; }
373 const DebugLoc &getEnd() const { return End; }
375 /// \brief Check for null.
377 explicit operator bool() const {
384 /// Return true if the specified value is loop invariant.
385 bool isLoopInvariant(const Value *V) const;
387 /// Return true if all the operands of the specified instruction are loop
389 bool hasLoopInvariantOperands(const Instruction *I) const;
391 /// If the given value is an instruction inside of the loop and it can be
392 /// hoisted, do so to make it trivially loop-invariant.
393 /// Return true if the value after any hoisting is loop invariant. This
394 /// function can be used as a slightly more aggressive replacement for
397 /// If InsertPt is specified, it is the point to hoist instructions to.
398 /// If null, the terminator of the loop preheader is used.
399 bool makeLoopInvariant(Value *V, bool &Changed,
400 Instruction *InsertPt = nullptr) const;
402 /// If the given instruction is inside of the loop and it can be hoisted, do
403 /// so to make it trivially loop-invariant.
404 /// Return true if the instruction after any hoisting is loop invariant. This
405 /// function can be used as a slightly more aggressive replacement for
408 /// If InsertPt is specified, it is the point to hoist instructions to.
409 /// If null, the terminator of the loop preheader is used.
411 bool makeLoopInvariant(Instruction *I, bool &Changed,
412 Instruction *InsertPt = nullptr) const;
414 /// Check to see if the loop has a canonical induction variable: an integer
415 /// recurrence that starts at 0 and increments by one each time through the
416 /// loop. If so, return the phi node that corresponds to it.
418 /// The IndVarSimplify pass transforms loops to have a canonical induction
421 PHINode *getCanonicalInductionVariable() const;
423 /// Return true if the Loop is in LCSSA form.
424 bool isLCSSAForm(DominatorTree &DT) const;
426 /// Return true if this Loop and all inner subloops are in LCSSA form.
427 bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const;
429 /// Return true if the Loop is in the form that the LoopSimplify form
430 /// transforms loops to, which is sometimes called normal form.
431 bool isLoopSimplifyForm() const;
433 /// Return true if the loop body is safe to clone in practice.
434 bool isSafeToClone() const;
436 /// Returns true if the loop is annotated parallel.
438 /// A parallel loop can be assumed to not contain any dependencies between
439 /// iterations by the compiler. That is, any loop-carried dependency checking
440 /// can be skipped completely when parallelizing the loop on the target
441 /// machine. Thus, if the parallel loop information originates from the
442 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
443 /// programmer's responsibility to ensure there are no loop-carried
444 /// dependencies. The final execution order of the instructions across
445 /// iterations is not guaranteed, thus, the end result might or might not
446 /// implement actual concurrent execution of instructions across multiple
448 bool isAnnotatedParallel() const;
450 /// Return the llvm.loop loop id metadata node for this loop if it is present.
452 /// If this loop contains the same llvm.loop metadata on each branch to the
453 /// header then the node is returned. If any latch instruction does not
454 /// contain llvm.loop or or if multiple latches contain different nodes then
456 MDNode *getLoopID() const;
457 /// Set the llvm.loop loop id metadata for this loop.
459 /// The LoopID metadata node will be added to each terminator instruction in
460 /// the loop that branches to the loop header.
462 /// The LoopID metadata node should have one or more operands and the first
463 /// operand should be the node itself.
464 void setLoopID(MDNode *LoopID) const;
466 /// Return true if no exit block for the loop has a predecessor that is
467 /// outside the loop.
468 bool hasDedicatedExits() const;
470 /// Return all unique successor blocks of this loop.
471 /// These are the blocks _outside of the current loop_ which are branched to.
472 /// This assumes that loop exits are in canonical form, i.e. all exits are
474 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
476 /// If getUniqueExitBlocks would return exactly one block, return that block.
477 /// Otherwise return null.
478 BasicBlock *getUniqueExitBlock() const;
481 void dumpVerbose() const;
483 /// Return the debug location of the start of this loop.
484 /// This looks for a BB terminating instruction with a known debug
485 /// location by looking at the preheader and header blocks. If it
486 /// cannot find a terminating instruction with location information,
487 /// it returns an unknown location.
488 DebugLoc getStartLoc() const;
490 /// Return the source code span of the loop.
491 LocRange getLocRange() const;
493 StringRef getName() const {
494 if (BasicBlock *Header = getHeader())
495 if (Header->hasName())
496 return Header->getName();
497 return "<unnamed loop>";
501 friend class LoopInfoBase<BasicBlock, Loop>;
502 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
505 //===----------------------------------------------------------------------===//
506 /// This class builds and contains all of the top-level loop
507 /// structures in the specified function.
510 template<class BlockT, class LoopT>
512 // BBMap - Mapping of basic blocks to the inner most loop they occur in
513 DenseMap<const BlockT *, LoopT *> BBMap;
514 std::vector<LoopT *> TopLevelLoops;
515 std::vector<LoopT *> RemovedLoops;
517 friend class LoopBase<BlockT, LoopT>;
518 friend class LoopInfo;
520 void operator=(const LoopInfoBase &) = delete;
521 LoopInfoBase(const LoopInfoBase &) = delete;
524 ~LoopInfoBase() { releaseMemory(); }
526 LoopInfoBase(LoopInfoBase &&Arg)
527 : BBMap(std::move(Arg.BBMap)),
528 TopLevelLoops(std::move(Arg.TopLevelLoops)) {
529 // We have to clear the arguments top level loops as we've taken ownership.
530 Arg.TopLevelLoops.clear();
532 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
533 BBMap = std::move(RHS.BBMap);
535 for (auto *L : TopLevelLoops)
537 TopLevelLoops = std::move(RHS.TopLevelLoops);
538 RHS.TopLevelLoops.clear();
542 void releaseMemory() {
545 for (auto *L : TopLevelLoops)
547 TopLevelLoops.clear();
548 for (auto *L : RemovedLoops)
550 RemovedLoops.clear();
553 /// iterator/begin/end - The interface to the top-level loops in the current
556 typedef typename std::vector<LoopT *>::const_iterator iterator;
557 typedef typename std::vector<LoopT *>::const_reverse_iterator
559 iterator begin() const { return TopLevelLoops.begin(); }
560 iterator end() const { return TopLevelLoops.end(); }
561 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
562 reverse_iterator rend() const { return TopLevelLoops.rend(); }
563 bool empty() const { return TopLevelLoops.empty(); }
565 /// Return all of the loops in the function in preorder across the loop
566 /// nests, with siblings in forward program order.
568 /// Note that because loops form a forest of trees, preorder is equivalent to
569 /// reverse postorder.
570 SmallVector<LoopT *, 4> getLoopsInPreorder();
572 /// Return all of the loops in the function in preorder across the loop
573 /// nests, with siblings in *reverse* program order.
575 /// Note that because loops form a forest of trees, preorder is equivalent to
576 /// reverse postorder.
578 /// Also note that this is *not* a reverse preorder. Only the siblings are in
579 /// reverse program order.
580 SmallVector<LoopT *, 4> getLoopsInReverseSiblingPreorder();
582 /// Return the inner most loop that BB lives in. If a basic block is in no
583 /// loop (for example the entry node), null is returned.
584 LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
586 /// Same as getLoopFor.
587 const LoopT *operator[](const BlockT *BB) const {
588 return getLoopFor(BB);
591 /// Return the loop nesting level of the specified block. A depth of 0 means
592 /// the block is not inside any loop.
593 unsigned getLoopDepth(const BlockT *BB) const {
594 const LoopT *L = getLoopFor(BB);
595 return L ? L->getLoopDepth() : 0;
598 // True if the block is a loop header node
599 bool isLoopHeader(const BlockT *BB) const {
600 const LoopT *L = getLoopFor(BB);
601 return L && L->getHeader() == BB;
604 /// This removes the specified top-level loop from this loop info object.
605 /// The loop is not deleted, as it will presumably be inserted into
607 LoopT *removeLoop(iterator I) {
608 assert(I != end() && "Cannot remove end iterator!");
610 assert(!L->getParentLoop() && "Not a top-level loop!");
611 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
615 /// Change the top-level loop that contains BB to the specified loop.
616 /// This should be used by transformations that restructure the loop hierarchy
618 void changeLoopFor(BlockT *BB, LoopT *L) {
626 /// Replace the specified loop in the top-level loops list with the indicated
628 void changeTopLevelLoop(LoopT *OldLoop,
630 auto I = find(TopLevelLoops, OldLoop);
631 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
633 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
634 "Loops already embedded into a subloop!");
637 /// This adds the specified loop to the collection of top-level loops.
638 void addTopLevelLoop(LoopT *New) {
639 assert(!New->getParentLoop() && "Loop already in subloop!");
640 TopLevelLoops.push_back(New);
643 /// This method completely removes BB from all data structures,
644 /// including all of the Loop objects it is nested in and our mapping from
645 /// BasicBlocks to loops.
646 void removeBlock(BlockT *BB) {
647 auto I = BBMap.find(BB);
648 if (I != BBMap.end()) {
649 for (LoopT *L = I->second; L; L = L->getParentLoop())
650 L->removeBlockFromLoop(BB);
658 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
659 const LoopT *ParentLoop) {
660 if (!SubLoop) return true;
661 if (SubLoop == ParentLoop) return false;
662 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
665 /// Create the loop forest using a stable algorithm.
666 void analyze(const DominatorTreeBase<BlockT> &DomTree);
669 void print(raw_ostream &OS) const;
671 void verify(const DominatorTreeBase<BlockT> &DomTree) const;
674 // Implementation in LoopInfoImpl.h
675 extern template class LoopInfoBase<BasicBlock, Loop>;
677 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
678 typedef LoopInfoBase<BasicBlock, Loop> BaseT;
680 friend class LoopBase<BasicBlock, Loop>;
682 void operator=(const LoopInfo &) = delete;
683 LoopInfo(const LoopInfo &) = delete;
686 explicit LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree);
688 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
689 LoopInfo &operator=(LoopInfo &&RHS) {
690 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
694 /// Handle invalidation explicitly.
695 bool invalidate(Function &F, const PreservedAnalyses &PA,
696 FunctionAnalysisManager::Invalidator &);
698 // Most of the public interface is provided via LoopInfoBase.
700 /// Update LoopInfo after removing the last backedge from a loop. This updates
701 /// the loop forest and parent loops for each block so that \c L is no longer
702 /// referenced, but does not actually delete \c L immediately. The pointer
703 /// will remain valid until this LoopInfo's memory is released.
704 void markAsRemoved(Loop *L);
706 /// Returns true if replacing From with To everywhere is guaranteed to
707 /// preserve LCSSA form.
708 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
709 // Preserving LCSSA form is only problematic if the replacing value is an
711 Instruction *I = dyn_cast<Instruction>(To);
713 // If both instructions are defined in the same basic block then replacement
714 // cannot break LCSSA form.
715 if (I->getParent() == From->getParent())
717 // If the instruction is not defined in a loop then it can safely replace
719 Loop *ToLoop = getLoopFor(I->getParent());
720 if (!ToLoop) return true;
721 // If the replacing instruction is defined in the same loop as the original
722 // instruction, or in a loop that contains it as an inner loop, then using
723 // it as a replacement will not break LCSSA form.
724 return ToLoop->contains(getLoopFor(From->getParent()));
727 /// Checks if moving a specific instruction can break LCSSA in any loop.
729 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
730 /// assuming that the function containing \p Inst and \p NewLoc is currently
732 bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
733 assert(Inst->getFunction() == NewLoc->getFunction() &&
734 "Can't reason about IPO!");
736 auto *OldBB = Inst->getParent();
737 auto *NewBB = NewLoc->getParent();
739 // Movement within the same loop does not break LCSSA (the equality check is
740 // to avoid doing a hashtable lookup in case of intra-block movement).
744 auto *OldLoop = getLoopFor(OldBB);
745 auto *NewLoop = getLoopFor(NewBB);
747 if (OldLoop == NewLoop)
750 // Check if Outer contains Inner; with the null loop counting as the
752 auto Contains = [](const Loop *Outer, const Loop *Inner) {
753 return !Outer || Outer->contains(Inner);
756 // To check that the movement of Inst to before NewLoc does not break LCSSA,
757 // we need to check two sets of uses for possible LCSSA violations at
758 // NewLoc: the users of NewInst, and the operands of NewInst.
760 // If we know we're hoisting Inst out of an inner loop to an outer loop,
761 // then the uses *of* Inst don't need to be checked.
763 if (!Contains(NewLoop, OldLoop)) {
764 for (Use &U : Inst->uses()) {
765 auto *UI = cast<Instruction>(U.getUser());
766 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
768 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
773 // If we know we're sinking Inst from an outer loop into an inner loop, then
774 // the *operands* of Inst don't need to be checked.
776 if (!Contains(OldLoop, NewLoop)) {
777 // See below on why we can't handle phi nodes here.
778 if (isa<PHINode>(Inst))
781 for (Use &U : Inst->operands()) {
782 auto *DefI = dyn_cast<Instruction>(U.get());
786 // This would need adjustment if we allow Inst to be a phi node -- the
787 // new use block won't simply be NewBB.
789 auto *DefBlock = DefI->getParent();
790 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
799 // Allow clients to walk the list of nested loops...
800 template <> struct GraphTraits<const Loop*> {
801 typedef const Loop *NodeRef;
802 typedef LoopInfo::iterator ChildIteratorType;
804 static NodeRef getEntryNode(const Loop *L) { return L; }
805 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
806 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
809 template <> struct GraphTraits<Loop*> {
810 typedef Loop *NodeRef;
811 typedef LoopInfo::iterator ChildIteratorType;
813 static NodeRef getEntryNode(Loop *L) { return L; }
814 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
815 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
818 /// \brief Analysis pass that exposes the \c LoopInfo for a function.
819 class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> {
820 friend AnalysisInfoMixin<LoopAnalysis>;
821 static AnalysisKey Key;
824 typedef LoopInfo Result;
826 LoopInfo run(Function &F, FunctionAnalysisManager &AM);
829 /// \brief Printer pass for the \c LoopAnalysis results.
830 class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> {
834 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
835 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
838 /// \brief Verifier pass for the \c LoopAnalysis results.
839 struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> {
840 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
843 /// \brief The legacy pass manager's analysis pass to compute loop information.
844 class LoopInfoWrapperPass : public FunctionPass {
848 static char ID; // Pass identification, replacement for typeid
850 LoopInfoWrapperPass() : FunctionPass(ID) {
851 initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
854 LoopInfo &getLoopInfo() { return LI; }
855 const LoopInfo &getLoopInfo() const { return LI; }
857 /// \brief Calculate the natural loop information for a given function.
858 bool runOnFunction(Function &F) override;
860 void verifyAnalysis() const override;
862 void releaseMemory() override { LI.releaseMemory(); }
864 void print(raw_ostream &O, const Module *M = nullptr) const override;
866 void getAnalysisUsage(AnalysisUsage &AU) const override;
869 /// Function to print a loop's contents as LLVM's text IR assembly.
870 void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner = "");
872 } // End llvm namespace