38 #ifndef LLVM_ANALYSIS_LOOPINFO_H 39 #define LLVM_ANALYSIS_LOOPINFO_H 60 class InductionDescriptor;
62 class MemorySSAUpdater;
64 class ScalarEvolution;
74 template <
class BlockT,
class LoopT>
class LoopBase {
77 std::vector<LoopT *> SubLoops;
80 std::vector<BlockT *> Blocks;
84 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 86 bool IsInvalid =
false;
100 for (
const LoopT *CurLoop = ParentLoop; CurLoop;
101 CurLoop = CurLoop->ParentLoop)
121 return contains(L->getParentLoop());
127 return DenseBlockSet.
count(BB);
131 template <
class InstT>
bool contains(
const InstT *Inst)
const {
144 typedef typename std::vector<LoopT *>::const_iterator
iterator;
170 return Blocks.size();
183 return DenseBlockSet;
189 return DenseBlockSet;
199 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 211 for (
const auto *Succ : children<const BlockT *>(BB)) {
229 return std::find(PredBegin, PredEnd, BB) != PredEnd;
235 unsigned NumBackEdges = 0;
289 typedef std::pair<BlockT *, BlockT *>
Edge;
324 template <
class Type>
328 PreOrderWorklist.
append(L.rbegin(), L.rend());
330 while (!PreOrderWorklist.
empty()) {
334 PreOrderWorklist.
append(L->rbegin(), L->rend());
343 const LoopT *CurLoop =
static_cast<const LoopT *
>(
this);
346 return PreOrderLoops;
350 LoopT *CurLoop =
static_cast<LoopT *
>(
this);
353 return PreOrderLoops;
377 assert(!NewChild->ParentLoop &&
"NewChild already has a parent!");
378 NewChild->ParentLoop =
static_cast<LoopT *
>(
this);
379 SubLoops.push_back(NewChild);
386 assert(I != SubLoops.end() &&
"Cannot remove end iterator!");
388 assert(Child->ParentLoop ==
this &&
"Child is not a child of this loop!");
389 SubLoops.erase(SubLoops.begin() + (I -
begin()));
390 Child->ParentLoop =
nullptr;
405 Blocks.push_back(BB);
418 Blocks.reserve(size);
427 for (
unsigned i = 0;; ++i) {
428 assert(i != Blocks.size() &&
"Loop does not contain BB!");
429 if (Blocks[i] == BB) {
430 Blocks[i] = Blocks[0];
442 auto I =
find(Blocks, BB);
443 assert(
I != Blocks.end() &&
"N is not in this list!");
446 DenseBlockSet.
erase(BB);
470 explicit LoopBase(BlockT *BB) : ParentLoop(nullptr) {
471 Blocks.push_back(BB);
485 for (
auto *SubLoop : SubLoops)
488 #if LLVM_ENABLE_ABI_BREAKING_CHECKS 493 DenseBlockSet.
clear();
494 ParentLoop =
nullptr;
498 template <
class BlockT,
class LoopT>
520 : Start(
std::move(Start)), End(
std::move(End)) {}
527 explicit operator bool()
const {
return Start && End; }
531 bool isLoopInvariant(
const Value *V)
const;
535 bool hasLoopInvariantOperands(
const Instruction *
I)
const;
545 bool makeLoopInvariant(
Value *V,
bool &Changed,
558 bool makeLoopInvariant(
Instruction *I,
bool &Changed,
569 PHINode *getCanonicalInductionVariable()
const;
573 bool getIncomingAndBackEdge(
BasicBlock *&Incoming,
685 : L(Loop), InitialIVValue(I), StepInst(SI), StepValue(SV),
686 FinalIVValue(F), SE(SE) {}
691 Value &InitialIVValue;
731 bool isAuxiliaryInductionVariable(
PHINode &AuxIndVar,
757 bool isGuarded()
const {
return (getLoopGuardBranch() !=
nullptr); }
782 bool isLoopSimplifyForm()
const;
785 bool isSafeToClone()
const;
807 MDNode *getLoopID()
const;
815 void setLoopID(
MDNode *LoopID)
const;
823 void setLoopAlreadyUnrolled();
826 void dumpVerbose()
const;
840 if (Header->hasName())
841 return Header->getName();
842 return "<unnamed loop>";
859 template <
class BlockT,
class LoopT>
class LoopInfoBase {
862 std::vector<LoopT *> TopLevelLoops;
876 : BBMap(
std::move(
Arg.BBMap)),
877 TopLevelLoops(
std::move(
Arg.TopLevelLoops)),
878 LoopAllocator(
std::move(
Arg.LoopAllocator)) {
880 Arg.TopLevelLoops.clear();
883 BBMap = std::move(RHS.BBMap);
885 for (
auto *L : TopLevelLoops)
888 TopLevelLoops = std::move(RHS.TopLevelLoops);
889 LoopAllocator = std::move(RHS.LoopAllocator);
890 RHS.TopLevelLoops.clear();
897 for (
auto *L : TopLevelLoops)
899 TopLevelLoops.clear();
900 LoopAllocator.
Reset();
904 LoopT *Storage = LoopAllocator.
Allocate<LoopT>();
905 return new (Storage) LoopT(std::forward<ArgsTy>(
Args)...);
911 typedef typename std::vector<LoopT *>::const_iterator
iterator;
914 iterator
begin()
const {
return TopLevelLoops.begin(); }
915 iterator
end()
const {
return TopLevelLoops.end(); }
916 reverse_iterator
rbegin()
const {
return TopLevelLoops.rbegin(); }
917 reverse_iterator
rend()
const {
return TopLevelLoops.rend(); }
918 bool empty()
const {
return TopLevelLoops.empty(); }
942 const LoopT *
operator[](
const BlockT *BB)
const {
return getLoopFor(BB); }
947 const LoopT *L = getLoopFor(BB);
948 return L ? L->getLoopDepth() : 0;
953 const LoopT *L = getLoopFor(BB);
954 return L && L->getHeader() == BB;
961 assert(I !=
end() &&
"Cannot remove end iterator!");
963 assert(!L->getParentLoop() &&
"Not a top-level loop!");
964 TopLevelLoops.erase(TopLevelLoops.begin() + (I -
begin()));
982 auto I =
find(TopLevelLoops, OldLoop);
983 assert(
I != TopLevelLoops.end() &&
"Old loop not at top level!");
985 assert(!NewLoop->ParentLoop && !OldLoop->ParentLoop &&
986 "Loops already embedded into a subloop!");
991 assert(!New->getParentLoop() &&
"Loop already in subloop!");
992 TopLevelLoops.push_back(New);
999 auto I = BBMap.
find(BB);
1000 if (
I != BBMap.
end()) {
1001 for (LoopT *L =
I->second; L; L = L->getParentLoop())
1002 L->removeBlockFromLoop(BB);
1011 const LoopT *ParentLoop) {
1014 if (SubLoop == ParentLoop)
1016 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
1054 void operator=(
const LoopInfo &) =
delete;
1063 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
1077 void erase(
Loop *L);
1109 "Can't reason about IPO!");
1119 auto *OldLoop = getLoopFor(OldBB);
1120 auto *NewLoop = getLoopFor(NewBB);
1122 if (OldLoop == NewLoop)
1127 auto Contains = [](
const Loop *Outer,
const Loop *Inner) {
1128 return !Outer || Outer->
contains(Inner);
1138 if (!Contains(NewLoop, OldLoop)) {
1140 auto *UI = cast<Instruction>(U.getUser());
1141 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
1143 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
1151 if (!Contains(OldLoop, NewLoop)) {
1153 if (isa<PHINode>(Inst))
1165 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
1233 void verifyAnalysis()
const override;
LoopInfo::iterator ChildIteratorType
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 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.
std::vector< BlockT * > & getBlocksVector()
Return a direct, mutable handle to the blocks vector so that we can mutate it efficiently with techni...
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. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
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...
llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode *> AddAttrs)
Create a new LoopID after the loop has been transformed.
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.
The main scalar evolution driver.
bool isRotatedForm() const
Return true if the loop is in rotated form.
SmallVector< LoopT *, 4 > getLoopsInPreorder()
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.
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...
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.
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
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.
Direction
An enum for the direction of the loop.
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...
Value & getFinalIVValue() const
Get the final value of the loop induction variable.
This is an important class for using LLVM in a threaded context.
Allocate memory in an ever growing pool, as if by bump-pointer.
Conditional or Unconditional Branch instruction.
std::pair< BlockT *, BlockT * > Edge
Edge type.
static ChildIteratorType child_begin(NodeRef N)
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.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
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.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
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...
void getUniqueNonLatchExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop except successors from Latch block are not considered...
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
Value & getInitialIVValue() const
Get the initial value of the loop induction variable.
void getExitEdges(SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
Instruction & getStepInst() const
Get the instruction that updates the loop induction variable.
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.
A struct for saving information about induction variables.
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)
LLVM_NODISCARD T pop_back_val()
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.
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, Align Alignment)
Allocate space at the specified alignment.
LoopInfo::iterator ChildIteratorType
bool isLoopHeader(const BlockT *BB) const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
reverse_iterator rbegin() const
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.
LLVM_NODISCARD bool empty() const
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.
Below are some utilities to get the loop guard, loop bounds and induction variable, and to check if a given phinode is an auxiliary induction variable, if the loop is guarded, and if the loop is canonical.
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
Value * getStepValue() const
Get the step that the loop induction variable gets updated by in each loop iteration.
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.
bool isGuarded() const
Return true iff the loop is.
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
static PHINode * getInductionVariable(Loop *L, ScalarEvolution *SE)
This class builds and contains all of the top-level loop structures in the specified function...