36 #ifndef LLVM_ANALYSIS_LOOPINFO_H 37 #define LLVM_ANALYSIS_LOOPINFO_H 69 template <
class BlockT,
class LoopT>
class LoopBase {
72 std::vector<LoopT *> SubLoops;
75 std::vector<BlockT *> Blocks;
79 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 81 bool IsInvalid =
false;
95 for (
const LoopT *CurLoop = ParentLoop; CurLoop;
96 CurLoop = CurLoop->ParentLoop)
116 return contains(L->getParentLoop());
122 return DenseBlockSet.
count(BB);
126 template <
class InstT>
bool contains(
const InstT *Inst)
const {
139 typedef typename std::vector<LoopT *>::const_iterator
iterator;
165 return Blocks.size();
178 return DenseBlockSet;
184 return DenseBlockSet;
194 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 205 for (
const auto &Succ : children<const BlockT *>(BB)) {
223 return std::find(PredBegin, PredEnd, BB) != PredEnd;
229 unsigned NumBackEdges = 0;
279 typedef std::pair<const BlockT *, const BlockT *>
Edge;
333 assert(!NewChild->ParentLoop &&
"NewChild already has a parent!");
334 NewChild->ParentLoop =
static_cast<LoopT *
>(
this);
335 SubLoops.push_back(NewChild);
342 assert(I != SubLoops.end() &&
"Cannot remove end iterator!");
344 assert(Child->ParentLoop ==
this &&
"Child is not a child of this loop!");
345 SubLoops.erase(SubLoops.begin() + (I -
begin()));
346 Child->ParentLoop =
nullptr;
361 Blocks.push_back(BB);
374 Blocks.reserve(size);
383 for (
unsigned i = 0;; ++i) {
384 assert(i != Blocks.size() &&
"Loop does not contain BB!");
385 if (Blocks[i] == BB) {
386 Blocks[i] = Blocks[0];
398 auto I =
find(Blocks, BB);
399 assert(
I != Blocks.end() &&
"N is not in this list!");
402 DenseBlockSet.
erase(BB);
426 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
427 Blocks.push_back(BB);
441 for (
auto *SubLoop : SubLoops)
444 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 449 DenseBlockSet.
clear();
450 ParentLoop =
nullptr;
454 template <
class BlockT,
class LoopT>
476 : Start(
std::move(Start)), End(
std::move(End)) {}
483 explicit operator bool()
const {
return Start && End; }
491 bool hasLoopInvariantOperands(
const Instruction *
I)
const;
501 bool makeLoopInvariant(
Value *V,
bool &Changed,
513 bool makeLoopInvariant(
Instruction *I,
bool &Changed,
523 PHINode *getCanonicalInductionVariable()
const;
533 bool isLoopSimplifyForm()
const;
536 bool isSafeToClone()
const;
558 MDNode *getLoopID()
const;
566 void setLoopID(
MDNode *LoopID)
const;
574 void setLoopAlreadyUnrolled();
577 void dumpVerbose()
const;
591 if (Header->hasName())
592 return Header->getName();
593 return "<unnamed loop>";
610 template <
class BlockT,
class LoopT>
class LoopInfoBase {
613 std::vector<LoopT *> TopLevelLoops;
627 : BBMap(
std::move(
Arg.BBMap)),
628 TopLevelLoops(
std::move(
Arg.TopLevelLoops)),
629 LoopAllocator(
std::move(
Arg.LoopAllocator)) {
631 Arg.TopLevelLoops.clear();
634 BBMap = std::move(RHS.BBMap);
636 for (
auto *L : TopLevelLoops)
639 TopLevelLoops = std::move(RHS.TopLevelLoops);
640 LoopAllocator = std::move(RHS.LoopAllocator);
641 RHS.TopLevelLoops.clear();
648 for (
auto *L : TopLevelLoops)
650 TopLevelLoops.clear();
651 LoopAllocator.
Reset();
655 LoopT *Storage = LoopAllocator.
Allocate<LoopT>();
656 return new (Storage) LoopT(std::forward<ArgsTy>(
Args)...);
662 typedef typename std::vector<LoopT *>::const_iterator
iterator;
665 iterator
begin()
const {
return TopLevelLoops.begin(); }
666 iterator
end()
const {
return TopLevelLoops.end(); }
667 reverse_iterator
rbegin()
const {
return TopLevelLoops.rbegin(); }
668 reverse_iterator
rend()
const {
return TopLevelLoops.rend(); }
669 bool empty()
const {
return TopLevelLoops.empty(); }
693 const LoopT *
operator[](
const BlockT *BB)
const {
return getLoopFor(BB); }
698 const LoopT *L = getLoopFor(BB);
699 return L ? L->getLoopDepth() : 0;
704 const LoopT *L = getLoopFor(BB);
705 return L && L->getHeader() == BB;
712 assert(I !=
end() &&
"Cannot remove end iterator!");
714 assert(!L->getParentLoop() &&
"Not a top-level loop!");
715 TopLevelLoops.erase(TopLevelLoops.begin() + (I -
begin()));
733 auto I =
find(TopLevelLoops, OldLoop);
734 assert(
I != TopLevelLoops.end() &&
"Old loop not at top level!");
736 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
737 "Loops already embedded into a subloop!");
742 assert(!New->getParentLoop() &&
"Loop already in subloop!");
743 TopLevelLoops.push_back(New);
750 auto I = BBMap.
find(BB);
751 if (
I != BBMap.
end()) {
752 for (LoopT *L =
I->second; L; L = L->getParentLoop())
753 L->removeBlockFromLoop(BB);
762 const LoopT *ParentLoop) {
765 if (SubLoop == ParentLoop)
767 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
805 void operator=(
const LoopInfo &) =
delete;
814 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
860 "Can't reason about IPO!");
870 auto *OldLoop = getLoopFor(OldBB);
871 auto *NewLoop = getLoopFor(NewBB);
873 if (OldLoop == NewLoop)
878 auto Contains = [](
const Loop *Outer,
const Loop *Inner) {
879 return !Outer || Outer->
contains(Inner);
889 if (!Contains(NewLoop, OldLoop)) {
891 auto *UI = cast<Instruction>(U.getUser());
892 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
894 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
902 if (!Contains(OldLoop, NewLoop)) {
904 if (isa<PHINode>(Inst))
916 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
986 void verifyAnalysis()
const override;
LoopInfo::iterator ChildIteratorType
void destroy(LoopT *L)
Destroy a loop that has been removed from the LoopInfo nest.
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
iterator_range< use_iterator > uses()
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
std::vector< BlockT * > & getBlocksVector()
Return a direct, mutable handle to the blocks vector so that we can mutate it efficiently with techni...
static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT)
Perform a quick domtree based check for loop invariance assuming that V is used within the loop...
This class represents lattice values for constants.
void setParentLoop(LoopT *L)
This is a raw interface for bypassing addChildLoop.
ArrayRef< BlockT * >::const_iterator block_iterator
A Module instance is used to store all the information related to an LLVM module. ...
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
Implements a dense probed hash-table based set.
unsigned getLoopDepth() const
Return the nesting level of this loop.
void push_back(const T &Elt)
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...
void reserveBlocks(unsigned size)
interface to do reserve() for Blocks
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
std::pair< const BlockT *, const BlockT * > Edge
Edge type.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild)
This is used when splitting loops up.
std::vector< LoopT * > & getSubLoopsVector()
const SmallPtrSetImpl< const BlockT * > & getBlocksSet() const
Return a direct, immutable handle to the blocks set.
LoopBase()
This creates an empty loop.
Instances of this class are used to represent loops that are detected in the flow graph...
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
bool isInvalid() const
Return true if this loop is no longer valid.
void print(raw_ostream &OS, unsigned Depth=0, bool Verbose=false) const
Print loop with all the BBs inside it.
amdgpu Simplify well known AMD library false Value Value const Twine & Name
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
void initializeLoopInfoWrapperPassPass(PassRegistry &)
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
SmallPtrSetImpl< const BlockT * > & getBlocksSet()
Return a direct, mutable handle to the blocks set so that we can mutate it efficiently.
A Use represents the edge between a Value definition and its users.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
static bool isNotAlreadyContainedIn(const LoopT *SubLoop, const LoopT *ParentLoop)
std::vector< LoopT * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
void getLoopLatches(SmallVectorImpl< BlockT *> &LoopLatches) const
Return all loop latch blocks of this loop.
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
Printer pass for the LoopAnalysis results.
Analysis pass that exposes the LoopInfo for a function.
void Deallocate(const void *Ptr, size_t Size)
BlockT * getHeader() const
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
const LoopInfo & getLoopInfo() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
std::vector< LoopT * >::const_iterator iterator
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
A CRTP mix-in to automatically provide informational APIs needed for passes.
MDNode * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a loop.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
LoopInfo & operator=(LoopInfo &&RHS)
LocRange(DebugLoc Start, DebugLoc End)
const DebugLoc & getEnd() const
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
iterator find(const_arg_type_t< KeyT > Val)
Core dominator tree base class.
static bool runOnFunction(Function &F, bool PostInlining)
bool erase(const KeyT &Val)
reverse_iterator rend() const
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
reverse_iterator rbegin() const
LLVM Basic Block Representation.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
Allocate memory in an ever growing pool, as if by bump-pointer.
static ChildIteratorType child_begin(NodeRef N)
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment)
Allocate space at the specified alignment.
LoopPrinterPass(raw_ostream &OS)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
A CRTP mix-in that provides informational APIs needed for analysis passes.
Represent the analysis usage information of a pass.
bool contains(const BlockT *BB) const
Return true if the specified basic block is in this loop.
FunctionPass class - This class is used to implement most global optimizations.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
const Function * getFunction() const
Return the function this instruction belongs to.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
A range representing the start and end location of a loop.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
void getExitEdges(SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LoopInfoBase & operator=(LoopInfoBase &&RHS)
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
BlockVerifier::State From
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc)
Checks if moving a specific instruction can break LCSSA in any loop.
reverse_iterator rend() const
Verifier pass for the LoopAnalysis results.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
LoopT * removeLoop(iterator I)
This removes the specified top-level loop from this loop info object.
bool contains(const InstT *Inst) const
Return true if the specified instruction is in this loop.
MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
static NodeRef getEntryNode(const Loop *L)
LoopT * AllocateLoop(ArgsTy &&... Args)
static ChildIteratorType child_end(NodeRef N)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
std::vector< LoopT * >::const_reverse_iterator reverse_iterator
bool isLoopLatch(const BlockT *BB) const
A range adaptor for a pair of iterators.
LoopInfo::iterator ChildIteratorType
bool isLoopHeader(const BlockT *BB) const
reverse_iterator rbegin() const
amdgpu Simplify well known AMD library false Value Value * Arg
LoopT * getParentLoop() const
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
void verifyLoopNest(DenseSet< const LoopT *> *Loops) const
Verify loop structure of this loop and all nested loops.
static NodeRef getEntryNode(Loop *L)
const DebugLoc & getStart() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
StringRef getName() const
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
static ChildIteratorType child_end(NodeRef N)
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
Replace the specified loop in the top-level loops list with the indicated loop.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
block_iterator block_end() const
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate...
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...
API to communicate dependencies between analyses during invalidation.
LoopT * removeChildLoop(LoopT *Child)
This removes the specified child from being a subloop of this loop.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
const LoopT * operator[](const BlockT *BB) const
Same as getLoopFor.
void reverseBlock(unsigned from)
interface to reverse Blocks[from, end of loop] in this loop
This class implements an extremely fast bulk output stream that can only output to a stream...
The legacy pass manager's analysis pass to compute loop information.
void verifyLoop() const
Verify loop structure.
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
LoopInfoBase(LoopInfoBase &&Arg)
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
std::vector< LoopT * >::const_reverse_iterator reverse_iterator
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
This header defines various interfaces for pass management in LLVM.
iterator_range< block_iterator > blocks() const
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
block_iterator block_begin() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
A special type used by analysis passes to provide an address that identifies that particular analysis...
static ChildIteratorType child_begin(NodeRef N)
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
const BasicBlock * getParent() const
This class builds and contains all of the top-level loop structures in the specified function...