15 #ifndef LLVM_ANALYSIS_LOOPINFOIMPL_H
16 #define LLVM_ANALYSIS_LOOPINFOIMPL_H
34 template<
class BlockT,
class LoopT>
37 for (
const auto BB : blocks())
38 for (
const auto &Succ : children<BlockT*>(BB))
48 template<
class BlockT,
class LoopT>
51 getExitingBlocks(ExitingBlocks);
52 if (ExitingBlocks.
size() == 1)
53 return ExitingBlocks[0];
60 template<
class BlockT,
class LoopT>
63 for (
const auto BB : blocks())
64 for (
const auto &Succ : children<BlockT*>(BB))
72 template<
class BlockT,
class LoopT>
75 getExitBlocks(ExitBlocks);
76 if (ExitBlocks.
size() == 1)
82 template<
class BlockT,
class LoopT>
85 for (
const auto BB : blocks())
86 for (
const auto &Succ : children<BlockT*>(BB))
100 template<
class BlockT,
class LoopT>
103 BlockT *Out = getLoopPredecessor();
104 if (!Out)
return nullptr;
107 if (!Out->isLegalToHoistInto())
112 typename BlockTraits::ChildIteratorType
SI = BlockTraits::child_begin(Out);
114 if (SI != BlockTraits::child_end(Out))
126 template<
class BlockT,
class LoopT>
129 BlockT *Out =
nullptr;
132 BlockT *Header = getHeader();
135 if (Out && Out != Pred)
142 assert(Out &&
"Header of loop has no predecessors from outside loop?");
148 template<
class BlockT,
class LoopT>
150 BlockT *Header = getHeader();
151 BlockT *Latch =
nullptr;
154 if (Latch)
return nullptr;
172 template<
class BlockT,
class LoopT>
176 if (!Blocks.empty()) {
177 auto SameHeader = LIB[getHeader()];
178 assert(
contains(SameHeader) && getHeader() == SameHeader->getHeader()
179 &&
"Incorrect LI specified for this loop!");
182 assert(NewBB &&
"Cannot add a null basic block to the loop!");
183 assert(!LIB[NewBB] &&
"BasicBlock already in the loop!");
185 LoopT *
L =
static_cast<LoopT *
>(
this);
188 LIB.BBMap[NewBB] =
L;
193 L = L->getParentLoop();
201 template<
class BlockT,
class LoopT>
204 assert(OldChild->ParentLoop ==
this &&
"This loop is already broken!");
205 assert(!NewChild->ParentLoop &&
"NewChild already has a parent!");
206 typename std::vector<LoopT *>::iterator
I =
find(SubLoops, OldChild);
207 assert(I != SubLoops.end() &&
"OldChild not in loop!");
209 OldChild->ParentLoop =
nullptr;
210 NewChild->ParentLoop =
static_cast<LoopT *
>(
this);
214 template<
class BlockT,
class LoopT>
217 assert(!Blocks.empty() &&
"Loop header is missing");
221 getExitBlocks(ExitBBs);
223 VisitSet.
insert(ExitBBs.begin(), ExitBBs.end());
232 for ( ; BI != BE; ++BI) {
238 "Loop block has no in-loop successors!");
242 [&](BlockT *B){
return contains(B);}) &&
243 "Loop block has no in-loop predecessors!");
252 if (BB == getHeader()) {
253 assert(!OutsideLoopPreds.
empty() &&
"Loop is unreachable!");
254 }
else if (!OutsideLoopPreds.
empty()) {
258 BlockT *EntryBB = &BB->getParent()->front();
260 for (
unsigned i = 0, e = OutsideLoopPreds.
size(); i != e; ++i)
261 assert(CB != OutsideLoopPreds[i] &&
262 "Loop has multiple entry points!");
265 "Loop contains function entry block!");
270 if (VisitedBBs.
size() != getNumBlocks()) {
271 dbgs() <<
"The following blocks are unreachable in the loop: ";
272 for (
auto BB : Blocks) {
273 if (!VisitedBBs.
count(BB)) {
274 dbgs() << *BB <<
"\n";
277 assert(
false &&
"Unreachable block in loop");
283 for (
block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
286 "Loop does not contain all the blocks of a subloop!");
292 "Loop is not a subloop of its parent!");
298 template<
class BlockT,
class LoopT>
301 Loops->
insert(static_cast<const LoopT *>(
this));
306 (*I)->verifyLoopNest(Loops);
309 template<
class BlockT,
class LoopT>
311 bool Verbose)
const {
312 OS.
indent(Depth*2) <<
"Loop at depth " << getLoopDepth()
315 BlockT *
H = getHeader();
316 for (
unsigned i = 0; i < getBlocks().size(); ++i) {
317 BlockT *BB = getBlocks()[i];
320 BB->printAsOperand(OS,
false);
323 if (BB == H) OS <<
"<header>";
324 if (isLoopLatch(BB)) OS <<
"<latch>";
325 if (isLoopExiting(BB)) OS <<
"<exiting>";
332 (*I)->print(OS, Depth+2);
343 template <
class BlockT,
class LoopT>
349 unsigned NumBlocks = 0;
350 unsigned NumSubloops = 0;
353 std::vector<BlockT *> ReverseCFGWorklist(Backedges.
begin(), Backedges.
end());
354 while (!ReverseCFGWorklist.empty()) {
355 BlockT *PredBB = ReverseCFGWorklist.back();
356 ReverseCFGWorklist.pop_back();
366 if (PredBB == L->getHeader())
369 ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
370 InvBlockTraits::child_begin(PredBB),
371 InvBlockTraits::child_end(PredBB));
375 while (LoopT *Parent = Subloop->getParentLoop())
383 Subloop->setParentLoop(L);
385 NumBlocks += Subloop->getBlocks().capacity();
386 PredBB = Subloop->getHeader();
393 ReverseCFGWorklist.push_back(Pred);
397 L->getSubLoopsVector().reserve(NumSubloops);
398 L->reserveBlocks(NumBlocks);
402 template<
class BlockT,
class LoopT>
405 typedef typename BlockTraits::ChildIteratorType SuccIterTy;
419 template<
class BlockT,
class LoopT>
428 template<
class BlockT,
class LoopT>
430 LoopT *Subloop = LI->getLoopFor(Block);
431 if (Subloop && Block == Subloop->getHeader()) {
434 if (Subloop->getParentLoop())
435 Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
437 LI->addTopLevelLoop(Subloop);
441 Subloop->reverseBlock(1);
443 Subloop->getSubLoopsVector().end());
445 Subloop = Subloop->getParentLoop();
447 for (; Subloop; Subloop = Subloop->getParentLoop())
448 Subloop->addBlockEntry(Block);
465 template <
class BlockT,
class LoopT>
472 BlockT *Header = DomNode->getBlock();
484 if (!Backedges.
empty()) {
485 LoopT *
L =
new LoopT(Header);
495 template <
class BlockT,
class LoopT>
503 for (LoopT *RootL :
reverse(*
this)) {
505 "Must start with an empty preorder walk worklist.");
511 PreOrderWorklist.
append(L->rbegin(), L->rend());
513 }
while (!PreOrderWorklist.
empty());
516 return PreOrderLoops;
519 template <
class BlockT,
class LoopT>
528 for (LoopT *RootL : *
this) {
530 "Must start with an empty preorder walk worklist.");
536 PreOrderWorklist.
append(L->begin(), L->end());
538 }
while (!PreOrderWorklist.
empty());
541 return PreOrderLoops;
545 template<
class BlockT,
class LoopT>
547 for (
unsigned i = 0; i < TopLevelLoops.size(); ++i)
548 TopLevelLoops[i]->print(OS);
551 E = BBMap.end();
I !=
E; ++
I)
552 OS <<
"BB '" <<
I->first->getName() <<
"' level = "
553 <<
I->second->getLoopDepth() <<
"\n";
557 template <
typename T>
564 template <
class BlockT,
class LoopT>
568 LoopHeaders[L.getHeader()] = &
L;
574 template <
class BlockT,
class LoopT>
577 BlockT *
H = L->getHeader();
578 BlockT *OtherH = OtherL->getHeader();
580 "Mismatched headers even though found in the same map entry!");
582 assert(L->getLoopDepth() == OtherL->getLoopDepth() &&
583 "Mismatched loop depth!");
584 const LoopT *ParentL =
L, *OtherParentL = OtherL;
586 assert(ParentL->getHeader() == OtherParentL->getHeader() &&
587 "Mismatched parent loop headers!");
588 ParentL = ParentL->getParentLoop();
589 OtherParentL = OtherParentL->getParentLoop();
592 for (
const LoopT *SubL : *L) {
593 BlockT *SubH = SubL->getHeader();
594 const LoopT *OtherSubL = OtherLoopHeaders.
lookup(SubH);
595 assert(OtherSubL &&
"Inner loop is missing in computed loop info!");
596 OtherLoopHeaders.
erase(SubH);
600 std::vector<BlockT *> BBs = L->getBlocks();
601 std::vector<BlockT *> OtherBBs = OtherL->getBlocks();
603 "Mismatched basic blocks in the loops!");
607 template <
class BlockT,
class LoopT>
612 assert(!(*I)->getParentLoop() &&
"Top-level loop has a parent!");
613 (*I)->verifyLoopNest(&Loops);
618 for (
auto &Entry : BBMap) {
619 const BlockT *BB = Entry.first;
620 LoopT *
L = Entry.second;
622 assert(L->contains(BB) &&
"orphaned block");
633 for (LoopT *
L : OtherLI)
639 for (LoopT *
L : *
this) {
640 BlockT *Header = L->getHeader();
641 const LoopT *OtherL = OtherLoopHeaders.
lookup(Header);
642 assert(OtherL &&
"Top level loop is missing in computed loop info!");
644 OtherLoopHeaders.
erase(Header);
651 if (!OtherLoopHeaders.
empty()) {
652 for (
const auto &HeaderAndLoop : OtherLoopHeaders)
653 dbgs() <<
"Found new loop: " << *HeaderAndLoop.second <<
"\n";
void push_back(const T &Elt)
const_iterator end(StringRef path)
Get end iterator over path.
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
bool compareVectors(std::vector< T > &BB1, std::vector< T > &BB2)
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
Implements a dense probed hash-table based set.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild)
This is used when splitting loops up.
void insertIntoLoop(BlockT *Block)
Add a single Block to its ancestor loops in PostOrder.
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
return AArch64::GPR64RegClass contains(Reg)
std::vector< LoopT * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
void getExitEdges(SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
static void discoverAndMapSubloop(LoopT *L, ArrayRef< BlockT * > Backedges, LoopInfoBase< BlockT, LoopT > *LI, const DomTreeBase< BlockT > &DomTree)
Stable LoopInfo Analysis - Build a loop tree using stable iterators so the result does / not depend o...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
LLVM_NODISCARD bool empty() const
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void traverse(BlockT *EntryBlock)
Top-level driver for the forward DFS within the loop.
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
void verifyLoop() const
Verify loop structure.
Core dominator tree base class.
static void compareLoops(const LoopT *L, const LoopT *OtherL, DenseMap< BlockT *, const LoopT * > &OtherLoopHeaders)
bool erase(const KeyT &Val)
PopulateLoopsDFS(LoopInfoBase< BlockT, LoopT > *li)
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
df_ext_iterator< T, SetTy > df_ext_end(const T &G, SetTy &S)
std::pair< iterator, bool > insert(const ValueT &V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void analyze(const DominatorTreeBase< BlockT, false > &DomTree)
Create the loop forest using a stable algorithm.
df_ext_iterator< T, SetTy > df_ext_begin(const T &G, SetTy &S)
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
iterator_range< po_iterator< T > > post_order(const T &G)
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
void addInnerLoopsToHeadersMap(DenseMap< BlockT *, const LoopT * > &LoopHeaders, const LoopInfoBase< BlockT, LoopT > &LI, const LoopT &L)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
void for_each(Policy policy, IterTy Begin, IterTy End, FuncTy Fn)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
LLVM_NODISCARD T pop_back_val()
std::pair< iterator, bool > insert(NodeRef N)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
std::vector< BlockT * >::const_iterator block_iterator
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
void verifyLoopNest(DenseSet< const LoopT * > *Loops) const
Verify loop structure of this loop and all nested loops.
llvm_unreachable("Unknown RegBank!")
void emplace_back(ArgTypes &&...Args)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
LLVM_NODISCARD bool empty() const
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
static const Function * getParent(const Value *V)
This class implements an extremely fast bulk output stream that can only output to a stream...
void print(raw_ostream &OS, unsigned Depth=0, bool Verbose=false) const
Print loop with all the BBs inside it.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
std::vector< LoopT * >::const_iterator iterator
Populate all loop data in a stable order during a single forward DFS.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.