LLVM 24.0.0git
GenericLoopInfo.h
Go to the documentation of this file.
1//===- GenericLoopInfo - Generic Loop Info for graphs -----------*- 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 LoopInfoBase class that is used to identify natural
10// loops and determine the loop depth of various nodes in a generic graph of
11// blocks. A natural loop has exactly one entry-point, which is called the
12// header. Note that natural loops may actually be several loops that share the
13// same header node.
14//
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 that make up the
18// loop.
19//
20// It can calculate on the fly various bits of information, for example:
21//
22// * whether there is a preheader for the loop
23// * the number of back edges to the header
24// * whether or not a particular block branches out of the loop
25// * the successor blocks of the loop
26// * the loop depth
27// * etc...
28//
29// Note that this analysis specifically identifies *Loops* not cycles or SCCs
30// in the graph. There can be strongly connected components in the graph which
31// this analysis will not recognize and that will not be represented by a Loop
32// instance. In particular, a Loop might be inside such a non-loop SCC, or a
33// non-loop SCC might contain a sub-SCC which is a Loop.
34//
35// For an overview of terminology used in this API (and thus all of our loop
36// analyses or transforms), see docs/LoopTerminology.md.
37//
38//===----------------------------------------------------------------------===//
39
40#ifndef LLVM_SUPPORT_GENERICLOOPINFO_H
41#define LLVM_SUPPORT_GENERICLOOPINFO_H
42
43#include "llvm/ADT/DenseSet.h"
45#include "llvm/ADT/STLExtras.h"
49
50namespace llvm {
51
52template <class N, class M> class LoopInfoBase;
53template <class N, class M> class LoopBase;
54
55//===----------------------------------------------------------------------===//
56/// Instances of this class are used to represent loops that are detected in the
57/// flow graph.
58///
59template <class BlockT, class LoopT> class LoopBase {
60 LoopT *ParentLoop;
61 // Loops contained entirely within this one.
62 std::vector<LoopT *> SubLoops;
63
64 // The list of blocks in this loop; first entry is the header. Either borrows
65 // a slice of the owning LoopInfo's BlockLayout, marked by the
66 // BorrowedCapacity sentinel, or is a private allocation of BlockCapacity
67 // slots from its allocator.
68 //
69 // Until analyze()'s layout carve runs, PendingHeader stashes the loop header
70 // (see pendingHeader()).
71 union {
73 BlockT **BlockData = nullptr;
74 };
75 unsigned BlockLen = 0;
76 unsigned BlockCapacity = 0;
77
78 static constexpr unsigned BorrowedCapacity = -1u;
79
80 // The LoopInfo that owns this loop. Used to answer contains(BlockT *) from
81 // the central block-to-loop map.
82 LoopInfoBase<BlockT, LoopT> *LI = nullptr;
83
84#if LLVM_ENABLE_ABI_BREAKING_CHECKS
85 /// Indicator that this loop is no longer a valid loop.
86 bool IsInvalid = false;
87#endif
88
89 LoopBase(const LoopBase<BlockT, LoopT> &) = delete;
91 operator=(const LoopBase<BlockT, LoopT> &) = delete;
92
93public:
94 /// Return the nesting level of this loop. An outer-most loop has depth 1,
95 /// for consistency with loop depth values used for basic blocks, where depth
96 /// 0 is used for blocks not inside any loops.
97 unsigned getLoopDepth() const {
98 assert(!isInvalid() && "Loop not in a valid state!");
99 unsigned D = 1;
100 for (const LoopT *CurLoop = ParentLoop; CurLoop;
101 CurLoop = CurLoop->ParentLoop)
102 ++D;
103 return D;
104 }
105 BlockT *getHeader() const { return getBlocks().front(); }
106 /// Return the parent loop if it exists or nullptr for top
107 /// level loops.
108
109 /// A loop is either top-level in a function (that is, it is not
110 /// contained in any other loop) or it is entirely enclosed in
111 /// some other loop.
112 /// If a loop is top-level, it has no parent, otherwise its
113 /// parent is the innermost loop in which it is enclosed.
114 LoopT *getParentLoop() const { return ParentLoop; }
115
116 /// Get the outermost loop in which this loop is contained.
117 /// This may be the loop itself, if it already is the outermost loop.
118 const LoopT *getOutermostLoop() const {
119 const LoopT *L = static_cast<const LoopT *>(this);
120 while (L->ParentLoop)
121 L = L->ParentLoop;
122 return L;
123 }
124
126 LoopT *L = static_cast<LoopT *>(this);
127 while (L->ParentLoop)
128 L = L->ParentLoop;
129 return L;
130 }
131
132 /// This is a raw interface for bypassing addChildLoop.
133 void setParentLoop(LoopT *L) {
134 assert(!isInvalid() && "Loop not in a valid state!");
135 ParentLoop = L;
136 }
137
138 /// Return true if the specified loop is contained within this loop.
139 ///
140 /// This walks the parent chain and is O(depth). Deep nesting is not a
141 /// performance target (yet).
142 bool contains(const LoopT *L) const {
143 assert(!isInvalid() && "Loop not in a valid state!");
144 for (;;) {
145 if (L == this)
146 return true;
147 if (!L)
148 return false;
149 L = L->getParentLoop();
150 }
151 }
152
153 /// Return true if the specified basic block is in this loop, using LoopInfo's
154 /// block-to-loop map.
155 ///
156 /// This is only valid when that map agrees with the block lists. Avoid when
157 /// the loop nest is being restructured, when a block may appear in a loop's
158 /// block list before it is mapped to that loop. Code in such a transient
159 /// state must scan getBlocks() directly instead.
160 bool contains(const BlockT *BB) const {
161 assert(!isInvalid() && "Loop not in a valid state!");
162 // A block from another function is never contained, and its number would
163 // otherwise index this function's map.
164 if (BB->getParent() != LI->ParentPtr)
165 return false;
166 return contains(LI->lookupLoopFor(BB));
167 }
168
169 /// Return true if the specified instruction is in this loop.
170 template <class InstT> bool contains(const InstT *Inst) const {
171 return contains(Inst->getParent());
172 }
173
174 /// Return the loops contained entirely within this loop.
175 const std::vector<LoopT *> &getSubLoops() const {
176 assert(!isInvalid() && "Loop not in a valid state!");
177 return SubLoops;
178 }
179 using iterator = typename std::vector<LoopT *>::const_iterator;
181 typename std::vector<LoopT *>::const_reverse_iterator;
182 iterator begin() const { return getSubLoops().begin(); }
183 iterator end() const { return getSubLoops().end(); }
184 reverse_iterator rbegin() const { return getSubLoops().rbegin(); }
185 reverse_iterator rend() const { return getSubLoops().rend(); }
186
187 // LoopInfo does not detect irreducible control flow, just natural
188 // loops. That is, it is possible that there is cyclic control
189 // flow within the "innermost loop" or around the "outermost
190 // loop".
191
192 /// Return true if the loop does not contain any (natural) loops.
193 bool isInnermost() const { return getSubLoops().empty(); }
194 /// Return true if the loop does not have a parent (natural) loop
195 // (i.e. it is outermost, which is the same as top-level).
196 bool isOutermost() const { return getParentLoop() == nullptr; }
197
198 /// Get a list of the basic blocks which make up this loop.
200 assert(!isInvalid() && "Loop not in a valid state!");
201 return ArrayRef<BlockT *>(BlockData, BlockLen);
202 }
204 block_iterator block_begin() const { return getBlocks().begin(); }
205 block_iterator block_end() const { return getBlocks().end(); }
207 assert(!isInvalid() && "Loop not in a valid state!");
208 return make_range(block_begin(), block_end());
209 }
210
211 /// Get the number of blocks in this loop in constant time.
212 /// Invalidate the loop, indicating that it is no longer a loop.
213 unsigned getNumBlocks() const {
214 assert(!isInvalid() && "Loop not in a valid state!");
215 return BlockLen;
216 }
217
218 /// Return true if this loop is no longer valid. The only valid use of this
219 /// helper is "assert(L.isInvalid())" or equivalent, since IsInvalid is set to
220 /// true by the destructor. In other words, if this accessor returns true,
221 /// the caller has already triggered UB by calling this accessor; and so it
222 /// can only be called in a context where a return value of true indicates a
223 /// programmer error.
224 bool isInvalid() const {
225#if LLVM_ENABLE_ABI_BREAKING_CHECKS
226 return IsInvalid;
227#else
228 return false;
229#endif
230 }
231
232 /// True if terminator in the block can branch to another block that is
233 /// outside of the current loop. \p BB must be inside the loop.
234 bool isLoopExiting(const BlockT *BB) const {
235 assert(!isInvalid() && "Loop not in a valid state!");
236 assert(contains(BB) && "Exiting block must be part of the loop");
237 for (const auto *Succ : children<const BlockT *>(BB)) {
238 if (!contains(Succ))
239 return true;
240 }
241 return false;
242 }
243
244 /// Returns true if \p BB is a loop-latch.
245 /// A latch block is a block that contains a branch back to the header.
246 /// This function is useful when there are multiple latches in a loop
247 /// because \fn getLoopLatch will return nullptr in that case.
248 bool isLoopLatch(const BlockT *BB) const {
249 assert(!isInvalid() && "Loop not in a valid state!");
250 assert(contains(BB) && "block does not belong to the loop");
252 }
253
254 /// Calculate the number of back edges to the loop header.
255 unsigned getNumBackEdges() const {
256 assert(!isInvalid() && "Loop not in a valid state!");
258 [&](BlockT *Pred) { return contains(Pred); });
259 }
260
261 //===--------------------------------------------------------------------===//
262 // APIs for simple analysis of the loop.
263 //
264 // Note that all of these methods can fail on general loops (ie, there may not
265 // be a preheader, etc). For best success, the loop simplification and
266 // induction variable canonicalization pass should be used to normalize loops
267 // for easy analysis. These methods assume canonical loops.
268
269 /// Return all blocks inside the loop that have successors outside of the
270 /// loop. These are the blocks _inside of the current loop_ which branch out.
271 /// The returned list is always unique.
272 void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
273
274 /// If getExitingBlocks would return exactly one block, return that block.
275 /// Otherwise return null.
276 BlockT *getExitingBlock() const;
277
278 /// Return all of the successor blocks of this loop. These are the blocks
279 /// _outside of the current loop_ which are branched to.
280 void getExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
281
282 /// If getExitBlocks would return exactly one block, return that block.
283 /// Otherwise return null.
284 BlockT *getExitBlock() const;
285
286 /// Return true if no exit block for the loop has a predecessor that is
287 /// outside the loop.
288 bool hasDedicatedExits() const;
289
290 /// Return all unique successor blocks of this loop.
291 /// These are the blocks _outside of the current loop_ which are branched to.
292 void getUniqueExitBlocks(SmallVectorImpl<BlockT *> &ExitBlocks) const;
293
294 /// Return all unique successor blocks of this loop except successors from
295 /// Latch block are not considered. If the exit comes from Latch has also
296 /// non Latch predecessor in a loop it will be added to ExitBlocks.
297 /// These are the blocks _outside of the current loop_ which are branched to.
299
300 /// If getUniqueExitBlocks would return exactly one block, return that block.
301 /// Otherwise return null.
302 BlockT *getUniqueExitBlock() const;
303
304 /// If there is a preheader for this loop, return it. A loop has a preheader
305 /// if there is only one edge to the header of the loop from outside of the
306 /// loop. If this is the case, the block branching to the header of the loop
307 /// is the preheader node.
308 ///
309 /// This method returns null if there is no preheader for the loop.
310 BlockT *getLoopPreheader() const;
311
312 /// If the given loop's header has exactly one unique predecessor outside the
313 /// loop, return it. Otherwise return null.
314 /// This is less strict that the loop "preheader" concept, which requires
315 /// the predecessor to have exactly one successor.
316 BlockT *getLoopPredecessor() const;
317
318 /// If there is a single latch block for this loop, return it.
319 /// A latch block is a block that contains a branch back to the header.
320 BlockT *getLoopLatch() const;
321
322 /// Return all loop latch blocks of this loop. A latch block is a block that
323 /// contains a branch back to the header.
324 void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
325 assert(!isInvalid() && "Loop not in a valid state!");
326 BlockT *H = getHeader();
327 for (const auto Pred : inverse_children<BlockT *>(H))
328 if (contains(Pred))
329 LoopLatches.push_back(Pred);
330 }
331
332 /// Return all inner loops in the loop nest rooted by the loop in preorder,
333 /// with siblings in forward program order.
334 template <class Type>
335 static void getInnerLoopsInPreorder(const LoopT &L,
336 SmallVectorImpl<Type> &PreOrderLoops) {
337 SmallVector<LoopT *, 4> PreOrderWorklist;
338 PreOrderWorklist.append(L.rbegin(), L.rend());
339
340 while (!PreOrderWorklist.empty()) {
341 LoopT *L = PreOrderWorklist.pop_back_val();
342 // Sub-loops are stored in forward program order, but will process the
343 // worklist backwards so append them in reverse order.
344 PreOrderWorklist.append(L->rbegin(), L->rend());
345 PreOrderLoops.push_back(L);
346 }
347 }
348
349 /// Return all loops in the loop nest rooted by the loop in preorder, with
350 /// siblings in forward program order.
352 SmallVector<const LoopT *, 4> PreOrderLoops;
353 const LoopT *CurLoop = static_cast<const LoopT *>(this);
354 PreOrderLoops.push_back(CurLoop);
355 getInnerLoopsInPreorder(*CurLoop, PreOrderLoops);
356 return PreOrderLoops;
357 }
359 SmallVector<LoopT *, 4> PreOrderLoops;
360 LoopT *CurLoop = static_cast<LoopT *>(this);
361 PreOrderLoops.push_back(CurLoop);
362 getInnerLoopsInPreorder(*CurLoop, PreOrderLoops);
363 return PreOrderLoops;
364 }
365
366 //===--------------------------------------------------------------------===//
367 // APIs for updating loop information after changing the CFG
368 //
369
370 /// This method is used by other analyses to update loop information.
371 /// NewBB is set to be a new member of the current loop.
372 /// Because of this, it is added as a member of all parent loops, and is added
373 /// to the specified LoopInfo object as being in the current basic block. It
374 /// is not valid to replace the loop header with this method.
375 void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
376
377 /// Add the specified loop to be a child of this loop.
378 /// This updates the loop depth of the new child.
379 void addChildLoop(LoopT *NewChild) {
380 assert(!isInvalid() && "Loop not in a valid state!");
381 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
382 NewChild->ParentLoop = static_cast<LoopT *>(this);
383 SubLoops.push_back(NewChild);
384 }
385
386 /// This removes the specified child from being a subloop of this loop. The
387 /// loop is not deleted, as it will presumably be inserted into another loop.
389 assert(!isInvalid() && "Loop not in a valid state!");
390 assert(I != SubLoops.end() && "Cannot remove end iterator!");
391 LoopT *Child = *I;
392 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
393 SubLoops.erase(SubLoops.begin() + (I - begin()));
394 Child->ParentLoop = nullptr;
395 return Child;
396 }
397
398 /// This removes the specified child from being a subloop of this loop. The
399 /// loop is not deleted, as it will presumably be inserted into another loop.
400 LoopT *removeChildLoop(LoopT *Child) {
401 return removeChildLoop(llvm::find(*this, Child));
402 }
403
404 /// This adds a basic block directly to the basic block list.
405 /// This should only be used by transformations that create new loops. Other
406 /// transformations should use addBasicBlockToLoop.
407 void addBlockEntry(BlockT *BB) {
408 assert(!isInvalid() && "Loop not in a valid state!");
409 // A borrowed slice or a full private allocation grows into fresh private
410 // storage before appending.
411 if (BlockCapacity == BorrowedCapacity || BlockLen == BlockCapacity)
412 LI->reallocBlocks(*static_cast<LoopT *>(this),
413 std::max(2 * BlockLen, 4u));
414 BlockData[BlockLen++] = BB;
415 }
416
417 /// interface to do reserve() for Blocks
418 void reserveBlocks(unsigned Size) {
419 assert(!isInvalid() && "Loop not in a valid state!");
420 if (BlockCapacity < Size)
421 LI->reallocBlocks(*static_cast<LoopT *>(this), Size);
422 }
423
424 /// This method is used to move BB (which must be part of this loop) to be the
425 /// loop header of the loop (the block that dominates all others).
426 void moveToHeader(BlockT *BB) {
427 assert(!isInvalid() && "Loop not in a valid state!");
428 if (BlockData[0] == BB)
429 return;
430 LI->materializeBlocks(*static_cast<LoopT *>(this));
431 for (unsigned i = 0;; ++i) {
432 assert(i != BlockLen && "Loop does not contain BB!");
433 if (BlockData[i] == BB) {
434 BlockData[i] = BlockData[0];
435 BlockData[0] = BB;
436 return;
437 }
438 }
439 }
440
441 /// This removes the specified basic block from the current loop, updating the
442 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
443 /// class.
444 void removeBlockFromLoop(BlockT *BB) {
445 assert(!isInvalid() && "Loop not in a valid state!");
446 LI->materializeBlocks(*static_cast<LoopT *>(this));
447 MutableArrayRef<BlockT *> Blocks(BlockData, BlockLen);
448 auto *I = llvm::find(Blocks, BB);
449 assert(I != Blocks.end() && "N is not in this list!");
450 std::move(I + 1, Blocks.end(), I);
451 --BlockLen;
452 }
453
454 /// Verify loop structure
455 void verifyLoop() const;
456
457 /// Verify loop structure of this loop and all nested loops.
459
460 /// Returns true if the loop is annotated parallel.
461 ///
462 /// Derived classes can override this method using static template
463 /// polymorphism.
464 bool isAnnotatedParallel() const { return false; }
465
466 /// Print loop with all the BBs inside it.
467 void print(raw_ostream &OS, bool Verbose = false, bool PrintNested = true,
468 unsigned Depth = 0) const;
469
470protected:
471 friend class LoopInfoBase<BlockT, LoopT>;
472
473 /// This creates an empty loop.
474 LoopBase() : ParentLoop(nullptr) {}
475
476 // ScalarEvolution and others key results off `Loop` pointers, so an address
477 // must never come to name a different loop. Passes call LoopInfo::destroy()
478 // rather than `delete`, retaining the memory until the owning LoopInfo dies;
479 // the non-public destructor enforces that.
481 for (auto *SubLoop : SubLoops)
482 SubLoop->~LoopT();
483
484#if LLVM_ENABLE_ABI_BREAKING_CHECKS
485 IsInvalid = true;
486#endif
487 clear();
488 }
489
490 void clear() {
491 SubLoops.clear();
492 // The block storage is reclaimed by the owning LoopInfo.
493 BlockData = nullptr;
494 BlockLen = 0;
495 BlockCapacity = 0;
496 ParentLoop = nullptr;
497 }
498};
499
500template <class BlockT, class LoopT>
502 Loop.print(OS);
503 return OS;
504}
505
506//===----------------------------------------------------------------------===//
507/// This class builds and contains all of the top-level loop
508/// structures in the specified function.
509///
510
511template <class BlockT, class LoopT> class LoopInfoBase {
513 "LoopInfo requires GraphTraits<BlockT *>::getNumber (see "
514 "GraphHasNodeNumbers)");
515
516 // Mapping of each block, indexed by its number, to the innermost loop it
517 // occurs in (or null).
519
520 using ParentT = decltype(std::declval<BlockT *>()->getParent());
521 ParentT ParentPtr = nullptr;
522 unsigned BlockNumberEpoch;
523
524 std::vector<LoopT *> TopLevelLoops;
525
526 // Shared reverse postorder layout of the in-loop blocks. Each initial loop is
527 // a slice of this array, subloop slices nested inside their parent's.
528 std::unique_ptr<BlockT *[]> BlockLayout;
529
530 BumpPtrAllocator LoopAllocator;
531
532 friend class LoopBase<BlockT, LoopT>;
533 friend class LoopInfo;
534
535 void operator=(const LoopInfoBase &) = delete;
536 LoopInfoBase(const LoopInfoBase &) = delete;
537
538public:
539 LoopInfoBase() = default;
541
542 LoopInfoBase(LoopInfoBase &&Arg)
543 : BBMap(std::move(Arg.BBMap)),
544 TopLevelLoops(std::move(Arg.TopLevelLoops)),
545 BlockLayout(std::move(Arg.BlockLayout)),
546 LoopAllocator(std::move(Arg.LoopAllocator)) {
547 ParentPtr = Arg.ParentPtr;
548 BlockNumberEpoch = Arg.BlockNumberEpoch;
549 resetLoopInfoOwners();
550 // We have to clear the arguments top level loops as we've taken ownership.
551 Arg.TopLevelLoops.clear();
552 }
553 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
554 BBMap = std::move(RHS.BBMap);
555 ParentPtr = RHS.ParentPtr;
556 BlockNumberEpoch = RHS.BlockNumberEpoch;
557
558 for (auto *L : TopLevelLoops)
559 L->~LoopT();
560
561 TopLevelLoops = std::move(RHS.TopLevelLoops);
562 BlockLayout = std::move(RHS.BlockLayout);
563 LoopAllocator = std::move(RHS.LoopAllocator);
564 resetLoopInfoOwners();
565 RHS.TopLevelLoops.clear();
566 return *this;
567 }
568
570 BBMap.clear();
571
572 for (auto *L : TopLevelLoops)
573 L->~LoopT();
574 TopLevelLoops.clear();
575 BlockLayout.reset();
576 LoopAllocator.Reset();
577 }
578
579 LoopT *AllocateLoop() {
580 LoopT *Storage = LoopAllocator.Allocate<LoopT>();
581 LoopT *L = new (Storage) LoopT();
582 L->LI = this;
583 return L;
584 }
585
586 /// iterator/begin/end - The interface to the top-level loops in the current
587 /// function.
588 ///
589 using iterator = typename std::vector<LoopT *>::const_iterator;
591 typename std::vector<LoopT *>::const_reverse_iterator;
592 iterator begin() const { return TopLevelLoops.begin(); }
593 iterator end() const { return TopLevelLoops.end(); }
594 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
595 reverse_iterator rend() const { return TopLevelLoops.rend(); }
596 bool empty() const { return TopLevelLoops.empty(); }
597
598 /// Return all of the loops in the function in preorder across the loop
599 /// nests, with siblings in forward program order.
600 ///
601 /// Note that because loops form a forest of trees, preorder is equivalent to
602 /// reverse postorder.
604
605 /// Return all of the loops in the function in preorder across the loop
606 /// nests, with siblings in *reverse* program order.
607 ///
608 /// Note that because loops form a forest of trees, preorder is equivalent to
609 /// reverse postorder.
610 ///
611 /// Also note that this is *not* a reverse preorder. Only the siblings are in
612 /// reverse program order.
614
615private:
616 // Point every loop's owning-LoopInfo back-pointer at this object. Called
617 // after a move.
618 void resetLoopInfoOwners() {
619 SmallVector<LoopT *, 8> Worklist(TopLevelLoops.begin(),
620 TopLevelLoops.end());
621 while (!Worklist.empty()) {
622 LoopT *L = Worklist.pop_back_val();
623 L->LI = this;
624 Worklist.append(L->begin(), L->end());
625 }
626 }
627
628 /// Verify that used block numbers are still valid.
629 void
630 verifyBlockNumberEpoch(const std::remove_pointer_t<ParentT> *BBParent) const {
631 assert(ParentPtr == BBParent &&
632 "loop info queried with block of other function");
633 assert(BlockNumberEpoch ==
634 GraphTraits<ParentT>::getNumberEpoch(ParentPtr) &&
635 "loop info used with outdated block numbers");
636 }
637
638 // Look up BB's innermost loop in the block-to-loop map; BB must belong to
639 // this function.
640 LoopT *lookupLoopFor(const BlockT *BB) const {
641 unsigned Number = GraphTraits<const BlockT *>::getNumber(BB);
642 return Number < BBMap.size() ? BBMap[Number] : nullptr;
643 }
644
645 /// Maps a header to the loop recompute() refills for it, if any.
646 using ReuseLoopT = function_ref<LoopT *(BlockT *)>;
647
648 /// AllocateLoop for analyze(): stash \p Header (see pendingHeader).
649 /// getHeader() only works once the layout carve has replaced the stash with
650 /// the loop's block list. \p ReuseLoop, if specified, returns an existing
651 /// loop rather than a fresh one for LoopInfoBase::recompute.
652 LoopT *allocateLoop(BlockT *Header, ReuseLoopT ReuseLoop) {
653 LoopT *L = ReuseLoop ? ReuseLoop(Header) : nullptr;
654 if (!L)
655 L = AllocateLoop();
656 L->PendingHeader = Header;
657 return L;
658 }
659
660 void analyzeImpl(
661 ParentT F,
662 function_ref<const DominatorTreeBase<BlockT, false> &()> GetDomTree,
663 ReuseLoopT ReuseLoop);
664 void analyzeImpl(const DominatorTreeBase<BlockT, false> &DomTree,
665 ReuseLoopT ReuseLoop);
666
667 /// The header of a loop under construction, stashed until the layout carve
668 /// builds the block list.
669 static BlockT *pendingHeader(const LoopT *L) { return L->PendingHeader; }
670
671 /// True if \p L borrows its block list from BlockLayout.
672 static bool hasBorrowedBlocks(const LoopT &L) {
673 return L.BlockCapacity == LoopT::BorrowedCapacity;
674 }
675
676 /// Replace \p L's block list with a private allocation of NewCapacity
677 /// slots. The old storage is abandoned in place so slices sharing it stay
678 /// intact; it is reclaimed when this LoopInfo is cleared.
679 void reallocBlocks(LoopT &L, unsigned NewCapacity) {
680 assert(NewCapacity >= L.BlockLen && "capacity below size");
681 BlockT **New = LoopAllocator.Allocate<BlockT *>(NewCapacity);
682 llvm::copy(L.getBlocks(), New);
683 L.BlockData = New;
684 L.BlockCapacity = NewCapacity;
685 }
686
687 /// Copy \p L's borrowed block list into private storage before a mutation.
688 void materializeBlocks(LoopT &L) {
689 if (hasBorrowedBlocks(L))
690 reallocBlocks(L, L.BlockLen);
691 }
692
693public:
694 /// Return the inner most loop that BB lives in. If a basic block is in no
695 /// loop (for example the entry node), null is returned.
696 LoopT *getLoopFor(const BlockT *BB) const {
697 verifyBlockNumberEpoch(BB->getParent());
698 return lookupLoopFor(BB);
699 }
700
701 /// Same as getLoopFor.
702 const LoopT *operator[](const BlockT *BB) const { return getLoopFor(BB); }
703
704 /// Return the loop nesting level of the specified block. A depth of 0 means
705 /// the block is not inside any loop.
706 unsigned getLoopDepth(const BlockT *BB) const {
707 const LoopT *L = getLoopFor(BB);
708 return L ? L->getLoopDepth() : 0;
709 }
710
711 /// Edge type.
712 using Edge = std::pair<BlockT *, BlockT *>;
713
714 /// Return true if \p L does not have any exit blocks.
715 bool hasNoExitBlocks(const LoopT &L) const;
716
717 /// Return all pairs of (_inside_block_,_outside_block_).
718 void getExitEdges(const LoopT &L, SmallVectorImpl<Edge> &ExitEdges) const;
719
720 /// Return the unique exit block for the latch of \p L, or null if there are
721 /// multiple different exit blocks or the latch is not exiting.
722 BlockT *getUniqueLatchExitBlock(const LoopT &L) const;
723
724 /// Remove every block satisfying \p Pred from \p L's block list, preserving
725 /// the order of the remaining blocks. Only \p L itself is updated, not its
726 /// ancestors or descendants, and not the block-to-loop mapping.
727 template <typename PredicateT>
728 void removeBlocksIf(LoopT &L, PredicateT Pred) {
729 materializeBlocks(L);
730 L.BlockLen = llvm::remove_if(
731 MutableArrayRef<BlockT *>(L.BlockData, L.BlockLen), Pred) -
732 L.BlockData;
733 }
734
735 /// Detach and return the children of \p Parent (the top-level loops if
736 /// \p Parent is null) that satisfy \p Pred, clearing their parent pointers.
737 /// Both the remaining and the returned children keep their relative order.
738 template <typename PredicateT>
740 std::vector<LoopT *> &List = Parent ? Parent->SubLoops : TopLevelLoops;
742 llvm::erase_if(List, [&](LoopT *Child) {
743 if (!Pred(Child))
744 return false;
745 Child->ParentLoop = nullptr;
746 Taken.push_back(Child);
747 return true;
748 });
749 return Taken;
750 }
751
752 /// \brief Find the innermost loop containing both given loops.
753 ///
754 /// \returns the innermost loop containing both \p A and \p B
755 /// or nullptr if there is no such loop.
756 LoopT *getSmallestCommonLoop(LoopT *A, LoopT *B) const;
757 /// \brief Find the innermost loop containing both given blocks.
758 ///
759 /// \returns the innermost loop containing both \p A and \p B
760 /// or nullptr if there is no such loop.
761 LoopT *getSmallestCommonLoop(BlockT *A, BlockT *B) const;
762
763 // True if the block is a loop header node
764 bool isLoopHeader(const BlockT *BB) const {
765 const LoopT *L = getLoopFor(BB);
766 return L && L->getHeader() == BB;
767 }
768
769 /// Return the top-level loops.
770 const std::vector<LoopT *> &getTopLevelLoops() const { return TopLevelLoops; }
771
772 /// This removes the specified top-level loop from this loop info object.
773 /// The loop is not deleted, as it will presumably be inserted into
774 /// another loop.
776 assert(I != end() && "Cannot remove end iterator!");
777 LoopT *L = *I;
778 assert(L->isOutermost() && "Not a top-level loop!");
779 TopLevelLoops.erase(TopLevelLoops.begin() + (I - begin()));
780 return L;
781 }
782
783 /// Change the top-level loop that contains BB to the specified loop.
784 /// This should be used by transformations that restructure the loop hierarchy
785 /// tree.
786 void changeLoopFor(const BlockT *BB, LoopT *L) {
787 verifyBlockNumberEpoch(BB->getParent());
789 if (Number >= BBMap.size()) {
790 unsigned Max =
791 GraphTraits<decltype(BB->getParent())>::getMaxNumber(BB->getParent());
792 assert(Number < Max);
793 BBMap.resize(Max);
794 }
795 BBMap[Number] = L;
796 }
797
798 /// Replace a loop among its siblings (a parent loop's child list or the
799 /// top-level list) with a new loop.
800 void replaceLoop(LoopT *Old, LoopT *New) {
801 assert(!New->ParentLoop && "New loop already has a parent!");
802 LoopT *Parent = Old->ParentLoop;
803 auto &Siblings = Parent ? Parent->SubLoops : TopLevelLoops;
804 auto I = find(Siblings, Old);
805 assert(I != Siblings.end() && "Old loop is not among its siblings!");
806 *I = New;
807 Old->ParentLoop = nullptr;
808 New->ParentLoop = Parent;
809 }
810
811 /// This adds the specified loop to the collection of top-level loops.
812 void addTopLevelLoop(LoopT *New) {
813 assert(New->isOutermost() && "Loop already in subloop!");
814 TopLevelLoops.push_back(New);
815 }
816
817 /// This method completely removes BB from all data structures,
818 /// including all of the Loop objects it is nested in and our mapping from
819 /// BasicBlocks to loops.
820 void removeBlock(BlockT *BB) {
821 verifyBlockNumberEpoch(BB->getParent());
823 if (Number >= BBMap.size())
824 return;
825
826 for (LoopT *L = BBMap[Number]; L; L = L->getParentLoop())
827 L->removeBlockFromLoop(BB);
828 BBMap[Number] = nullptr;
829 }
830
831 // Internals
832
833 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
834 const LoopT *ParentLoop) {
835 if (!SubLoop)
836 return true;
837 if (SubLoop == ParentLoop)
838 return false;
839 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
840 }
841
842 /// Create the loop forest for a function. A dominator tree is needed only for
843 /// an irreducible CFG, where dominance reduces a loop that an edge re-enters
844 /// to the natural loop of its header's backedges.
845 ///@{
846 /// Build a dominator tree if one is needed.
847 void analyze(ParentT F);
848 /// Call \p GetDomTree if a dominator tree is needed.
849 void
850 analyze(ParentT F,
851 function_ref<const DominatorTreeBase<BlockT, false> &()> GetDomTree);
852 /// Analyze the function \p DomTree describes.
854 ///@}
855
856 /// Rebuild the loop forest from the CFG, refilling the existing loop object
857 /// of every block that still heads a loop, so that analyses keyed on loop
858 /// pointers stay valid for the survivors.
859 ///
860 /// Returns the loops whose header no longer heads one, each with its former
861 /// header, in a deterministic order. They are left empty and unlinked; the
862 /// caller must run its deletion callbacks on them and then destroy() them.
863 ///
864 /// Every loop's header must still belong to the function.
867
868 // Debugging
869 void print(raw_ostream &OS) const;
870
871 void verify() const;
872
873 /// Destroy a loop that has been removed from the `LoopInfo` nest.
874 ///
875 /// This runs the destructor of the loop object making it invalid to
876 /// reference afterward. The memory is retained so that the *pointer* to the
877 /// loop remains valid.
878 ///
879 /// The caller is responsible for removing this loop from the loop nest and
880 /// otherwise disconnecting it from the broader `LoopInfo` data structures.
881 /// Callers that don't naturally handle this themselves should probably call
882 /// `erase' instead.
883 void destroy(LoopT *L) {
884 L->~LoopT();
885
886 // Since LoopAllocator is a BumpPtrAllocator, this Deallocate only poisons
887 // \c L, but the pointer remains valid for non-dereferencing uses.
888 LoopAllocator.Deallocate(L);
889 }
890};
891
892} // namespace llvm
893
894#endif // LLVM_SUPPORT_GENERICLOOPINFO_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
This file defines a set of templates that efficiently compute a dominator tree over a generic graph.
Hexagon Hardware Loops
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains some templates that are useful if you are working with the STL at all.
This file defines generic set operations that may be used on set's of different types,...
Value * RHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const_pointer const_iterator
Definition ArrayRef.h:48
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Core dominator tree base class.
Instances of this class are used to represent loops that are detected in the flow graph.
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
static void getInnerLoopsInPreorder(const LoopT &L, SmallVectorImpl< Type > &PreOrderLoops)
Return all inner loops in the loop nest rooted by the loop in preorder, with siblings in forward prog...
typename std::vector< LoopT * >::const_iterator iterator
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
void reserveBlocks(unsigned Size)
interface to do reserve() for Blocks
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate.
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
bool contains(const InstT *Inst) const
Return true if the specified instruction is in this loop.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
void verifyLoop() const
Verify loop structure.
void verifyLoopNest(DenseSet< const LoopT * > *Loops) const
Verify loop structure of this loop and all nested loops.
SmallVector< LoopT *, 4 > getLoopsInPreorder()
typename std::vector< LoopT * >::const_reverse_iterator reverse_iterator
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
SmallVector< const LoopT *, 4 > getLoopsInPreorder() const
Return all loops in the loop nest rooted by the loop in preorder, with siblings in forward program or...
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
BlockT * getHeader() const
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
void getLoopLatches(SmallVectorImpl< BlockT * > &LoopLatches) const
Return all loop latch blocks of this loop.
unsigned getLoopDepth() const
Return the nesting level of this loop.
LoopBase()
This creates an empty loop.
void print(raw_ostream &OS, bool Verbose=false, bool PrintNested=true, unsigned Depth=0) const
Print loop with all the BBs inside it.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
LoopT * removeChildLoop(LoopT *Child)
This removes the specified child from being a subloop of this loop.
iterator_range< block_iterator > blocks() const
block_iterator block_end() const
bool isInvalid() const
Return true if this loop is no longer valid.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
bool contains(const BlockT *BB) const
Return true if the specified basic block is in this loop, using LoopInfo's block-to-loop map.
bool isLoopLatch(const BlockT *BB) const
iterator end() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
reverse_iterator rbegin() const
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
reverse_iterator rend() const
BlockT ** BlockData
BlockT * PendingHeader
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
LoopT * getOutermostLoop()
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
void setParentLoop(LoopT *L)
This is a raw interface for bypassing addChildLoop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
void getUniqueNonLatchExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop except successors from Latch block are not considered...
iterator begin() const
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
block_iterator block_begin() const
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
typename ArrayRef< BlockT * >::const_iterator block_iterator
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
This class builds and contains all of the top-level loop structures in the specified function.
const std::vector< LoopT * > & getTopLevelLoops() const
Return the top-level loops.
SmallVector< std::pair< LoopT *, BlockT * >, 4 > recompute(const DominatorTreeBase< BlockT, false > &DomTree)
Rebuild the loop forest from the CFG, refilling the existing loop object of every block that still he...
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
void analyze(const DominatorTreeBase< BlockT, false > &DomTree)
Analyze the function DomTree describes.
bool hasNoExitBlocks(const LoopT &L) const
Return true if L does not have any exit blocks.
SmallVector< LoopT *, 4 > getLoopsInReverseSiblingPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in reverse p...
void print(raw_ostream &OS) const
reverse_iterator rend() const
iterator end() const
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
LoopInfoBase(LoopInfoBase &&Arg)
const LoopT * operator[](const BlockT *BB) const
Same as getLoopFor.
void analyze(ParentT F, function_ref< const DominatorTreeBase< BlockT, false > &()> GetDomTree)
Call GetDomTree if a dominator tree is needed.
bool isLoopHeader(const BlockT *BB) const
LoopT * removeLoop(iterator I)
This removes the specified top-level loop from this loop info object.
LoopT * getSmallestCommonLoop(BlockT *A, BlockT *B) const
Find the innermost loop containing both given blocks.
LoopInfoBase()=default
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
LoopT * getSmallestCommonLoop(LoopT *A, LoopT *B) const
Find the innermost loop containing both given loops.
typename std::vector< Loop * >::const_iterator iterator
typename std::vector< Loop * >::const_reverse_iterator reverse_iterator
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
void analyze(ParentT F)
Create the loop forest for a function.
void replaceLoop(LoopT *Old, LoopT *New)
Replace a loop among its siblings (a parent loop's child list or the top-level list) with a new loop.
SmallVector< LoopT *, 4 > takeChildrenIf(LoopT *Parent, PredicateT Pred)
Detach and return the children of Parent (the top-level loops if Parent is null) that satisfy Pred,...
iterator begin() const
BlockT * getUniqueLatchExitBlock(const LoopT &L) const
Return the unique exit block for the latch of L, or null if there are multiple different exit blocks ...
void getExitEdges(const LoopT &L, SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
static bool isNotAlreadyContainedIn(const LoopT *SubLoop, const LoopT *ParentLoop)
void removeBlocksIf(LoopT &L, PredicateT Pred)
Remove every block satisfying Pred from L's block list, preserving the order of the remaining blocks.
reverse_iterator rbegin() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
std::pair< BasicBlock *, BasicBlock * > Edge
LoopInfoBase & operator=(LoopInfoBase &&RHS)
void destroy(LoopT *L)
Destroy a loop that has been removed from the LoopInfo nest.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
iterator end() const
Definition ArrayRef.h:339
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr bool GraphHasNodeNumbers
Indicate whether a GraphTraits<NodeT>::getNumber() is supported.
auto remove_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1784
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878