14#ifndef LLVM_SUPPORT_GENERICLOOPINFOIMPL_H
15#define LLVM_SUPPORT_GENERICLOOPINFOIMPL_H
31template <
class BlockT,
class LoopT>
35 for (
const auto BB :
blocks())
46template <
class BlockT,
class LoopT>
49 auto notInLoop = [&](BlockT *BB) {
return !
contains(BB); };
50 auto isExitBlock = [&](BlockT *BB,
bool AllowRepeats) -> BlockT * {
51 assert(!AllowRepeats &&
"Unexpected parameter value.");
62template <
class BlockT,
class LoopT>
66 for (
const auto BB :
blocks())
75template <
class BlockT,
class LoopT>
78 assert(!L->isInvalid() &&
"Loop not in a valid state!");
79 auto notInLoop = [&](BlockT *BB,
80 bool AllowRepeats) -> std::pair<BlockT *, bool> {
81 assert(AllowRepeats == Unique &&
"Unexpected parameter value.");
82 return {!L->contains(BB) ? BB :
nullptr,
false};
84 auto singleExitBlock = [&](BlockT *BB,
85 bool AllowRepeats) -> std::pair<BlockT *, bool> {
86 assert(AllowRepeats == Unique &&
"Unexpected parameter value.");
93template <
class BlockT,
class LoopT>
105template <
class BlockT,
class LoopT>
110template <
class BlockT,
class LoopT>
116 for (BlockT *EB : UniqueExitBlocks)
126template <
class BlockT,
class LoopT,
typename PredicateT>
130 assert(!L->isInvalid() &&
"Loop not in a valid state!");
133 for (BlockT *BB : Filtered)
140template <
class BlockT,
class LoopT>
144 [](
const BlockT *BB) {
return true; });
147template <
class BlockT,
class LoopT>
151 assert(Latch &&
"Latch block must exists");
153 [Latch](
const BlockT *BB) {
return BB != Latch; });
156template <
class BlockT,
class LoopT>
161template <
class BlockT,
class LoopT>
164 BlockT *Latch = L.getLoopLatch();
165 assert(Latch &&
"Latch block must exists");
166 auto IsExitBlock = [&L](BlockT *BB,
bool AllowRepeats) -> BlockT * {
167 assert(!AllowRepeats &&
"Unexpected parameter value.");
168 return !L.contains(BB) ? BB :
nullptr;
174template <
class BlockT,
class LoopT>
177 for (
const auto BB : L.blocks())
179 if (!L.contains(Succ))
185template <
class BlockT>
188template <
class BlockT>
195 return Block->isLegalToHoistInto();
208template <
class BlockT,
class LoopT>
233template <
class BlockT,
class LoopT>
237 BlockT *Out =
nullptr;
243 if (Out && Out != Pred)
254template <
class BlockT,
class LoopT>
258 BlockT *Latch =
nullptr;
280template <
class BlockT,
class LoopT>
288 "Incorrect LI specified for this loop!");
291 assert(NewBB &&
"Cannot add a null basic block to the loop!");
292 assert(!LIB[NewBB] &&
"BasicBlock already in the loop!");
294 LoopT *L =
static_cast<LoopT *
>(
this);
301 L->addBlockEntry(NewBB);
302 L = L->getParentLoop();
310template <
class BlockT,
class LoopT>
314 assert(OldChild->ParentLoop ==
this &&
"This loop is already broken!");
315 assert(!NewChild->ParentLoop &&
"NewChild already has a parent!");
316 typename std::vector<LoopT *>::iterator
I =
find(SubLoops, OldChild);
317 assert(
I != SubLoops.end() &&
"OldChild not in loop!");
319 OldChild->ParentLoop =
nullptr;
320 NewChild->ParentLoop =
static_cast<LoopT *
>(
this);
324template <
class BlockT,
class LoopT>
343 "Loop block has no in-loop successors!");
347 "Loop block has no in-loop predecessors!");
355 assert(!OutsideLoopPreds.empty() &&
"Loop is unreachable!");
356 }
else if (!OutsideLoopPreds.empty()) {
360 BlockT *EntryBB = &BB->getParent()->front();
362 for (
unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
363 assert(CB != OutsideLoopPreds[i] &&
364 "Loop has multiple entry points!");
367 "Loop contains function entry block!");
373 dbgs() <<
"The following blocks are unreachable in the loop: ";
376 dbgs() << *BB <<
"\n";
379 assert(
false &&
"Unreachable block in loop");
385 for (
block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
388 "Loop does not contain all the blocks of a subloop!");
394 "Loop is not a subloop of its parent!");
400template <
class BlockT,
class LoopT>
404 Loops->insert(
static_cast<const LoopT *
>(
this));
409 (*I)->verifyLoopNest(
Loops);
412template <
class BlockT,
class LoopT>
414 bool PrintNested,
unsigned Depth)
const {
418 OS <<
"Loop at depth " <<
getLoopDepth() <<
" containing: ";
421 for (
unsigned i = 0; i <
getBlocks().size(); ++i) {
426 BB->printAsOperand(OS,
false);
445 (*I)->print(OS,
false, PrintNested,
Depth + 2);
457template <
class BlockT,
class LoopT>
458void LoopInfoBase<BlockT, LoopT>::discoverAndMapSubloop(
463 unsigned NumSubloops = 0;
466 std::vector<BlockT *> ReverseCFGWorklist(Backedges.
begin(), Backedges.
end());
467 while (!ReverseCFGWorklist.empty()) {
468 BlockT *PredBB = ReverseCFGWorklist.back();
469 ReverseCFGWorklist.pop_back();
471 LoopT *Subloop = getLoopFor(PredBB);
477 changeLoopFor(PredBB, L);
478 if (PredBB == Header)
481 ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
482 InvBlockTraits::child_begin(PredBB),
483 InvBlockTraits::child_end(PredBB));
486 Subloop = Subloop->getOutermostLoop();
493 Subloop->setParentLoop(L);
495 PredBB = pendingHeader(Subloop);
501 if (getLoopFor(Pred) != Subloop)
502 ReverseCFGWorklist.push_back(Pred);
506 L->reserveSubLoops(NumSubloops);
518template <
class BlockT,
class LoopT>
521 ParentPtr = DomRoot->
getBlock()->getParent();
531 PreorderNodes[
Node->getDFSNumIn()] =
Node;
533 bool HasLoops =
false;
535 BlockT *Header = DomNode->getBlock();
542 if (BackedgeNode && DomTree.
dominates(DomNode, BackedgeNode))
546 if (!Backedges.
empty()) {
548 LoopT *L = allocateLoop(Header);
549 discoverAndMapSubloop(L, Header, Backedges, DomTree);
562 LoopT *L = lookupLoopFor(BB);
567 if (BB != pendingHeader(L))
570 if (LoopT *Parent = L->getParentLoop())
571 Parent->BlockLen += L->BlockLen;
573 TopLevelLoops.push_back(L);
576 assert(!LoopsPO.
empty() &&
"discovered loops but found no header");
578 BlockLayout.reset(
new BlockT *[PO.
size()]);
579 BlockT **RootCursor = BlockLayout.get();
581 if (L->BlockCapacity == 0) {
584 if (LoopT *Parent = L->getParentLoop()) {
585 assert(Parent->BlockCapacity != 0 &&
586 "parent slice not carved before child");
587 L->BlockData = Parent->BlockData + Parent->BlockCapacity;
588 Parent->BlockCapacity += L->BlockLen;
589 Parent->SubLoops.push_back(L);
591 L->BlockData = RootCursor;
592 RootCursor += L->BlockLen;
596 L->BlockData[L->BlockCapacity++] = BB;
601 for (LoopT *L : LoopsPO) {
602 assert(L->BlockCapacity == L->BlockLen &&
"layout slice not fully used");
603 L->BlockCapacity = LoopT::BorrowedCapacity;
607template <
class BlockT,
class LoopT>
618 LoopT::getInnerLoopsInPreorder(*RootL, PreOrderLoops);
621 return PreOrderLoops;
624template <
class BlockT,
class LoopT>
633 for (LoopT *RootL : *
this) {
635 "Must start with an empty preorder walk worklist.");
641 PreOrderWorklist.
append(L->begin(), L->end());
643 }
while (!PreOrderWorklist.
empty());
646 return PreOrderLoops;
649template <
class BlockT,
class LoopT>
657 unsigned DepthA =
A->getLoopDepth(), DepthB =
B->getLoopDepth();
658 for (; DepthA > DepthB; --DepthA)
659 A =
A->getParentLoop();
660 for (; DepthB > DepthA; --DepthB)
661 B =
B->getParentLoop();
667 A =
A->getParentLoop();
668 B =
B->getParentLoop();
674template <
class BlockT,
class LoopT>
681template <
class BlockT,
class LoopT>
683 for (
unsigned i = 0; i < TopLevelLoops.size(); ++i)
684 TopLevelLoops[i]->
print(OS);
694template <
class BlockT,
class LoopT>
698 LoopHeaders[L.getHeader()] = &L;
704template <
class BlockT,
class LoopT>
707 BlockT *
H = L->getHeader();
708 BlockT *OtherH = OtherL->getHeader();
710 "Mismatched headers even though found in the same map entry!");
712 assert(L->getLoopDepth() == OtherL->getLoopDepth() &&
713 "Mismatched loop depth!");
714 const LoopT *ParentL = L, *OtherParentL = OtherL;
716 assert(ParentL->getHeader() == OtherParentL->getHeader() &&
717 "Mismatched parent loop headers!");
718 ParentL = ParentL->getParentLoop();
719 OtherParentL = OtherParentL->getParentLoop();
722 for (
const LoopT *SubL : *L) {
723 BlockT *SubH = SubL->getHeader();
724 const LoopT *OtherSubL = OtherLoopHeaders.
lookup(SubH);
725 assert(OtherSubL &&
"Inner loop is missing in computed loop info!");
730 std::vector<BlockT *> BBs = L->getBlocks();
731 std::vector<BlockT *> OtherBBs = OtherL->getBlocks();
733 "Mismatched basic blocks in the loops!");
737template <
class BlockT,
class LoopT>
742 assert((*I)->isOutermost() &&
"Top-level loop has a parent!");
743 (*I)->verifyLoopNest(&
Loops);
749 for (
const LoopT *L :
Loops)
750 assert(L->LI ==
this &&
"Loop has a stale owning-LoopInfo back-pointer");
757 while (!Worklist.
empty()) {
761 for (
const BlockT *BB : L->getBlocks()) {
766 Worklist.
append(L->begin(), L->end());
772 "BBMap should point to the innermost loop containing the block");
783 for (LoopT *L : OtherLI)
789 for (LoopT *L : *
this) {
790 BlockT *Header = L->getHeader();
791 const LoopT *OtherL = OtherLoopHeaders.
lookup(Header);
792 assert(OtherL &&
"Top level loop is missing in computed loop info!");
794 OtherLoopHeaders.
erase(Header);
801 if (!OtherLoopHeaders.
empty()) {
802 for (
const auto &HeaderAndLoop : OtherLoopHeaders)
803 dbgs() <<
"Found new loop: " << *HeaderAndLoop.second <<
"\n";
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const Function * getParent(const Value *V)
bbsections Prepares for basic block by splitting functions into clusters of basic blocks
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isExitBlock(BasicBlock *BB, const SmallVectorImpl< BasicBlock * > &ExitBlocks)
Return true if the specified block is in the list.
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
bool erase(const KeyT &Val)
Implements a dense probed hash-table based set.
Base class for the actual dominator tree node.
unsigned getDFSNumOut() const
Core dominator tree base class.
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void updateDFSNumbers() const
updateDFSNumbers - Assign In and Out numbers to the nodes while walking dominator tree in dfs order.
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
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.
typename std::vector< Loop * >::const_iterator iterator
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of 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.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this 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.
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 isLoopLatch(const BlockT *BB) 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< BasicBlock * > getBlocks() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
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...
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
typename ArrayRef< BasicBlock * >::const_iterator block_iterator
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
This class builds and contains all of the top-level loop structures in the specified function.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
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.
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
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< LoopT * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
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).
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void changeLoopFor(const BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
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.
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
decltype(&BlockT::isLegalToHoistInto) has_hoist_check
llvm::is_detected< has_hoist_check, BlockT > detect_has_hoist_check
bool isLegalToHoistInto(BlockT *Block)
SFINAE functions that dispatch to the isLegalToHoistInto member function or return false,...
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
static void compareLoops(const LoopT *L, const LoopT *OtherL, DenseMap< BlockT *, const LoopT * > &OtherLoopHeaders)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
DominatorTreeBase< T, false > DomTreeBase
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
std::pair< BlockT *, bool > getExitBlockHelper(const LoopBase< BlockT, LoopT > *L, bool Unique)
getExitBlock - If getExitBlocks would return exactly one block, return that block.
std::pair< T *, bool > find_singleton_nested(R &&Range, Predicate P, bool AllowRepeats=false)
Return a pair consisting of the single value in Range that satisfies P(<member of Range> ,...
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
void addInnerLoopsToHeadersMap(DenseMap< BlockT *, const LoopT * > &LoopHeaders, const LoopInfoBase< BlockT, LoopT > &LI, const LoopT &L)
void getUniqueExitBlocksHelper(const LoopT *L, SmallVectorImpl< BlockT * > &ExitBlocks, PredicateT Pred)
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
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.
bool compareVectors(std::vector< T > &BB1, std::vector< T > &BB2)
iterator_range< df_iterator< T > > depth_first(const T &G)
std::pair< iterator, bool > insert(NodeRef N)