Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / Analysis / LoopInfo.h
blob0899630fe8ead5c3435dc845f0dc11c2c4444cd4
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.
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.
18 // It can calculate on the fly various bits of information, for example:
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...
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.
33 //===----------------------------------------------------------------------===//
35 #ifndef LLVM_ANALYSIS_LOOPINFO_H
36 #define LLVM_ANALYSIS_LOOPINFO_H
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>
52 namespace llvm {
54 class DominatorTree;
55 class LoopInfo;
56 class Loop;
57 class MDNode;
58 class PHINode;
59 class raw_ostream;
60 template <class N, bool IsPostDom> class DominatorTreeBase;
61 template <class N, class M> class LoopInfoBase;
62 template <class N, class M> class LoopBase;
64 //===----------------------------------------------------------------------===//
65 /// Instances of this class are used to represent loops that are detected in the
66 /// flow graph.
67 ///
68 template <class BlockT, class LoopT> class LoopBase {
69 LoopT *ParentLoop;
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 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
79 /// Indicator that this loop is no longer a valid loop.
80 bool IsInvalid = false;
81 #endif
83 LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
84 const LoopBase<BlockT, LoopT> &
85 operator=(const LoopBase<BlockT, LoopT> &) = delete;
87 public:
88 /// Return the nesting level of this loop. An outer-most loop has depth 1,
89 /// for consistency with loop depth values used for basic blocks, where depth
90 /// 0 is used for blocks not inside any loops.
91 unsigned getLoopDepth() const {
92 assert(!isInvalid() && "Loop not in a valid state!");
93 unsigned D = 1;
94 for (const LoopT *CurLoop = ParentLoop; CurLoop;
95 CurLoop = CurLoop->ParentLoop)
96 ++D;
97 return D;
99 BlockT *getHeader() const { return getBlocks().front(); }
100 LoopT *getParentLoop() const { return ParentLoop; }
102 /// This is a raw interface for bypassing addChildLoop.
103 void setParentLoop(LoopT *L) {
104 assert(!isInvalid() && "Loop not in a valid state!");
105 ParentLoop = L;
108 /// Return true if the specified loop is contained within in this loop.
109 bool contains(const LoopT *L) const {
110 assert(!isInvalid() && "Loop not in a valid state!");
111 if (L == this)
112 return true;
113 if (!L)
114 return false;
115 return contains(L->getParentLoop());
118 /// Return true if the specified basic block is in this loop.
119 bool contains(const BlockT *BB) const {
120 assert(!isInvalid() && "Loop not in a valid state!");
121 return DenseBlockSet.count(BB);
124 /// Return true if the specified instruction is in this loop.
125 template <class InstT> bool contains(const InstT *Inst) const {
126 return contains(Inst->getParent());
129 /// Return the loops contained entirely within this loop.
130 const std::vector<LoopT *> &getSubLoops() const {
131 assert(!isInvalid() && "Loop not in a valid state!");
132 return SubLoops;
134 std::vector<LoopT *> &getSubLoopsVector() {
135 assert(!isInvalid() && "Loop not in a valid state!");
136 return SubLoops;
138 typedef typename std::vector<LoopT *>::const_iterator iterator;
139 typedef
140 typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
141 iterator begin() const { return getSubLoops().begin(); }
142 iterator end() const { return getSubLoops().end(); }
143 reverse_iterator rbegin() const { return getSubLoops().rbegin(); }
144 reverse_iterator rend() const { return getSubLoops().rend(); }
145 bool empty() const { return getSubLoops().empty(); }
147 /// Get a list of the basic blocks which make up this loop.
148 ArrayRef<BlockT *> getBlocks() const {
149 assert(!isInvalid() && "Loop not in a valid state!");
150 return Blocks;
152 typedef typename ArrayRef<BlockT *>::const_iterator block_iterator;
153 block_iterator block_begin() const { return getBlocks().begin(); }
154 block_iterator block_end() const { return getBlocks().end(); }
155 inline iterator_range<block_iterator> blocks() const {
156 assert(!isInvalid() && "Loop not in a valid state!");
157 return make_range(block_begin(), block_end());
160 /// Get the number of blocks in this loop in constant time.
161 /// Invalidate the loop, indicating that it is no longer a loop.
162 unsigned getNumBlocks() const {
163 assert(!isInvalid() && "Loop not in a valid state!");
164 return Blocks.size();
167 /// Return a direct, mutable handle to the blocks vector so that we can
168 /// mutate it efficiently with techniques like `std::remove`.
169 std::vector<BlockT *> &getBlocksVector() {
170 assert(!isInvalid() && "Loop not in a valid state!");
171 return Blocks;
173 /// Return a direct, mutable handle to the blocks set so that we can
174 /// mutate it efficiently.
175 SmallPtrSetImpl<const BlockT *> &getBlocksSet() {
176 assert(!isInvalid() && "Loop not in a valid state!");
177 return DenseBlockSet;
180 /// Return a direct, immutable handle to the blocks set.
181 const SmallPtrSetImpl<const BlockT *> &getBlocksSet() const {
182 assert(!isInvalid() && "Loop not in a valid state!");
183 return DenseBlockSet;
186 /// Return true if this loop is no longer valid. The only valid use of this
187 /// helper is "assert(L.isInvalid())" or equivalent, since IsInvalid is set to
188 /// true by the destructor. In other words, if this accessor returns true,
189 /// the caller has already triggered UB by calling this accessor; and so it
190 /// can only be called in a context where a return value of true indicates a
191 /// programmer error.
192 bool isInvalid() const {
193 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
194 return IsInvalid;
195 #else
196 return false;
197 #endif
200 /// True if terminator in the block can branch to another block that is
201 /// outside of the current loop.
202 bool isLoopExiting(const BlockT *BB) const {
203 assert(!isInvalid() && "Loop not in a valid state!");
204 for (const auto &Succ : children<const BlockT *>(BB)) {
205 if (!contains(Succ))
206 return true;
208 return false;
211 /// Returns true if \p BB is a loop-latch.
212 /// A latch block is a block that contains a branch back to the header.
213 /// This function is useful when there are multiple latches in a loop
214 /// because \fn getLoopLatch will return nullptr in that case.
215 bool isLoopLatch(const BlockT *BB) const {
216 assert(!isInvalid() && "Loop not in a valid state!");
217 assert(contains(BB) && "block does not belong to the loop");
219 BlockT *Header = getHeader();
220 auto PredBegin = GraphTraits<Inverse<BlockT *>>::child_begin(Header);
221 auto PredEnd = GraphTraits<Inverse<BlockT *>>::child_end(Header);
222 return std::find(PredBegin, PredEnd, BB) != PredEnd;
225 /// Calculate the number of back edges to the loop header.
226 unsigned getNumBackEdges() const {
227 assert(!isInvalid() && "Loop not in a valid state!");
228 unsigned NumBackEdges = 0;
229 BlockT *H = getHeader();
231 for (const auto Pred : children<Inverse<BlockT *>>(H))
232 if (contains(Pred))
233 ++NumBackEdges;
235 return NumBackEdges;
238 //===--------------------------------------------------------------------===//
239 // APIs for simple analysis of the loop.
241 // Note that all of these methods can fail on general loops (ie, there may not
242 // be a preheader, etc). For best success, the loop simplification and
243 // induction variable canonicalization pass should be used to normalize loops
244 // for easy analysis. These methods assume canonical loops.
246 /// Return all blocks inside the loop that have successors outside of the
247 /// loop. These are the blocks _inside of the current loop_ which branch out.
248 /// The returned list is always unique.
249 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
251 /// If getExitingBlocks would return exactly one block, return that block.
252 /// Otherwise return null.
253 BlockT *getExitingBlock() const;
255 /// Return all of the successor blocks of this loop. These are the blocks
256 /// _outside of the current loop_ which are branched to.
257 void getExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
259 /// If getExitBlocks would return exactly one block, return that block.
260 /// Otherwise return null.
261 BlockT *getExitBlock() const;
263 /// Return true if no exit block for the loop has a predecessor that is
264 /// outside the loop.
265 bool hasDedicatedExits() const;
267 /// Return all unique successor blocks of this loop.
268 /// These are the blocks _outside of the current loop_ which are branched to.
269 /// This assumes that loop exits are in canonical form, i.e. all exits are
270 /// dedicated exits.
271 void getUniqueExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
273 /// If getUniqueExitBlocks would return exactly one block, return that block.
274 /// Otherwise return null.
275 BlockT *getUniqueExitBlock() const;
277 /// Edge type.
278 typedef std::pair<const BlockT *, const BlockT *> Edge;
280 /// Return all pairs of (_inside_block_,_outside_block_).
281 void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
283 /// If there is a preheader for this loop, return it. A loop has a preheader
284 /// if there is only one edge to the header of the loop from outside of the
285 /// loop. If this is the case, the block branching to the header of the loop
286 /// is the preheader node.
288 /// This method returns null if there is no preheader for the loop.
289 BlockT *getLoopPreheader() const;
291 /// If the given loop's header has exactly one unique predecessor outside the
292 /// loop, return it. Otherwise return null.
293 /// This is less strict that the loop "preheader" concept, which requires
294 /// the predecessor to have exactly one successor.
295 BlockT *getLoopPredecessor() const;
297 /// If there is a single latch block for this loop, return it.
298 /// A latch block is a block that contains a branch back to the header.
299 BlockT *getLoopLatch() const;
301 /// Return all loop latch blocks of this loop. A latch block is a block that
302 /// contains a branch back to the header.
303 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
304 assert(!isInvalid() && "Loop not in a valid state!");
305 BlockT *H = getHeader();
306 for (const auto Pred : children<Inverse<BlockT *>>(H))
307 if (contains(Pred))
308 LoopLatches.push_back(Pred);
311 //===--------------------------------------------------------------------===//
312 // APIs for updating loop information after changing the CFG
315 /// This method is used by other analyses to update loop information.
316 /// NewBB is set to be a new member of the current loop.
317 /// Because of this, it is added as a member of all parent loops, and is added
318 /// to the specified LoopInfo object as being in the current basic block. It
319 /// is not valid to replace the loop header with this method.
320 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
322 /// This is used when splitting loops up. It replaces the OldChild entry in
323 /// our children list with NewChild, and updates the parent pointer of
324 /// OldChild to be null and the NewChild to be this loop.
325 /// This updates the loop depth of the new child.
326 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
328 /// Add the specified loop to be a child of this loop.
329 /// This updates the loop depth of the new child.
330 void addChildLoop(LoopT *NewChild) {
331 assert(!isInvalid() && "Loop not in a valid state!");
332 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
333 NewChild->ParentLoop = static_cast<LoopT *>(this);
334 SubLoops.push_back(NewChild);
337 /// This removes the specified child from being a subloop of this loop. The
338 /// loop is not deleted, as it will presumably be inserted into another loop.
339 LoopT *removeChildLoop(iterator I) {
340 assert(!isInvalid() && "Loop not in a valid state!");
341 assert(I != SubLoops.end() && "Cannot remove end iterator!");
342 LoopT *Child = *I;
343 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
344 SubLoops.erase(SubLoops.begin() + (I - begin()));
345 Child->ParentLoop = nullptr;
346 return Child;
349 /// This removes the specified child from being a subloop of this loop. The
350 /// loop is not deleted, as it will presumably be inserted into another loop.
351 LoopT *removeChildLoop(LoopT *Child) {
352 return removeChildLoop(llvm::find(*this, Child));
355 /// This adds a basic block directly to the basic block list.
356 /// This should only be used by transformations that create new loops. Other
357 /// transformations should use addBasicBlockToLoop.
358 void addBlockEntry(BlockT *BB) {
359 assert(!isInvalid() && "Loop not in a valid state!");
360 Blocks.push_back(BB);
361 DenseBlockSet.insert(BB);
364 /// interface to reverse Blocks[from, end of loop] in this loop
365 void reverseBlock(unsigned from) {
366 assert(!isInvalid() && "Loop not in a valid state!");
367 std::reverse(Blocks.begin() + from, Blocks.end());
370 /// interface to do reserve() for Blocks
371 void reserveBlocks(unsigned size) {
372 assert(!isInvalid() && "Loop not in a valid state!");
373 Blocks.reserve(size);
376 /// This method is used to move BB (which must be part of this loop) to be the
377 /// loop header of the loop (the block that dominates all others).
378 void moveToHeader(BlockT *BB) {
379 assert(!isInvalid() && "Loop not in a valid state!");
380 if (Blocks[0] == BB)
381 return;
382 for (unsigned i = 0;; ++i) {
383 assert(i != Blocks.size() && "Loop does not contain BB!");
384 if (Blocks[i] == BB) {
385 Blocks[i] = Blocks[0];
386 Blocks[0] = BB;
387 return;
392 /// This removes the specified basic block from the current loop, updating the
393 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
394 /// class.
395 void removeBlockFromLoop(BlockT *BB) {
396 assert(!isInvalid() && "Loop not in a valid state!");
397 auto I = find(Blocks, BB);
398 assert(I != Blocks.end() && "N is not in this list!");
399 Blocks.erase(I);
401 DenseBlockSet.erase(BB);
404 /// Verify loop structure
405 void verifyLoop() const;
407 /// Verify loop structure of this loop and all nested loops.
408 void verifyLoopNest(DenseSet<const LoopT *> *Loops) const;
410 /// Returns true if the loop is annotated parallel.
412 /// Derived classes can override this method using static template
413 /// polymorphism.
414 bool isAnnotatedParallel() const { return false; }
416 /// Print loop with all the BBs inside it.
417 void print(raw_ostream &OS, unsigned Depth = 0, bool Verbose = false) const;
419 protected:
420 friend class LoopInfoBase<BlockT, LoopT>;
422 /// This creates an empty loop.
423 LoopBase() : ParentLoop(nullptr) {}
425 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
426 Blocks.push_back(BB);
427 DenseBlockSet.insert(BB);
430 // Since loop passes like SCEV are allowed to key analysis results off of
431 // `Loop` pointers, we cannot re-use pointers within a loop pass manager.
432 // This means loop passes should not be `delete` ing `Loop` objects directly
433 // (and risk a later `Loop` allocation re-using the address of a previous one)
434 // but should be using LoopInfo::markAsRemoved, which keeps around the `Loop`
435 // pointer till the end of the lifetime of the `LoopInfo` object.
437 // To make it easier to follow this rule, we mark the destructor as
438 // non-public.
439 ~LoopBase() {
440 for (auto *SubLoop : SubLoops)
441 SubLoop->~LoopT();
443 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
444 IsInvalid = true;
445 #endif
446 SubLoops.clear();
447 Blocks.clear();
448 DenseBlockSet.clear();
449 ParentLoop = nullptr;
453 template <class BlockT, class LoopT>
454 raw_ostream &operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
455 Loop.print(OS);
456 return OS;
459 // Implementation in LoopInfoImpl.h
460 extern template class LoopBase<BasicBlock, Loop>;
462 /// Represents a single loop in the control flow graph. Note that not all SCCs
463 /// in the CFG are necessarily loops.
464 class Loop : public LoopBase<BasicBlock, Loop> {
465 public:
466 /// A range representing the start and end location of a loop.
467 class LocRange {
468 DebugLoc Start;
469 DebugLoc End;
471 public:
472 LocRange() {}
473 LocRange(DebugLoc Start) : Start(std::move(Start)), End(std::move(Start)) {}
474 LocRange(DebugLoc Start, DebugLoc End)
475 : Start(std::move(Start)), End(std::move(End)) {}
477 const DebugLoc &getStart() const { return Start; }
478 const DebugLoc &getEnd() const { return End; }
480 /// Check for null.
482 explicit operator bool() const { return Start && End; }
485 /// Return true if the specified value is loop invariant.
486 bool isLoopInvariant(const Value *V) const;
488 /// Return true if all the operands of the specified instruction are loop
489 /// invariant.
490 bool hasLoopInvariantOperands(const Instruction *I) const;
492 /// If the given value is an instruction inside of the loop and it can be
493 /// hoisted, do so to make it trivially loop-invariant.
494 /// Return true if the value after any hoisting is loop invariant. This
495 /// function can be used as a slightly more aggressive replacement for
496 /// isLoopInvariant.
498 /// If InsertPt is specified, it is the point to hoist instructions to.
499 /// If null, the terminator of the loop preheader is used.
500 bool makeLoopInvariant(Value *V, bool &Changed,
501 Instruction *InsertPt = nullptr) const;
503 /// If the given instruction is inside of the loop and it can be hoisted, do
504 /// so to make it trivially loop-invariant.
505 /// Return true if the instruction after any hoisting is loop invariant. This
506 /// function can be used as a slightly more aggressive replacement for
507 /// isLoopInvariant.
509 /// If InsertPt is specified, it is the point to hoist instructions to.
510 /// If null, the terminator of the loop preheader is used.
512 bool makeLoopInvariant(Instruction *I, bool &Changed,
513 Instruction *InsertPt = nullptr) const;
515 /// Check to see if the loop has a canonical induction variable: an integer
516 /// recurrence that starts at 0 and increments by one each time through the
517 /// loop. If so, return the phi node that corresponds to it.
519 /// The IndVarSimplify pass transforms loops to have a canonical induction
520 /// variable.
522 PHINode *getCanonicalInductionVariable() const;
524 /// Return true if the Loop is in LCSSA form.
525 bool isLCSSAForm(DominatorTree &DT) const;
527 /// Return true if this Loop and all inner subloops are in LCSSA form.
528 bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const;
530 /// Return true if the Loop is in the form that the LoopSimplify form
531 /// transforms loops to, which is sometimes called normal form.
532 bool isLoopSimplifyForm() const;
534 /// Return true if the loop body is safe to clone in practice.
535 bool isSafeToClone() const;
537 /// Returns true if the loop is annotated parallel.
539 /// A parallel loop can be assumed to not contain any dependencies between
540 /// iterations by the compiler. That is, any loop-carried dependency checking
541 /// can be skipped completely when parallelizing the loop on the target
542 /// machine. Thus, if the parallel loop information originates from the
543 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
544 /// programmer's responsibility to ensure there are no loop-carried
545 /// dependencies. The final execution order of the instructions across
546 /// iterations is not guaranteed, thus, the end result might or might not
547 /// implement actual concurrent execution of instructions across multiple
548 /// iterations.
549 bool isAnnotatedParallel() const;
551 /// Return the llvm.loop loop id metadata node for this loop if it is present.
553 /// If this loop contains the same llvm.loop metadata on each branch to the
554 /// header then the node is returned. If any latch instruction does not
555 /// contain llvm.loop or if multiple latches contain different nodes then
556 /// 0 is returned.
557 MDNode *getLoopID() const;
558 /// Set the llvm.loop loop id metadata for this loop.
560 /// The LoopID metadata node will be added to each terminator instruction in
561 /// the loop that branches to the loop header.
563 /// The LoopID metadata node should have one or more operands and the first
564 /// operand should be the node itself.
565 void setLoopID(MDNode *LoopID) const;
567 /// Add llvm.loop.unroll.disable to this loop's loop id metadata.
569 /// Remove existing unroll metadata and add unroll disable metadata to
570 /// indicate the loop has already been unrolled. This prevents a loop
571 /// from being unrolled more than is directed by a pragma if the loop
572 /// unrolling pass is run more than once (which it generally is).
573 void setLoopAlreadyUnrolled();
575 void dump() const;
576 void dumpVerbose() const;
578 /// Return the debug location of the start of this loop.
579 /// This looks for a BB terminating instruction with a known debug
580 /// location by looking at the preheader and header blocks. If it
581 /// cannot find a terminating instruction with location information,
582 /// it returns an unknown location.
583 DebugLoc getStartLoc() const;
585 /// Return the source code span of the loop.
586 LocRange getLocRange() const;
588 StringRef getName() const {
589 if (BasicBlock *Header = getHeader())
590 if (Header->hasName())
591 return Header->getName();
592 return "<unnamed loop>";
595 private:
596 Loop() = default;
598 friend class LoopInfoBase<BasicBlock, Loop>;
599 friend class LoopBase<BasicBlock, Loop>;
600 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
601 ~Loop() = default;
604 //===----------------------------------------------------------------------===//
605 /// This class builds and contains all of the top-level loop
606 /// structures in the specified function.
609 template <class BlockT, class LoopT> class LoopInfoBase {
610 // BBMap - Mapping of basic blocks to the inner most loop they occur in
611 DenseMap<const BlockT *, LoopT *> BBMap;
612 std::vector<LoopT *> TopLevelLoops;
613 BumpPtrAllocator LoopAllocator;
615 friend class LoopBase<BlockT, LoopT>;
616 friend class LoopInfo;
618 void operator=(const LoopInfoBase &) = delete;
619 LoopInfoBase(const LoopInfoBase &) = delete;
621 public:
622 LoopInfoBase() {}
623 ~LoopInfoBase() { releaseMemory(); }
625 LoopInfoBase(LoopInfoBase &&Arg)
626 : BBMap(std::move(Arg.BBMap)),
627 TopLevelLoops(std::move(Arg.TopLevelLoops)),
628 LoopAllocator(std::move(Arg.LoopAllocator)) {
629 // We have to clear the arguments top level loops as we've taken ownership.
630 Arg.TopLevelLoops.clear();
632 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
633 BBMap = std::move(RHS.BBMap);
635 for (auto *L : TopLevelLoops)
636 L->~LoopT();
638 TopLevelLoops = std::move(RHS.TopLevelLoops);
639 LoopAllocator = std::move(RHS.LoopAllocator);
640 RHS.TopLevelLoops.clear();
641 return *this;
644 void releaseMemory() {
645 BBMap.clear();
647 for (auto *L : TopLevelLoops)
648 L->~LoopT();
649 TopLevelLoops.clear();
650 LoopAllocator.Reset();
653 template <typename... ArgsTy> LoopT *AllocateLoop(ArgsTy &&... Args) {
654 LoopT *Storage = LoopAllocator.Allocate<LoopT>();
655 return new (Storage) LoopT(std::forward<ArgsTy>(Args)...);
658 /// iterator/begin/end - The interface to the top-level loops in the current
659 /// function.
661 typedef typename std::vector<LoopT *>::const_iterator iterator;
662 typedef
663 typename std::vector<LoopT *>::const_reverse_iterator reverse_iterator;
664 iterator begin() const { return TopLevelLoops.begin(); }
665 iterator end() const { return TopLevelLoops.end(); }
666 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
667 reverse_iterator rend() const { return TopLevelLoops.rend(); }
668 bool empty() const { return TopLevelLoops.empty(); }
670 /// Return all of the loops in the function in preorder across the loop
671 /// nests, with siblings in forward program order.
673 /// Note that because loops form a forest of trees, preorder is equivalent to
674 /// reverse postorder.
675 SmallVector<LoopT *, 4> getLoopsInPreorder();
677 /// Return all of the loops in the function in preorder across the loop
678 /// nests, with siblings in *reverse* program order.
680 /// Note that because loops form a forest of trees, preorder is equivalent to
681 /// reverse postorder.
683 /// Also note that this is *not* a reverse preorder. Only the siblings are in
684 /// reverse program order.
685 SmallVector<LoopT *, 4> getLoopsInReverseSiblingPreorder();
687 /// Return the inner most loop that BB lives in. If a basic block is in no
688 /// loop (for example the entry node), null is returned.
689 LoopT *getLoopFor(const BlockT *BB) const { return BBMap.lookup(BB); }
691 /// Same as getLoopFor.
692 const LoopT *operator[](const BlockT *BB) const { return getLoopFor(BB); }
694 /// Return the loop nesting level of the specified block. A depth of 0 means
695 /// the block is not inside any loop.
696 unsigned getLoopDepth(const BlockT *BB) const {
697 const LoopT *L = getLoopFor(BB);
698 return L ? L->getLoopDepth() : 0;
701 // True if the block is a loop header node
702 bool isLoopHeader(const BlockT *BB) const {
703 const LoopT *L = getLoopFor(BB);
704 return L && L->getHeader() == BB;
707 /// This removes the specified top-level loop from this loop info object.
708 /// The loop is not deleted, as it will presumably be inserted into
709 /// another loop.
710 LoopT *removeLoop(iterator I) {
711 assert(I != end() && "Cannot remove end iterator!");
712 LoopT *L = *I;
713 assert(!L->getParentLoop() && "Not a top-level loop!");
714 TopLevelLoops.erase(TopLevelLoops.begin() + (I - begin()));
715 return L;
718 /// Change the top-level loop that contains BB to the specified loop.
719 /// This should be used by transformations that restructure the loop hierarchy
720 /// tree.
721 void changeLoopFor(BlockT *BB, LoopT *L) {
722 if (!L) {
723 BBMap.erase(BB);
724 return;
726 BBMap[BB] = L;
729 /// Replace the specified loop in the top-level loops list with the indicated
730 /// loop.
731 void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop) {
732 auto I = find(TopLevelLoops, OldLoop);
733 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
734 *I = NewLoop;
735 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
736 "Loops already embedded into a subloop!");
739 /// This adds the specified loop to the collection of top-level loops.
740 void addTopLevelLoop(LoopT *New) {
741 assert(!New->getParentLoop() && "Loop already in subloop!");
742 TopLevelLoops.push_back(New);
745 /// This method completely removes BB from all data structures,
746 /// including all of the Loop objects it is nested in and our mapping from
747 /// BasicBlocks to loops.
748 void removeBlock(BlockT *BB) {
749 auto I = BBMap.find(BB);
750 if (I != BBMap.end()) {
751 for (LoopT *L = I->second; L; L = L->getParentLoop())
752 L->removeBlockFromLoop(BB);
754 BBMap.erase(I);
758 // Internals
760 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
761 const LoopT *ParentLoop) {
762 if (!SubLoop)
763 return true;
764 if (SubLoop == ParentLoop)
765 return false;
766 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
769 /// Create the loop forest using a stable algorithm.
770 void analyze(const DominatorTreeBase<BlockT, false> &DomTree);
772 // Debugging
773 void print(raw_ostream &OS) const;
775 void verify(const DominatorTreeBase<BlockT, false> &DomTree) const;
777 /// Destroy a loop that has been removed from the `LoopInfo` nest.
779 /// This runs the destructor of the loop object making it invalid to
780 /// reference afterward. The memory is retained so that the *pointer* to the
781 /// loop remains valid.
783 /// The caller is responsible for removing this loop from the loop nest and
784 /// otherwise disconnecting it from the broader `LoopInfo` data structures.
785 /// Callers that don't naturally handle this themselves should probably call
786 /// `erase' instead.
787 void destroy(LoopT *L) {
788 L->~LoopT();
790 // Since LoopAllocator is a BumpPtrAllocator, this Deallocate only poisons
791 // \c L, but the pointer remains valid for non-dereferencing uses.
792 LoopAllocator.Deallocate(L);
796 // Implementation in LoopInfoImpl.h
797 extern template class LoopInfoBase<BasicBlock, Loop>;
799 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
800 typedef LoopInfoBase<BasicBlock, Loop> BaseT;
802 friend class LoopBase<BasicBlock, Loop>;
804 void operator=(const LoopInfo &) = delete;
805 LoopInfo(const LoopInfo &) = delete;
807 public:
808 LoopInfo() {}
809 explicit LoopInfo(const DominatorTreeBase<BasicBlock, false> &DomTree);
811 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
812 LoopInfo &operator=(LoopInfo &&RHS) {
813 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
814 return *this;
817 /// Handle invalidation explicitly.
818 bool invalidate(Function &F, const PreservedAnalyses &PA,
819 FunctionAnalysisManager::Invalidator &);
821 // Most of the public interface is provided via LoopInfoBase.
823 /// Update LoopInfo after removing the last backedge from a loop. This updates
824 /// the loop forest and parent loops for each block so that \c L is no longer
825 /// referenced, but does not actually delete \c L immediately. The pointer
826 /// will remain valid until this LoopInfo's memory is released.
827 void erase(Loop *L);
829 /// Returns true if replacing From with To everywhere is guaranteed to
830 /// preserve LCSSA form.
831 bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
832 // Preserving LCSSA form is only problematic if the replacing value is an
833 // instruction.
834 Instruction *I = dyn_cast<Instruction>(To);
835 if (!I)
836 return true;
837 // If both instructions are defined in the same basic block then replacement
838 // cannot break LCSSA form.
839 if (I->getParent() == From->getParent())
840 return true;
841 // If the instruction is not defined in a loop then it can safely replace
842 // anything.
843 Loop *ToLoop = getLoopFor(I->getParent());
844 if (!ToLoop)
845 return true;
846 // If the replacing instruction is defined in the same loop as the original
847 // instruction, or in a loop that contains it as an inner loop, then using
848 // it as a replacement will not break LCSSA form.
849 return ToLoop->contains(getLoopFor(From->getParent()));
852 /// Checks if moving a specific instruction can break LCSSA in any loop.
854 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
855 /// assuming that the function containing \p Inst and \p NewLoc is currently
856 /// in LCSSA form.
857 bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
858 assert(Inst->getFunction() == NewLoc->getFunction() &&
859 "Can't reason about IPO!");
861 auto *OldBB = Inst->getParent();
862 auto *NewBB = NewLoc->getParent();
864 // Movement within the same loop does not break LCSSA (the equality check is
865 // to avoid doing a hashtable lookup in case of intra-block movement).
866 if (OldBB == NewBB)
867 return true;
869 auto *OldLoop = getLoopFor(OldBB);
870 auto *NewLoop = getLoopFor(NewBB);
872 if (OldLoop == NewLoop)
873 return true;
875 // Check if Outer contains Inner; with the null loop counting as the
876 // "outermost" loop.
877 auto Contains = [](const Loop *Outer, const Loop *Inner) {
878 return !Outer || Outer->contains(Inner);
881 // To check that the movement of Inst to before NewLoc does not break LCSSA,
882 // we need to check two sets of uses for possible LCSSA violations at
883 // NewLoc: the users of NewInst, and the operands of NewInst.
885 // If we know we're hoisting Inst out of an inner loop to an outer loop,
886 // then the uses *of* Inst don't need to be checked.
888 if (!Contains(NewLoop, OldLoop)) {
889 for (Use &U : Inst->uses()) {
890 auto *UI = cast<Instruction>(U.getUser());
891 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
892 : UI->getParent();
893 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
894 return false;
898 // If we know we're sinking Inst from an outer loop into an inner loop, then
899 // the *operands* of Inst don't need to be checked.
901 if (!Contains(OldLoop, NewLoop)) {
902 // See below on why we can't handle phi nodes here.
903 if (isa<PHINode>(Inst))
904 return false;
906 for (Use &U : Inst->operands()) {
907 auto *DefI = dyn_cast<Instruction>(U.get());
908 if (!DefI)
909 return false;
911 // This would need adjustment if we allow Inst to be a phi node -- the
912 // new use block won't simply be NewBB.
914 auto *DefBlock = DefI->getParent();
915 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
916 return false;
920 return true;
924 // Allow clients to walk the list of nested loops...
925 template <> struct GraphTraits<const Loop *> {
926 typedef const Loop *NodeRef;
927 typedef LoopInfo::iterator ChildIteratorType;
929 static NodeRef getEntryNode(const Loop *L) { return L; }
930 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
931 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
934 template <> struct GraphTraits<Loop *> {
935 typedef Loop *NodeRef;
936 typedef LoopInfo::iterator ChildIteratorType;
938 static NodeRef getEntryNode(Loop *L) { return L; }
939 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
940 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
943 /// Analysis pass that exposes the \c LoopInfo for a function.
944 class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> {
945 friend AnalysisInfoMixin<LoopAnalysis>;
946 static AnalysisKey Key;
948 public:
949 typedef LoopInfo Result;
951 LoopInfo run(Function &F, FunctionAnalysisManager &AM);
954 /// Printer pass for the \c LoopAnalysis results.
955 class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> {
956 raw_ostream &OS;
958 public:
959 explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
960 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
963 /// Verifier pass for the \c LoopAnalysis results.
964 struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> {
965 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
968 /// The legacy pass manager's analysis pass to compute loop information.
969 class LoopInfoWrapperPass : public FunctionPass {
970 LoopInfo LI;
972 public:
973 static char ID; // Pass identification, replacement for typeid
975 LoopInfoWrapperPass() : FunctionPass(ID) {
976 initializeLoopInfoWrapperPassPass(*PassRegistry::getPassRegistry());
979 LoopInfo &getLoopInfo() { return LI; }
980 const LoopInfo &getLoopInfo() const { return LI; }
982 /// Calculate the natural loop information for a given function.
983 bool runOnFunction(Function &F) override;
985 void verifyAnalysis() const override;
987 void releaseMemory() override { LI.releaseMemory(); }
989 void print(raw_ostream &O, const Module *M = nullptr) const override;
991 void getAnalysisUsage(AnalysisUsage &AU) const override;
994 /// Function to print a loop's contents as LLVM's text IR assembly.
995 void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner = "");
997 /// Find and return the loop attribute node for the attribute @p Name in
998 /// @p LoopID. Return nullptr if there is no such attribute.
999 MDNode *findOptionMDForLoopID(MDNode *LoopID, StringRef Name);
1001 /// Find string metadata for a loop.
1003 /// Returns the MDNode where the first operand is the metadata's name. The
1004 /// following operands are the metadata's values. If no metadata with @p Name is
1005 /// found, return nullptr.
1006 MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name);
1008 /// Return whether an MDNode might represent an access group.
1010 /// Access group metadata nodes have to be distinct and empty. Being
1011 /// always-empty ensures that it never needs to be changed (which -- because
1012 /// MDNodes are designed immutable -- would require creating a new MDNode). Note
1013 /// that this is not a sufficient condition: not every distinct and empty NDNode
1014 /// is representing an access group.
1015 bool isValidAsAccessGroup(MDNode *AccGroup);
1017 /// Create a new LoopID after the loop has been transformed.
1019 /// This can be used when no follow-up loop attributes are defined
1020 /// (llvm::makeFollowupLoopID returning None) to stop transformations to be
1021 /// applied again.
1023 /// @param Context The LLVMContext in which to create the new LoopID.
1024 /// @param OrigLoopID The original LoopID; can be nullptr if the original
1025 /// loop has no LoopID.
1026 /// @param RemovePrefixes Remove all loop attributes that have these prefixes.
1027 /// Use to remove metadata of the transformation that has
1028 /// been applied.
1029 /// @param AddAttrs Add these loop attributes to the new LoopID.
1031 /// @return A new LoopID that can be applied using Loop::setLoopID().
1032 llvm::MDNode *
1033 makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID,
1034 llvm::ArrayRef<llvm::StringRef> RemovePrefixes,
1035 llvm::ArrayRef<llvm::MDNode *> AddAttrs);
1037 } // End llvm namespace
1039 #endif