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 /// This is used when splitting loops up. It replaces the OldChild entry in
378 /// our children list with NewChild, and updates the parent pointer of
379 /// OldChild to be null and the NewChild to be this loop.
380 /// This updates the loop depth of the new child.
381 void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
382
383 /// Add the specified loop to be a child of this loop.
384 /// This updates the loop depth of the new child.
385 void addChildLoop(LoopT *NewChild) {
386 assert(!isInvalid() && "Loop not in a valid state!");
387 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
388 NewChild->ParentLoop = static_cast<LoopT *>(this);
389 SubLoops.push_back(NewChild);
390 }
391
392 /// This removes the specified child from being a subloop of this loop. The
393 /// loop is not deleted, as it will presumably be inserted into another loop.
395 assert(!isInvalid() && "Loop not in a valid state!");
396 assert(I != SubLoops.end() && "Cannot remove end iterator!");
397 LoopT *Child = *I;
398 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
399 SubLoops.erase(SubLoops.begin() + (I - begin()));
400 Child->ParentLoop = nullptr;
401 return Child;
402 }
403
404 /// This removes the specified child from being a subloop of this loop. The
405 /// loop is not deleted, as it will presumably be inserted into another loop.
406 LoopT *removeChildLoop(LoopT *Child) {
407 return removeChildLoop(llvm::find(*this, Child));
408 }
409
410 /// This adds a basic block directly to the basic block list.
411 /// This should only be used by transformations that create new loops. Other
412 /// transformations should use addBasicBlockToLoop.
413 void addBlockEntry(BlockT *BB) {
414 assert(!isInvalid() && "Loop not in a valid state!");
415 // A borrowed slice or a full private allocation grows into fresh private
416 // storage before appending.
417 if (BlockCapacity == BorrowedCapacity || BlockLen == BlockCapacity)
418 LI->reallocBlocks(*static_cast<LoopT *>(this),
419 std::max(2 * BlockLen, 4u));
420 BlockData[BlockLen++] = BB;
421 }
422
423 /// interface to do reserve() for Blocks
424 void reserveBlocks(unsigned Size) {
425 assert(!isInvalid() && "Loop not in a valid state!");
426 if (BlockCapacity < Size)
427 LI->reallocBlocks(*static_cast<LoopT *>(this), Size);
428 }
429
430 /// interface to do reserve() for SubLoops
431 void reserveSubLoops(unsigned Size) {
432 assert(!isInvalid() && "Loop not in a valid state!");
433 SubLoops.reserve(Size);
434 }
435
436 /// This method is used to move BB (which must be part of this loop) to be the
437 /// loop header of the loop (the block that dominates all others).
438 void moveToHeader(BlockT *BB) {
439 assert(!isInvalid() && "Loop not in a valid state!");
440 if (BlockData[0] == BB)
441 return;
442 LI->materializeBlocks(*static_cast<LoopT *>(this));
443 for (unsigned i = 0;; ++i) {
444 assert(i != BlockLen && "Loop does not contain BB!");
445 if (BlockData[i] == BB) {
446 BlockData[i] = BlockData[0];
447 BlockData[0] = BB;
448 return;
449 }
450 }
451 }
452
453 /// This removes the specified basic block from the current loop, updating the
454 /// Blocks as appropriate. This does not update the mapping in the LoopInfo
455 /// class.
456 void removeBlockFromLoop(BlockT *BB) {
457 assert(!isInvalid() && "Loop not in a valid state!");
458 LI->materializeBlocks(*static_cast<LoopT *>(this));
459 MutableArrayRef<BlockT *> Blocks(BlockData, BlockLen);
460 auto *I = llvm::find(Blocks, BB);
461 assert(I != Blocks.end() && "N is not in this list!");
462 std::move(I + 1, Blocks.end(), I);
463 --BlockLen;
464 }
465
466 /// Verify loop structure
467 void verifyLoop() const;
468
469 /// Verify loop structure of this loop and all nested loops.
471
472 /// Returns true if the loop is annotated parallel.
473 ///
474 /// Derived classes can override this method using static template
475 /// polymorphism.
476 bool isAnnotatedParallel() const { return false; }
477
478 /// Print loop with all the BBs inside it.
479 void print(raw_ostream &OS, bool Verbose = false, bool PrintNested = true,
480 unsigned Depth = 0) const;
481
482protected:
483 friend class LoopInfoBase<BlockT, LoopT>;
484
485 /// This creates an empty loop.
486 LoopBase() : ParentLoop(nullptr) {}
487
488 // Since loop passes like SCEV are allowed to key analysis results off of
489 // `Loop` pointers, we cannot re-use pointers within a loop pass manager.
490 // This means loop passes should not be `delete` ing `Loop` objects directly
491 // (and risk a later `Loop` allocation re-using the address of a previous one)
492 // but should be using LoopInfo::markAsRemoved, which keeps around the `Loop`
493 // pointer till the end of the lifetime of the `LoopInfo` object.
494 //
495 // To make it easier to follow this rule, we mark the destructor as
496 // non-public.
498 for (auto *SubLoop : SubLoops)
499 SubLoop->~LoopT();
500
501#if LLVM_ENABLE_ABI_BREAKING_CHECKS
502 IsInvalid = true;
503#endif
504 SubLoops.clear();
505 // The block storage is reclaimed by the owning LoopInfo.
506 BlockData = nullptr;
507 BlockLen = 0;
508 BlockCapacity = 0;
509 ParentLoop = nullptr;
510 }
511};
512
513template <class BlockT, class LoopT>
515 Loop.print(OS);
516 return OS;
517}
518
519//===----------------------------------------------------------------------===//
520/// This class builds and contains all of the top-level loop
521/// structures in the specified function.
522///
523
524template <class BlockT, class LoopT> class LoopInfoBase {
526 "LoopInfo requires GraphTraits<BlockT *>::getNumber (see "
527 "GraphHasNodeNumbers)");
528
529 // Mapping of each block, indexed by its number, to the innermost loop it
530 // occurs in (or null).
532
533 using ParentT = decltype(std::declval<BlockT *>()->getParent());
534 ParentT ParentPtr = nullptr;
535 unsigned BlockNumberEpoch;
536
537 std::vector<LoopT *> TopLevelLoops;
538
539 // Shared reverse postorder layout of the in-loop blocks. Each initial loop is
540 // a slice of this array, subloop slices nested inside their parent's.
541 std::unique_ptr<BlockT *[]> BlockLayout;
542
543 BumpPtrAllocator LoopAllocator;
544
545 friend class LoopBase<BlockT, LoopT>;
546 friend class LoopInfo;
547
548 void operator=(const LoopInfoBase &) = delete;
549 LoopInfoBase(const LoopInfoBase &) = delete;
550
551public:
552 LoopInfoBase() = default;
554
555 LoopInfoBase(LoopInfoBase &&Arg)
556 : BBMap(std::move(Arg.BBMap)),
557 TopLevelLoops(std::move(Arg.TopLevelLoops)),
558 BlockLayout(std::move(Arg.BlockLayout)),
559 LoopAllocator(std::move(Arg.LoopAllocator)) {
560 ParentPtr = Arg.ParentPtr;
561 BlockNumberEpoch = Arg.BlockNumberEpoch;
562 resetLoopInfoOwners();
563 // We have to clear the arguments top level loops as we've taken ownership.
564 Arg.TopLevelLoops.clear();
565 }
566 LoopInfoBase &operator=(LoopInfoBase &&RHS) {
567 BBMap = std::move(RHS.BBMap);
568 ParentPtr = RHS.ParentPtr;
569 BlockNumberEpoch = RHS.BlockNumberEpoch;
570
571 for (auto *L : TopLevelLoops)
572 L->~LoopT();
573
574 TopLevelLoops = std::move(RHS.TopLevelLoops);
575 BlockLayout = std::move(RHS.BlockLayout);
576 LoopAllocator = std::move(RHS.LoopAllocator);
577 resetLoopInfoOwners();
578 RHS.TopLevelLoops.clear();
579 return *this;
580 }
581
583 BBMap.clear();
584
585 for (auto *L : TopLevelLoops)
586 L->~LoopT();
587 TopLevelLoops.clear();
588 BlockLayout.reset();
589 LoopAllocator.Reset();
590 }
591
592 LoopT *AllocateLoop() {
593 LoopT *Storage = LoopAllocator.Allocate<LoopT>();
594 LoopT *L = new (Storage) LoopT();
595 L->LI = this;
596 return L;
597 }
598
599 /// iterator/begin/end - The interface to the top-level loops in the current
600 /// function.
601 ///
602 using iterator = typename std::vector<LoopT *>::const_iterator;
604 typename std::vector<LoopT *>::const_reverse_iterator;
605 iterator begin() const { return TopLevelLoops.begin(); }
606 iterator end() const { return TopLevelLoops.end(); }
607 reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
608 reverse_iterator rend() const { return TopLevelLoops.rend(); }
609 bool empty() const { return TopLevelLoops.empty(); }
610
611 /// Return all of the loops in the function in preorder across the loop
612 /// nests, with siblings in forward program order.
613 ///
614 /// Note that because loops form a forest of trees, preorder is equivalent to
615 /// reverse postorder.
617
618 /// Return all of the loops in the function in preorder across the loop
619 /// nests, with siblings in *reverse* program order.
620 ///
621 /// Note that because loops form a forest of trees, preorder is equivalent to
622 /// reverse postorder.
623 ///
624 /// Also note that this is *not* a reverse preorder. Only the siblings are in
625 /// reverse program order.
627
628private:
629 // Point every loop's owning-LoopInfo back-pointer at this object. Called
630 // after a move.
631 void resetLoopInfoOwners() {
632 SmallVector<LoopT *, 8> Worklist(TopLevelLoops.begin(),
633 TopLevelLoops.end());
634 while (!Worklist.empty()) {
635 LoopT *L = Worklist.pop_back_val();
636 L->LI = this;
637 Worklist.append(L->begin(), L->end());
638 }
639 }
640
641 /// Verify that used block numbers are still valid.
642 void
643 verifyBlockNumberEpoch(const std::remove_pointer_t<ParentT> *BBParent) const {
644 assert(ParentPtr == BBParent &&
645 "loop info queried with block of other function");
646 assert(BlockNumberEpoch ==
647 GraphTraits<ParentT>::getNumberEpoch(ParentPtr) &&
648 "loop info used with outdated block numbers");
649 }
650
651 // Look up BB's innermost loop in the block-to-loop map; BB must belong to
652 // this function.
653 LoopT *lookupLoopFor(const BlockT *BB) const {
654 unsigned Number = GraphTraits<const BlockT *>::getNumber(BB);
655 return Number < BBMap.size() ? BBMap[Number] : nullptr;
656 }
657
658 /// AllocateLoop for analyze(): stash \p Header (see pendingHeader).
659 /// getHeader() only works once the layout carve has replaced the stash with
660 /// the loop's block list.
661 LoopT *allocateLoop(BlockT *Header) {
662 LoopT *L = AllocateLoop();
663 L->PendingHeader = Header;
664 return L;
665 }
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 void discoverAndMapSubloop(LoopT *L, BlockT *Header,
672 ArrayRef<BlockT *> Backedges,
673 const DominatorTreeBase<BlockT, false> &DomTree);
674
675 /// True if \p L borrows its block list from BlockLayout.
676 static bool hasBorrowedBlocks(const LoopT &L) {
677 return L.BlockCapacity == LoopT::BorrowedCapacity;
678 }
679
680 /// Replace \p L's block list with a private allocation of NewCapacity
681 /// slots. The old storage is abandoned in place so slices sharing it stay
682 /// intact; it is reclaimed when this LoopInfo is cleared.
683 void reallocBlocks(LoopT &L, unsigned NewCapacity) {
684 assert(NewCapacity >= L.BlockLen && "capacity below size");
685 BlockT **New = LoopAllocator.Allocate<BlockT *>(NewCapacity);
686 llvm::copy(L.getBlocks(), New);
687 L.BlockData = New;
688 L.BlockCapacity = NewCapacity;
689 }
690
691 /// Copy \p L's borrowed block list into private storage before a mutation.
692 void materializeBlocks(LoopT &L) {
693 if (hasBorrowedBlocks(L))
694 reallocBlocks(L, L.BlockLen);
695 }
696
697public:
698 /// Return the inner most loop that BB lives in. If a basic block is in no
699 /// loop (for example the entry node), null is returned.
700 LoopT *getLoopFor(const BlockT *BB) const {
701 verifyBlockNumberEpoch(BB->getParent());
702 return lookupLoopFor(BB);
703 }
704
705 /// Same as getLoopFor.
706 const LoopT *operator[](const BlockT *BB) const { return getLoopFor(BB); }
707
708 /// Return the loop nesting level of the specified block. A depth of 0 means
709 /// the block is not inside any loop.
710 unsigned getLoopDepth(const BlockT *BB) const {
711 const LoopT *L = getLoopFor(BB);
712 return L ? L->getLoopDepth() : 0;
713 }
714
715 /// Edge type.
716 using Edge = std::pair<BlockT *, BlockT *>;
717
718 /// Return true if \p L does not have any exit blocks.
719 bool hasNoExitBlocks(const LoopT &L) const;
720
721 /// Return all pairs of (_inside_block_,_outside_block_).
722 void getExitEdges(const LoopT &L, SmallVectorImpl<Edge> &ExitEdges) const;
723
724 /// Return the unique exit block for the latch of \p L, or null if there are
725 /// multiple different exit blocks or the latch is not exiting.
726 BlockT *getUniqueLatchExitBlock(const LoopT &L) const;
727
728 /// Remove every block satisfying \p Pred from \p L's block list, preserving
729 /// the order of the remaining blocks. Only \p L itself is updated, not its
730 /// ancestors or descendants, and not the block-to-loop mapping.
731 template <typename PredicateT>
732 void removeBlocksIf(LoopT &L, PredicateT Pred) {
733 materializeBlocks(L);
734 L.BlockLen = llvm::remove_if(
735 MutableArrayRef<BlockT *>(L.BlockData, L.BlockLen), Pred) -
736 L.BlockData;
737 }
738
739 /// Remove every block satisfying \p Pred from \p Start and each of its
740 /// ancestors up to but not including \p Stop, which must be null or an
741 /// ancestor of \p Start; a null \p Stop walks to the top level.
742 template <typename PredicateT>
743 void removeBlocksFromLoopAndAncestors(LoopT *Start, LoopT *Stop,
744 PredicateT Pred) {
745 for (LoopT *Cur = Start; Cur != Stop; Cur = Cur->getParentLoop())
746 removeBlocksIf(*Cur, Pred);
747 }
748
749 /// Detach and return the children of \p Parent (the top-level loops if
750 /// \p Parent is null) that satisfy \p Pred, clearing their parent pointers.
751 /// Both the remaining and the returned children keep their relative order.
752 template <typename PredicateT>
754 std::vector<LoopT *> &List = Parent ? Parent->SubLoops : TopLevelLoops;
756 llvm::erase_if(List, [&](LoopT *Child) {
757 if (!Pred(Child))
758 return false;
759 Child->ParentLoop = nullptr;
760 Taken.push_back(Child);
761 return true;
762 });
763 return Taken;
764 }
765
766 /// \brief Find the innermost loop containing both given loops.
767 ///
768 /// \returns the innermost loop containing both \p A and \p B
769 /// or nullptr if there is no such loop.
770 LoopT *getSmallestCommonLoop(LoopT *A, LoopT *B) const;
771 /// \brief Find the innermost loop containing both given blocks.
772 ///
773 /// \returns the innermost loop containing both \p A and \p B
774 /// or nullptr if there is no such loop.
775 LoopT *getSmallestCommonLoop(BlockT *A, BlockT *B) const;
776
777 // True if the block is a loop header node
778 bool isLoopHeader(const BlockT *BB) const {
779 const LoopT *L = getLoopFor(BB);
780 return L && L->getHeader() == BB;
781 }
782
783 /// Return the top-level loops.
784 const std::vector<LoopT *> &getTopLevelLoops() const { return TopLevelLoops; }
785
786 /// This removes the specified top-level loop from this loop info object.
787 /// The loop is not deleted, as it will presumably be inserted into
788 /// another loop.
790 assert(I != end() && "Cannot remove end iterator!");
791 LoopT *L = *I;
792 assert(L->isOutermost() && "Not a top-level loop!");
793 TopLevelLoops.erase(TopLevelLoops.begin() + (I - begin()));
794 return L;
795 }
796
797 /// Change the top-level loop that contains BB to the specified loop.
798 /// This should be used by transformations that restructure the loop hierarchy
799 /// tree.
800 void changeLoopFor(const BlockT *BB, LoopT *L) {
801 verifyBlockNumberEpoch(BB->getParent());
803 if (Number >= BBMap.size()) {
804 unsigned Max =
805 GraphTraits<decltype(BB->getParent())>::getMaxNumber(BB->getParent());
806 assert(Number < Max);
807 BBMap.resize(Max);
808 }
809 BBMap[Number] = L;
810 }
811
812 /// Replace the specified loop in the top-level loops list with the indicated
813 /// loop.
814 void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop) {
815 auto I = find(TopLevelLoops, OldLoop);
816 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
817 *I = NewLoop;
818 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
819 "Loops already embedded into a subloop!");
820 }
821
822 /// This adds the specified loop to the collection of top-level loops.
823 void addTopLevelLoop(LoopT *New) {
824 assert(New->isOutermost() && "Loop already in subloop!");
825 TopLevelLoops.push_back(New);
826 }
827
828 /// This method completely removes BB from all data structures,
829 /// including all of the Loop objects it is nested in and our mapping from
830 /// BasicBlocks to loops.
831 void removeBlock(BlockT *BB) {
832 verifyBlockNumberEpoch(BB->getParent());
834 if (Number >= BBMap.size())
835 return;
836
837 for (LoopT *L = BBMap[Number]; L; L = L->getParentLoop())
838 L->removeBlockFromLoop(BB);
839 BBMap[Number] = nullptr;
840 }
841
842 // Internals
843
844 static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
845 const LoopT *ParentLoop) {
846 if (!SubLoop)
847 return true;
848 if (SubLoop == ParentLoop)
849 return false;
850 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
851 }
852
853 /// Create the loop forest using a stable algorithm.
855
856 // Debugging
857 void print(raw_ostream &OS) const;
858
859 void verify(const DominatorTreeBase<BlockT, false> &DomTree) const;
860
861 /// Destroy a loop that has been removed from the `LoopInfo` nest.
862 ///
863 /// This runs the destructor of the loop object making it invalid to
864 /// reference afterward. The memory is retained so that the *pointer* to the
865 /// loop remains valid.
866 ///
867 /// The caller is responsible for removing this loop from the loop nest and
868 /// otherwise disconnecting it from the broader `LoopInfo` data structures.
869 /// Callers that don't naturally handle this themselves should probably call
870 /// `erase' instead.
871 void destroy(LoopT *L) {
872 L->~LoopT();
873
874 // Since LoopAllocator is a BumpPtrAllocator, this Deallocate only poisons
875 // \c L, but the pointer remains valid for non-dereferencing uses.
876 LoopAllocator.Deallocate(L);
877 }
878};
879
880} // namespace llvm
881
882#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 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 reserveSubLoops(unsigned Size)
interface to do reserve() for SubLoops
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.
void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild)
This is used when splitting loops up.
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.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
void analyze(const DominatorTreeBase< BlockT, false > &DomTree)
Create the loop forest using a stable algorithm.
bool hasNoExitBlocks(const LoopT &L) const
Return true if L does not have any exit blocks.
void removeBlocksFromLoopAndAncestors(LoopT *Start, LoopT *Stop, PredicateT Pred)
Remove every block satisfying Pred from Start and each of its ancestors up to but not including Stop,...
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
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
Replace the specified loop in the top-level loops list with the indicated loop.
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.
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.
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.
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