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 /// LoopBase class - Instances of this class are used to represent loops that
63 /// are detected in the flow graph
65 template<class BlockT, class LoopT>
68 // SubLoops - Loops contained entirely within this one.
69 std::vector<LoopT *> SubLoops;
71 // Blocks - 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 /// Loop ctor - This creates an empty loop.
84 LoopBase() : ParentLoop(nullptr) {}
86 for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
90 /// getLoopDepth - Return the nesting level of this loop. An outer-most
91 /// loop has depth 1, for consistency with loop depth values used for basic
92 /// blocks, where depth 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 /// setParentLoop is a raw interface for bypassing addChildLoop.
104 void setParentLoop(LoopT *L) { ParentLoop = L; }
106 /// contains - Return true if the specified loop is contained within in
109 bool contains(const LoopT *L) const {
110 if (L == this) return true;
111 if (!L) return false;
112 return contains(L->getParentLoop());
115 /// contains - Return true if the specified basic block is in this loop.
117 bool contains(const BlockT *BB) const {
118 return DenseBlockSet.count(BB);
121 /// contains - Return true if the specified instruction is in this loop.
123 template<class InstT>
124 bool contains(const InstT *Inst) const {
125 return contains(Inst->getParent());
128 /// iterator/begin/end - Return the loops contained entirely within this loop.
130 const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
131 std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
132 typedef typename std::vector<LoopT *>::const_iterator iterator;
133 typedef typename std::vector<LoopT *>::const_reverse_iterator
135 iterator begin() const { return SubLoops.begin(); }
136 iterator end() const { return SubLoops.end(); }
137 reverse_iterator rbegin() const { return SubLoops.rbegin(); }
138 reverse_iterator rend() const { return SubLoops.rend(); }
139 bool empty() const { return SubLoops.empty(); }
141 /// getBlocks - Get a list of the basic blocks which make up this loop.
143 const std::vector<BlockT*> &getBlocks() const { return Blocks; }
144 typedef typename std::vector<BlockT*>::const_iterator block_iterator;
145 block_iterator block_begin() const { return Blocks.begin(); }
146 block_iterator block_end() const { return Blocks.end(); }
147 inline iterator_range<block_iterator> blocks() const {
148 return make_range(block_begin(), block_end());
151 /// getNumBlocks - Get the number of blocks in this loop in constant time.
152 unsigned getNumBlocks() const {
153 return Blocks.size();
156 /// Invalidate the loop, indicating that it is no longer a loop.
157 void invalidate() { IsInvalid = true; }
159 /// Return true if this loop is no longer valid.
160 bool isInvalid() { return IsInvalid; }
162 /// isLoopExiting - True if terminator in the block can branch to another
163 /// block that is outside of the current loop.
165 bool isLoopExiting(const BlockT *BB) const {
166 typedef GraphTraits<const BlockT*> BlockTraits;
167 for (typename BlockTraits::ChildIteratorType SI =
168 BlockTraits::child_begin(BB),
169 SE = BlockTraits::child_end(BB); SI != SE; ++SI) {
176 /// getNumBackEdges - Calculate the number of back edges to the loop header
178 unsigned getNumBackEdges() const {
179 unsigned NumBackEdges = 0;
180 BlockT *H = getHeader();
182 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
183 for (typename InvBlockTraits::ChildIteratorType I =
184 InvBlockTraits::child_begin(H),
185 E = InvBlockTraits::child_end(H); I != E; ++I)
192 //===--------------------------------------------------------------------===//
193 // APIs for simple analysis of the loop.
195 // Note that all of these methods can fail on general loops (ie, there may not
196 // be a preheader, etc). For best success, the loop simplification and
197 // induction variable canonicalization pass should be used to normalize loops
198 // for easy analysis. These methods assume canonical loops.
200 /// getExitingBlocks - Return all blocks inside the loop that have successors
201 /// outside of the loop. These are the blocks _inside of the current loop_
202 /// which branch out. The returned list is always unique.
204 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
206 /// getExitingBlock - If getExitingBlocks would return exactly one block,
207 /// return that block. Otherwise return null.
208 BlockT *getExitingBlock() const;
210 /// getExitBlocks - Return all of the successor blocks of this loop. These
211 /// are the blocks _outside of the current loop_ which are branched to.
213 void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
215 /// getExitBlock - If getExitBlocks would return exactly one block,
216 /// return that block. Otherwise return null.
217 BlockT *getExitBlock() const;
220 typedef std::pair<const BlockT*, const BlockT*> Edge;
222 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
223 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
225 /// getLoopPreheader - If there is a preheader for this loop, return it. A
226 /// loop has a preheader if there is only one edge to the header of the loop
227 /// from outside of the loop. If this is the case, the block branching to the
228 /// header of the loop is the preheader node.
230 /// This method returns null if there is no preheader for the loop.
232 BlockT *getLoopPreheader() const;
234 /// getLoopPredecessor - If the given loop's header has exactly one unique
235 /// predecessor outside the loop, return it. Otherwise return null.
236 /// This is less strict that the loop "preheader" concept, which requires
237 /// the predecessor to have exactly one successor.
239 BlockT *getLoopPredecessor() const;
241 /// getLoopLatch - If there is a single latch block for this loop, return it.
242 /// A latch block is a block that contains a branch back to the header.
243 BlockT *getLoopLatch() const;
245 /// getLoopLatches - Return all loop latch blocks of this loop. A latch block
246 /// is a block that contains a branch back to the header.
247 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
248 BlockT *H = getHeader();
249 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
250 for (typename InvBlockTraits::ChildIteratorType I =
251 InvBlockTraits::child_begin(H),
252 E = InvBlockTraits::child_end(H); I != E; ++I)
254 LoopLatches.push_back(*I);
257 //===--------------------------------------------------------------------===//
258 // APIs for updating loop information after changing the CFG
261 /// addBasicBlockToLoop - This method is used by other analyses to update loop
262 /// information. NewBB is set to be a new member of the current loop.
263 /// Because of this, it is added as a member of all parent loops, and is added
264 /// to the specified LoopInfo object as being in the current basic block. It
265 /// is not valid to replace the loop header with this method.
267 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
269 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
270 /// the OldChild entry in our children list with NewChild, and updates the
271 /// parent pointer of OldChild to be null and the NewChild to be this loop.
272 /// This updates the loop depth of the new child.
273 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
275 /// addChildLoop - Add the specified loop to be a child of this loop. This
276 /// updates the loop depth of the new child.
278 void addChildLoop(LoopT *NewChild) {
279 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
280 NewChild->ParentLoop = static_cast<LoopT *>(this);
281 SubLoops.push_back(NewChild);
284 /// removeChildLoop - This removes the specified child from being a subloop of
285 /// this loop. The loop is not deleted, as it will presumably be inserted
286 /// into another loop.
287 LoopT *removeChildLoop(iterator I) {
288 assert(I != SubLoops.end() && "Cannot remove end iterator!");
290 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
291 SubLoops.erase(SubLoops.begin()+(I-begin()));
292 Child->ParentLoop = nullptr;
296 /// addBlockEntry - This adds a basic block directly to the basic block list.
297 /// This should only be used by transformations that create new loops. Other
298 /// transformations should use addBasicBlockToLoop.
299 void addBlockEntry(BlockT *BB) {
300 Blocks.push_back(BB);
301 DenseBlockSet.insert(BB);
304 /// reverseBlocks - interface to reverse Blocks[from, end of loop] in this loop
305 void reverseBlock(unsigned from) {
306 std::reverse(Blocks.begin() + from, Blocks.end());
309 /// reserveBlocks- interface to do reserve() for Blocks
310 void reserveBlocks(unsigned size) {
311 Blocks.reserve(size);
314 /// moveToHeader - This method is used to move BB (which must be part of this
315 /// loop) to be the loop header of the loop (the block that dominates all
317 void moveToHeader(BlockT *BB) {
318 if (Blocks[0] == BB) return;
319 for (unsigned i = 0; ; ++i) {
320 assert(i != Blocks.size() && "Loop does not contain BB!");
321 if (Blocks[i] == BB) {
322 Blocks[i] = Blocks[0];
329 /// removeBlockFromLoop - This removes the specified basic block from the
330 /// current loop, updating the Blocks as appropriate. This does not update
331 /// the mapping in the LoopInfo class.
332 void removeBlockFromLoop(BlockT *BB) {
333 auto I = std::find(Blocks.begin(), Blocks.end(), BB);
334 assert(I != Blocks.end() && "N is not in this list!");
337 DenseBlockSet.erase(BB);
340 /// verifyLoop - Verify loop structure
341 void verifyLoop() const;
343 /// verifyLoop - Verify loop structure of this loop and all nested loops.
344 void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
346 void print(raw_ostream &OS, unsigned Depth = 0) const;
349 friend class LoopInfoBase<BlockT, LoopT>;
350 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
351 Blocks.push_back(BB);
352 DenseBlockSet.insert(BB);
356 template<class BlockT, class LoopT>
357 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
362 // Implementation in LoopInfoImpl.h
363 extern template class LoopBase<BasicBlock, Loop>;
365 class Loop : public LoopBase<BasicBlock, Loop> {
369 /// isLoopInvariant - Return true if the specified value is loop invariant
371 bool isLoopInvariant(const Value *V) const;
373 /// hasLoopInvariantOperands - Return true if all the operands of the
374 /// specified instruction are loop invariant.
375 bool hasLoopInvariantOperands(const Instruction *I) const;
377 /// makeLoopInvariant - If the given value is an instruction inside of the
378 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
379 /// Return true if the value after any hoisting is loop invariant. This
380 /// function can be used as a slightly more aggressive replacement for
383 /// If InsertPt is specified, it is the point to hoist instructions to.
384 /// If null, the terminator of the loop preheader is used.
386 bool makeLoopInvariant(Value *V, bool &Changed,
387 Instruction *InsertPt = nullptr) const;
389 /// makeLoopInvariant - If the given instruction is inside of the
390 /// loop and it can be hoisted, do so to make it trivially loop-invariant.
391 /// Return true if the instruction after any hoisting is loop invariant. This
392 /// function can be used as a slightly more aggressive replacement for
395 /// If InsertPt is specified, it is the point to hoist instructions to.
396 /// If null, the terminator of the loop preheader is used.
398 bool makeLoopInvariant(Instruction *I, bool &Changed,
399 Instruction *InsertPt = nullptr) const;
401 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
402 /// induction variable: an integer recurrence that starts at 0 and increments
403 /// by one each time through the loop. If so, return the phi node that
404 /// corresponds to it.
406 /// The IndVarSimplify pass transforms loops to have a canonical induction
409 PHINode *getCanonicalInductionVariable() const;
411 /// isLCSSAForm - Return true if the Loop is in LCSSA form
412 bool isLCSSAForm(DominatorTree &DT) const;
414 /// \brief Return true if this Loop and all inner subloops are in LCSSA form.
415 bool isRecursivelyLCSSAForm(DominatorTree &DT) const;
417 /// isLoopSimplifyForm - Return true if the Loop is in the form that
418 /// the LoopSimplify form transforms loops to, which is sometimes called
420 bool isLoopSimplifyForm() const;
422 /// isSafeToClone - Return true if the loop body is safe to clone in practice.
423 bool isSafeToClone() const;
425 /// Returns true if the loop is annotated parallel.
427 /// A parallel loop can be assumed to not contain any dependencies between
428 /// iterations by the compiler. That is, any loop-carried dependency checking
429 /// can be skipped completely when parallelizing the loop on the target
430 /// machine. Thus, if the parallel loop information originates from the
431 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
432 /// programmer's responsibility to ensure there are no loop-carried
433 /// dependencies. The final execution order of the instructions across
434 /// iterations is not guaranteed, thus, the end result might or might not
435 /// implement actual concurrent execution of instructions across multiple
437 bool isAnnotatedParallel() const;
439 /// Return the llvm.loop loop id metadata node for this loop if it is present.
441 /// If this loop contains the same llvm.loop metadata on each branch to the
442 /// header then the node is returned. If any latch instruction does not
443 /// contain llvm.loop or or if multiple latches contain different nodes then
445 MDNode *getLoopID() const;
446 /// Set the llvm.loop loop id metadata for this loop.
448 /// The LoopID metadata node will be added to each terminator instruction in
449 /// the loop that branches to the loop header.
451 /// The LoopID metadata node should have one or more operands and the first
452 /// operand should should be the node itself.
453 void setLoopID(MDNode *LoopID) const;
455 /// hasDedicatedExits - Return true if no exit block for the loop
456 /// has a predecessor that is outside the loop.
457 bool hasDedicatedExits() const;
459 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
460 /// These are the blocks _outside of the current loop_ which are branched to.
461 /// This assumes that loop exits are in canonical form.
463 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
465 /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
466 /// block, return that block. Otherwise return null.
467 BasicBlock *getUniqueExitBlock() const;
471 /// \brief Return the debug location of the start of this loop.
472 /// This looks for a BB terminating instruction with a known debug
473 /// location by looking at the preheader and header blocks. If it
474 /// cannot find a terminating instruction with location information,
475 /// it returns an unknown location.
476 DebugLoc getStartLoc() const {
479 // Try the pre-header first.
480 if ((HeadBB = getLoopPreheader()) != nullptr)
481 if (DebugLoc DL = HeadBB->getTerminator()->getDebugLoc())
484 // If we have no pre-header or there are no instructions with debug
485 // info in it, try the header.
486 HeadBB = getHeader();
488 return HeadBB->getTerminator()->getDebugLoc();
494 friend class LoopInfoBase<BasicBlock, Loop>;
495 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
498 //===----------------------------------------------------------------------===//
499 /// LoopInfo - This class builds and contains all of the top level loop
500 /// structures in the specified function.
503 template<class BlockT, class LoopT>
505 // BBMap - Mapping of basic blocks to the inner most loop they occur in
506 DenseMap<const BlockT *, LoopT *> BBMap;
507 std::vector<LoopT *> TopLevelLoops;
508 std::vector<LoopT *> RemovedLoops;
510 friend class LoopBase<BlockT, LoopT>;
511 friend class LoopInfo;
513 void operator=(const LoopInfoBase &) = delete;
514 LoopInfoBase(const LoopInfoBase &) = delete;
517 ~LoopInfoBase() { releaseMemory(); }
519 LoopInfoBase(LoopInfoBase &&Arg)
520 : BBMap(std::move(Arg.BBMap)),
521 TopLevelLoops(std::move(Arg.TopLevelLoops)) {
522 // We have to clear the arguments top level loops as we've taken ownership.
523 Arg.TopLevelLoops.clear();
525 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
526 BBMap = std::move(RHS.BBMap);
528 for (auto *L : TopLevelLoops)
530 TopLevelLoops = std::move(RHS.TopLevelLoops);
531 RHS.TopLevelLoops.clear();
535 void releaseMemory() {
538 for (auto *L : TopLevelLoops)
540 TopLevelLoops.clear();
541 for (auto *L : RemovedLoops)
543 RemovedLoops.clear();
546 /// iterator/begin/end - The interface to the top-level loops in the current
549 typedef typename std::vector<LoopT *>::const_iterator iterator;
550 typedef typename std::vector<LoopT *>::const_reverse_iterator
552 iterator begin() const { return TopLevelLoops.begin(); }
553 iterator end() const { return TopLevelLoops.end(); }
554 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
555 reverse_iterator rend() const { return TopLevelLoops.rend(); }
556 bool empty() const { return TopLevelLoops.empty(); }
558 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
559 /// block is in no loop (for example the entry node), null is returned.
561 LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
563 /// operator[] - same as getLoopFor...
565 const LoopT *operator[](const BlockT *BB) const {
566 return getLoopFor(BB);
569 /// getLoopDepth - Return the loop nesting level of the specified block. A
570 /// depth of 0 means the block is not inside any loop.
572 unsigned getLoopDepth(const BlockT *BB) const {
573 const LoopT *L = getLoopFor(BB);
574 return L ? L->getLoopDepth() : 0;
577 // isLoopHeader - True if the block is a loop header node
578 bool isLoopHeader(const BlockT *BB) const {
579 const LoopT *L = getLoopFor(BB);
580 return L && L->getHeader() == BB;
583 /// removeLoop - This removes the specified top-level loop from this loop info
584 /// object. The loop is not deleted, as it will presumably be inserted into
586 LoopT *removeLoop(iterator I) {
587 assert(I != end() && "Cannot remove end iterator!");
589 assert(!L->getParentLoop() && "Not a top-level loop!");
590 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
594 /// changeLoopFor - Change the top-level loop that contains BB to the
595 /// specified loop. This should be used by transformations that restructure
596 /// the loop hierarchy tree.
597 void changeLoopFor(BlockT *BB, LoopT *L) {
605 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
606 /// list with the indicated loop.
607 void changeTopLevelLoop(LoopT *OldLoop,
609 auto I = std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
610 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
612 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
613 "Loops already embedded into a subloop!");
616 /// addTopLevelLoop - This adds the specified loop to the collection of
618 void addTopLevelLoop(LoopT *New) {
619 assert(!New->getParentLoop() && "Loop already in subloop!");
620 TopLevelLoops.push_back(New);
623 /// removeBlock - This method completely removes BB from all data structures,
624 /// including all of the Loop objects it is nested in and our mapping from
625 /// BasicBlocks to loops.
626 void removeBlock(BlockT *BB) {
627 auto I = BBMap.find(BB);
628 if (I != BBMap.end()) {
629 for (LoopT *L = I->second; L; L = L->getParentLoop())
630 L->removeBlockFromLoop(BB);
638 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
639 const LoopT *ParentLoop) {
640 if (!SubLoop) return true;
641 if (SubLoop == ParentLoop) return false;
642 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
645 /// Create the loop forest using a stable algorithm.
646 void analyze(const DominatorTreeBase<BlockT> &DomTree);
649 void print(raw_ostream &OS) const;
654 // Implementation in LoopInfoImpl.h
655 extern template class LoopInfoBase<BasicBlock, Loop>;
657 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
658 typedef LoopInfoBase<BasicBlock, Loop> BaseT;
660 friend class LoopBase<BasicBlock, Loop>;
662 void operator=(const LoopInfo &) = delete;
663 LoopInfo(const LoopInfo &) = delete;
666 explicit LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree);
668 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
669 LoopInfo &operator=(LoopInfo &&RHS) {
670 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
674 // Most of the public interface is provided via LoopInfoBase.
676 /// Update LoopInfo after removing the last backedge from a loop. This updates
677 /// the loop forest and parent loops for each block so that \c L is no longer
678 /// referenced, but does not actually delete \c L immediately. The pointer
679 /// will remain valid until this LoopInfo's memory is released.
680 void markAsRemoved(Loop *L);
682 /// replacementPreservesLCSSAForm - Returns true if replacing From with To
683 /// everywhere is guaranteed to preserve LCSSA form.
684 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
685 // Preserving LCSSA form is only problematic if the replacing value is an
687 Instruction *I = dyn_cast<Instruction>(To);
689 // If both instructions are defined in the same basic block then replacement
690 // cannot break LCSSA form.
691 if (I->getParent() == From->getParent())
693 // If the instruction is not defined in a loop then it can safely replace
695 Loop *ToLoop = getLoopFor(I->getParent());
696 if (!ToLoop) return true;
697 // If the replacing instruction is defined in the same loop as the original
698 // instruction, or in a loop that contains it as an inner loop, then using
699 // it as a replacement will not break LCSSA form.
700 return ToLoop->contains(getLoopFor(From->getParent()));
703 /// \brief Checks if moving a specific instruction can break LCSSA in any
706 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
707 /// assuming that the function containing \p Inst and \p NewLoc is currently
709 bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
710 assert(Inst->getFunction() == NewLoc->getFunction() &&
711 "Can't reason about IPO!");
713 auto *OldBB = Inst->getParent();
714 auto *NewBB = NewLoc->getParent();
716 // Movement within the same loop does not break LCSSA (the equality check is
717 // to avoid doing a hashtable lookup in case of intra-block movement).
721 auto *OldLoop = getLoopFor(OldBB);
722 auto *NewLoop = getLoopFor(NewBB);
724 if (OldLoop == NewLoop)
727 // Check if Outer contains Inner; with the null loop counting as the
729 auto Contains = [](const Loop *Outer, const Loop *Inner) {
730 return !Outer || Outer->contains(Inner);
733 // To check that the movement of Inst to before NewLoc does not break LCSSA,
734 // we need to check two sets of uses for possible LCSSA violations at
735 // NewLoc: the users of NewInst, and the operands of NewInst.
737 // If we know we're hoisting Inst out of an inner loop to an outer loop,
738 // then the uses *of* Inst don't need to be checked.
740 if (!Contains(NewLoop, OldLoop)) {
741 for (Use &U : Inst->uses()) {
742 auto *UI = cast<Instruction>(U.getUser());
743 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
745 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
750 // If we know we're sinking Inst from an outer loop into an inner loop, then
751 // the *operands* of Inst don't need to be checked.
753 if (!Contains(OldLoop, NewLoop)) {
754 // See below on why we can't handle phi nodes here.
755 if (isa<PHINode>(Inst))
758 for (Use &U : Inst->operands()) {
759 auto *DefI = dyn_cast<Instruction>(U.get());
763 // This would need adjustment if we allow Inst to be a phi node -- the
764 // new use block won't simply be NewBB.
766 auto *DefBlock = DefI->getParent();
767 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
776 // Allow clients to walk the list of nested loops...
777 template <> struct GraphTraits<const Loop*> {
778 typedef const Loop NodeType;
779 typedef LoopInfo::iterator ChildIteratorType;
781 static NodeType *getEntryNode(const Loop *L) { return L; }
782 static inline ChildIteratorType child_begin(NodeType *N) {
785 static inline ChildIteratorType child_end(NodeType *N) {
790 template <> struct GraphTraits<Loop*> {
791 typedef Loop NodeType;
792 typedef LoopInfo::iterator ChildIteratorType;
794 static NodeType *getEntryNode(Loop *L) { return L; }
795 static inline ChildIteratorType child_begin(NodeType *N) {
798 static inline ChildIteratorType child_end(NodeType *N) {
803 /// \brief Analysis pass that exposes the \c LoopInfo for a function.
808 typedef LoopInfo Result;
810 /// \brief Opaque, unique identifier for this analysis pass.
811 static void *ID() { return (void *)&PassID; }
813 /// \brief Provide a name for the analysis for debugging and logging.
814 static StringRef name() { return "LoopAnalysis"; }
816 LoopInfo run(Function &F, AnalysisManager<Function> *AM);
819 /// \brief Printer pass for the \c LoopAnalysis results.
820 class LoopPrinterPass {
824 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
825 PreservedAnalyses run(Function &F, AnalysisManager<Function> *AM);
827 static StringRef name() { return "LoopPrinterPass"; }
830 /// \brief The legacy pass manager's analysis pass to compute loop information.
831 class LoopInfoWrapperPass : public FunctionPass {
835 static char ID; // Pass identification, replacement for typeid
837 LoopInfoWrapperPass() : FunctionPass(ID) {
838 initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
841 LoopInfo &getLoopInfo() { return LI; }
842 const LoopInfo &getLoopInfo() const { return LI; }
844 /// \brief Calculate the natural loop information for a given function.
845 bool runOnFunction(Function &F) override;
847 void verifyAnalysis() const override;
849 void releaseMemory() override { LI.releaseMemory(); }
851 void print(raw_ostream &O, const Module *M = nullptr) const override;
853 void getAnalysisUsage(AnalysisUsage &AU) const override;
856 /// \brief Pass for printing a loop's contents as LLVM's text IR assembly.
857 class PrintLoopPass {
863 PrintLoopPass(raw_ostream &OS, const std::string &Banner = "");
865 PreservedAnalyses run(Loop &L);
866 static StringRef name() { return "PrintLoopPass"; }
869 } // End llvm namespace