1//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===// 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 7//===----------------------------------------------------------------------===// 9// This file defines the LoopInfo class that is used to identify natural loops 10// and determine the loop depth of various nodes of the CFG. Note that the 11// loops identified may actually be several natural loops that share the same 12// header node... not just a single natural loop. 14//===----------------------------------------------------------------------===// 26#include "llvm/Config/llvm-config.h" 43// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops. 47// Always verify loopinfo if expensive checking is enabled. 48#ifdef EXPENSIVE_CHECKS 57//===----------------------------------------------------------------------===// 64returntrue;
// All non-instructions are loop invariant 68returnall_of(
I->operands(), [
this](
Value *V) { return isLoopInvariant(V); });
76returntrue;
// All non-instructions are loop-invariant. 82// Test if the value is already loop-invariant. 87if (
I->mayReadFromMemory())
89// EH block instructions are immobile. 92// Determine the insertion point, unless one was given. 95// Without a preheader, hoisting is not feasible. 100// Don't hoist instructions with loop-variant operands. 101for (
Value *Operand :
I->operands())
112// There is possibility of hoisting this instruction above some arbitrary 113// condition. Any metadata defined on it can be control dependent on this 114// condition. Conservatively strip it here so that we don't give any wrong 115// information to the optimizer. 116I->dropUnknownNonDebugMetadata();
135returnfalse;
// dead loop 138returnfalse;
// multiple backedges? 147assert(
Incoming && Backedge &&
"expected non-null incoming and backedges");
158// Loop over all of the PHI nodes, looking for a canonical indvar. 166if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
167if (
ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
174/// Get the latch condition instruction. 177if (
BranchInst *BI = dyn_cast_or_null<BranchInst>(Latch->getTerminator()))
178if (BI->isConditional())
179return dyn_cast<ICmpInst>(BI->getCondition());
184/// Return the final value of the loop induction variable if found. 187ICmpInst *LatchCmpInst = L.getLatchCmpInst();
193if (Op0 == &IndVar || Op0 == &StepInst)
196if (Op1 == &IndVar || Op1 == &StepInst)
202std::optional<Loop::LoopBounds>
211if (!InitialIVValue || !StepInst)
217Value *StepValue =
nullptr;
218if (SE.
getSCEV(StepInstOp1) == Step)
219 StepValue = StepInstOp1;
220elseif (SE.
getSCEV(StepInstOp0) == Step)
221 StepValue = StepInstOp0;
227returnLoopBounds(L, *InitialIVValue, *StepInst, StepValue, *FinalIVValue,
235assert(Latch &&
"Expecting valid latch");
242"Expecting the latch compare instruction to be a CmpInst");
244// Need to inverse the predicate when first successor is not the loop 250if (LatchCmpInst->
getOperand(0) == &getFinalIVValue())
253// Need to flip strictness of the predicate when the latch compare instruction 254// is not using StepInst 255if (LatchCmpInst->
getOperand(0) == &getStepInst() ||
256 LatchCmpInst->
getOperand(1) == &getStepInst())
259// Cannot flip strictness of NE and EQ 264if (
D == Direction::Increasing)
267if (
D == Direction::Decreasing)
270// If cannot determine the direction, then unable to find the canonical 277 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&getStepInst())))
278if (
constSCEV *StepRecur = StepAddRecExpr->getStepRecurrence(SE)) {
279if (SE.isKnownPositive(StepRecur))
280return Direction::Increasing;
281if (SE.isKnownNegative(StepRecur))
282return Direction::Decreasing;
285return Direction::Unknown;
300assert(Header &&
"Expected a valid loop header");
308for (
PHINode &IndVar : Header->phis()) {
314Value *StepInst = IndVar.getIncomingValueForBlock(Latch);
317// IndVar = phi[{InitialValue, preheader}, {StepInst, latch}] 318// StepInst = IndVar + step 319// cmp = StepInst < FinalValue 320if (StepInst == LatchCmpOp0 || StepInst == LatchCmpOp1)
324// IndVar = phi[{InitialValue, preheader}, {StepInst, latch}] 325// StepInst = IndVar + step 326// cmp = IndVar < FinalValue 327if (&IndVar == LatchCmpOp0 || &IndVar == LatchCmpOp1)
344// Located in the loop header 349// No uses outside of the loop 359// The step instruction opcode should be add or sub. 364// Incremented by a loop invariant step for each loop iteration 374"Expecting a loop with valid preheader and latch");
376// Loop should be in rotate form. 380// Disallow loops with more than one unique exit block, as we do not verify 381// that GuardOtherSucc post dominates all exit blocks. 400// Check if ExitFromLatch (or any BasicBlock which is an empty unique 401// successor of ExitFromLatch) is equal to GuardOtherSucc. If 402// skipEmptyBlockUntil returns GuardOtherSucc, then the guard branch for the 403// loop is GuardBI (return GuardBI), otherwise return nullptr. 405/*CheckUniquePred=*/true) ==
425if (!Step || !Step->
isOne())
431// Check that 'BB' doesn't have any uses outside of the 'L' 435// Tokens can't be used in PHI nodes and live-out tokens prevent loop 436// optimizations, so for the purposes of considered LCSSA form, we 438if (IgnoreTokens &&
I.getType()->isTokenTy())
441for (
constUse &U :
I.uses()) {
442constInstruction *UI = cast<Instruction>(U.getUser());
445// For practical purposes, we consider that the use in a PHI 446// occurs in the respective predecessor block. For more info, 447// see the `phi` doc in LangRef and the LCSSA doc. 448if (
constPHINode *
P = dyn_cast<PHINode>(UI))
449 UserBB =
P->getIncomingBlock(U);
451// Check the current block, as a fast-path, before checking whether 452// the use is anywhere in the loop. Most values are used in the same 453// block they are defined in. Also, blocks not reachable from the 454// entry are special; uses in them don't need to go through PHIs. 455if (UserBB != &BB && !L.contains(UserBB) &&
464// For each block we check that it doesn't have any uses outside of this loop. 471bool IgnoreTokens)
const{
472// For each block we check that it doesn't have any uses outside of its 473// innermost loop. This process will transitively guarantee that the current 474// loop and all of the nested loops are in LCSSA form. 481// Normal-form loops have a preheader, a single backedge, and all of their 482// exits have all their predecessors inside the loop. 486// Routines that reform the loop CFG and split edges often fail on indirectbr. 488// Return false if any loop blocks contain indirectbrs, or there are any calls 489// to noduplicate functions. 491if (isa<IndirectBrInst>(BB->getTerminator()))
495if (
auto *CB = dyn_cast<CallBase>(&
I))
496if (CB->cannotDuplicate())
505// Go through the latch blocks and check the terminator for the metadata. 528"Loop ID needs at least one operand");
530"Loop ID should refer to itself");
535 BB->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
545 Context, LoopID, {
"llvm.loop.unroll."}, {DisableUnrollMD});
568if (!DesiredLoopIdMetadata)
574 ParallelAccessGroups;
// For scalable 'contains' check. 575if (ParallelAccesses) {
577MDNode *AccGroup = cast<MDNode>(MD.get());
579"List item must be an access group");
580 ParallelAccessGroups.
insert(AccGroup);
584// The loop branch contains the parallel loop metadata. In order to ensure 585// that any parallel-loop-unaware optimization pass hasn't added loop-carried 586// dependencies (thus converted the loop back to a sequential loop), check 587// that all the memory instructions in the loop belong to an access group that 588// is parallel to this loop. 591if (!
I.mayReadOrWriteMemory())
594if (
MDNode *AccessGroup =
I.getMetadata(LLVMContext::MD_access_group)) {
595auto ContainsAccessGroup = [&ParallelAccessGroups](
MDNode *AG) ->
bool {
596if (AG->getNumOperands() == 0) {
598return ParallelAccessGroups.
count(AG);
601for (
constMDOperand &AccessListItem : AG->operands()) {
602MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
604"List item must be an access group");
605if (ParallelAccessGroups.
count(AccGroup))
611if (ContainsAccessGroup(AccessGroup))
615// The memory instruction can refer to the loop identifier metadata 616// directly or indirectly through another list metadata (in case of 617// nested parallel loops). The loop identifier metadata refers to 618// itself so we can check both cases with the same routine. 620I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
635// If we have a debug location in the loop ID, then use it. 638// We use the first DebugLoc in the header as the start location of the loop 639// and if there is a second DebugLoc in the header we use it as end location 642if (
DILocation *L = dyn_cast<DILocation>(MDO)) {
654// Try the pre-header first. 656if (
DebugLocDL = PHeadBB->getTerminator()->getDebugLoc())
659// If we have no pre-header or there are no instructions with debug 660// info in it, try the header. 662returnLocRange(HeadBB->getTerminator()->getDebugLoc());
671 LoopDbgLoc.print(
OS);
673// Just print the module name. 678#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 686//===----------------------------------------------------------------------===// 687// UnloopUpdater implementation 691/// Find the new parent loop for all blocks within the "unloop" whose last 692/// backedges has just been removed. 699// Map unloop's immediate subloops to their nearest reachable parents. Nested 700// loops within these subloops will not change parents. However, an immediate 701// subloop's new parent will be the nearest loop reachable from either its own 702// exits *or* any of its nested loop's exits. 705// Flag the presence of an irreducible backedge whose destination is a block 706// directly contained by the original unloop. 710 UnloopUpdater(
Loop *UL,
LoopInfo *LInfo) : Unloop(*UL), LI(LInfo), DFS(UL) {}
712void updateBlockParents();
714void removeBlocksFromAncestors();
716void updateSubloopParents();
721}
// end anonymous namespace 723/// Update the parent loop for all blocks that are directly contained within the 724/// original "unloop". 725void UnloopUpdater::updateBlockParents() {
726if (Unloop.getNumBlocks()) {
727// Perform a post order CFG traversal of all blocks within this loop, 728// propagating the nearest loop from successors to predecessors. 732Loop *
L = LI->getLoopFor(POI);
733Loop *NL = getNearestLoop(POI, L);
736// For reducible loops, NL is now an ancestor of Unloop. 738"uninitialized successor");
739 LI->changeLoopFor(POI, NL);
741// Or the current block is part of a subloop, in which case its parent 743assert((FoundIB || Unloop.contains(L)) &&
"uninitialized successor");
747// Each irreducible loop within the unloop induces a round of iteration using 748// the DFS result cached by Traversal. 749bool Changed = FoundIB;
750for (
unsigned NIters = 0; Changed; ++NIters) {
751assert(NIters < Unloop.getNumBlocks() &&
"runaway iterative algorithm");
754// Iterate over the postorder list of blocks, propagating the nearest loop 755// from successors to predecessors as before. 758 POE = DFS.endPostorder();
761Loop *
L = LI->getLoopFor(*POI);
762Loop *NL = getNearestLoop(*POI, L);
765"uninitialized successor");
766 LI->changeLoopFor(*POI, NL);
773/// Remove unloop's blocks from all ancestors below their new parents. 774void UnloopUpdater::removeBlocksFromAncestors() {
775// Remove all unloop's blocks (including those in nested subloops) from 776// ancestors below the new parent loop. 778Loop *OuterParent = LI->getLoopFor(BB);
779if (Unloop.contains(OuterParent)) {
782 OuterParent = SubloopParents[OuterParent];
784// Remove blocks from former Ancestors except Unloop itself which will be 788assert(OldParent &&
"new loop is not an ancestor of the original");
789 OldParent->removeBlockFromLoop(BB);
794/// Update the parent loop for all subloops directly nested within unloop. 795void UnloopUpdater::updateSubloopParents() {
796while (!Unloop.isInnermost()) {
797Loop *Subloop = *std::prev(Unloop.end());
798 Unloop.removeChildLoop(std::prev(Unloop.end()));
800assert(SubloopParents.count(Subloop) &&
"DFS failed to visit subloop");
801if (
Loop *Parent = SubloopParents[Subloop])
802 Parent->addChildLoop(Subloop);
804 LI->addTopLevelLoop(Subloop);
808/// Return the nearest parent loop among this block's successors. If a successor 809/// is a subloop header, consider its parent to be the nearest parent of the 812/// For subloop blocks, simply update SubloopParents and return NULL. 815// Initially for blocks directly contained by Unloop, NearLoop == Unloop and 816// is considered uninitialized. 817Loop *NearLoop = BBLoop;
819Loop *Subloop =
nullptr;
820if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
822// Find the subloop ancestor that is directly contained within Unloop. 825assert(Subloop &&
"subloop is not an ancestor of the original loop");
827// Get the current nearest parent of the Subloop exits, initially Unloop. 828 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
832assert(!Subloop &&
"subloop blocks must have a successor");
833 NearLoop =
nullptr;
// unloop blocks may now exit the function. 837continue;
// self loops are uninteresting 839Loop *
L = LI->getLoopFor(Succ);
841// This successor has not been processed. This path must lead to an 842// irreducible backedge. 843assert((FoundIB || !DFS.hasPostorder(Succ)) &&
"should have seen IB");
846if (L != &Unloop && Unloop.contains(L)) {
847// Successor is in a subloop. 849continue;
// Branching within subloops. Ignore it. 851// BB branches from the original into a subloop header. 852assert(
L->getParentLoop() == &Unloop &&
"cannot skip into nested loops");
854// Get the current nearest parent of the Subloop's exits. 855L = SubloopParents[
L];
856// L could be Unloop if the only exit was an irreducible backedge. 861// Handle critical edges from Unloop into a sibling loop. 862if (L && !
L->contains(&Unloop)) {
863L =
L->getParentLoop();
865// Remember the nearest parent loop among successors or subloop exits. 866if (NearLoop == &Unloop || !NearLoop || NearLoop->
contains(L))
870 SubloopParents[Subloop] = NearLoop;
880// Check whether the analysis, all analyses on functions, or the function's 881// CFG have been preserved. 892// First handle the special case of no parent loop to simplify the algorithm. 894// Since BBLoop had no parent, Unloop blocks are no longer in a loop. 896// Don't reparent blocks in subloops. 897if (getLoopFor(BB) != Unloop)
900// Blocks no longer have a parent but are still referenced by Unloop until 901// the Unloop object is deleted. 902 changeLoopFor(BB,
nullptr);
905// Remove the loop from the top-level LoopInfo object. 914// Move all of the subloops to the top-level. 921// Update the parent loop for all blocks within the loop. Blocks within 922// subloops will not change parents. 923 UnloopUpdater Updater(Unloop,
this);
924 Updater.updateBlockParents();
926// Remove blocks from former ancestor loops. 927 Updater.removeBlocksFromAncestors();
929// Add direct subloops as children in their new parent loop. 930 Updater.updateSubloopParents();
932// Remove unloop from its parent loop. 935assert(
I != ParentLoop->
end() &&
"Couldn't find loop");
945if (V->getType()->isTokenTy())
946// We can't form PHIs of token type, so the definition of LCSSA excludes 947// values of that type. 953constLoop *L = getLoopFor(
I->getParent());
956if (L->contains(ExitBB))
957// Could be an exit bb of a subloop and contained in defining loop 960// We found a (new) out-of-loop use location, for a value defined in-loop. 961// (Note that because of LCSSA, we don't have to account for values defined 962// in sibling loops. Such values will have LCSSA phis of their own in the 963// common parent loop.) 970// FIXME: Currently we create a LoopInfo from scratch for every function. 971// This may prove to be too wasteful due to deallocating and re-allocating 972// memory each time for the underlying map and vector datastructures. At some 973// point it may prove worthwhile to use a freelist and recycle LoopInfo 974// objects. I don't want to add that kind of complexity until the scope of 975// the problem is better understood. 984OS <<
"Loop info for function '" <<
F.getName() <<
"':\n";
992// handling -print-module-scope 993OS << Banner <<
" (loop: ";
994 L.getHeader()->printAsOperand(
OS,
false);
997// printing whole module 998OS << *L.getHeader()->getModule();
1003// handling -print-loop-func-scope. 1004// -print-module-scope overrides this. 1005OS << Banner <<
" (loop: ";
1006 L.getHeader()->printAsOperand(
OS,
false);
1009// printing whole function. 1010OS << *L.getHeader()->getParent();
1016auto *PreHeader = L.getLoopPreheader();
1018OS <<
"\n; Preheader:";
1019 PreHeader->print(
OS);
1023for (
auto *
Block : L.blocks())
1027OS <<
"Printing <null> block";
1030 L.getExitBlocks(ExitBlocks);
1031if (!ExitBlocks.
empty()) {
1032OS <<
"\n; Exit blocks";
1033for (
auto *
Block : ExitBlocks)
1037OS <<
"Printing <null> block";
1042// No loop metadata node, no loop properties. 1046// First operand should refer to the metadata node itself, for legacy reasons. 1050// Iterate over the metdata node operands and look for MDString metadata. 1052MDNode *MD = dyn_cast<MDNode>(MDO);
1058// Return the operand node if MDString holds expected metadata. 1063// Loop property not found. 1071/// Find string metadata for loop 1073/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an 1074/// operand or null otherwise. If the string metadata is not found return 1075/// Optional's not-a-value. 1076std::optional<const MDOperand *>
1098// When the value is absent it is interpreted as 'attribute set'. 1102 mdconst::extract_or_null<ConstantInt>(MD->
getOperand(1).
get()))
1103return IntMD->getZExtValue();
1120ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
1135if (
auto *CB = dyn_cast<CallBase>(&
II)) {
1136if (!CB->isConvergent())
1138// This is the heart if it uses a token defined outside the loop. The 1139// verifier has already checked that only the loop intrinsic can use such 1141if (
auto *Token = CB->getConvergenceControlToken()) {
1142auto *TokenDef = cast<Instruction>(Token);
1143if (!TheLoop->
contains(TokenDef->getParent()))
1153return L->getHeader()->getParent()->willReturn();
1163return L->getHeader()->getParent()->mustProgress() ||
hasMustProgress(L);
1167return Node->getNumOperands() == 0 && Node->isDistinct();
1174// First remove any existing loop metadata related to this transformation. 1177// Reserve first location for self reference to the LoopID metadata node. 1180// Remove metadata for the transformation that has been applied or that became 1184bool IsVectorMetadata =
false;
1186if (
MDNode *MD = dyn_cast<MDNode>(
Op)) {
1187constMDString *S = dyn_cast<MDString>(MD->getOperand(0));
1194if (!IsVectorMetadata)
1199// Add metadata to avoid reapplying a transformation, such as 1200// llvm.loop.unroll.disable and llvm.loop.isvectorized. 1204// Replace the temporary node with a self-reference. 1209//===----------------------------------------------------------------------===// 1210// LoopInfo implementation 1226 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
1231// LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the 1232// function each time verifyAnalysis is called is very expensive. The 1233// -verify-loop-info option can enable this. In order to perform some 1234// checking by default, LoopPass has been taught to call verifyLoop manually 1235// during loop pass sequences. 1237auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1259//===----------------------------------------------------------------------===// 1260// LoopBlocksDFS implementation 1263/// Traverse the loop blocks and store the DFS result. 1264/// Useful for clients that just want the final DFS result and don't need to 1265/// visit blocks during the initial traversal. 1269 POE = Traversal.
end();
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool runOnFunction(Function &F, bool PostInlining)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB, const DominatorTree &DT, bool IgnoreTokens)
static const char * LLVMLoopMustProgress
static Value * findFinalIVValue(const Loop &L, const PHINode &IndVar, const Instruction &StepInst)
Return the final value of the loop induction variable if found.
static cl::opt< bool, true > VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), cl::Hidden, cl::desc("Verify loop info (time consuming)"))
This file defines the interface for the loop nest analysis.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
This templated class represents "all analyses that operate over <a particular IR unit>" (e....
API to communicate dependencies between analyses during invalidation.
A container for analyses that lazily runs them and caches their results.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM Basic Block Representation.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Conditional or Unconditional Branch instruction.
bool isConditional() const
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Value * getCondition() const
Represents analyses that only rely on functions' control flow.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class is the base class for the comparison instructions.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_SGT
signed greater than
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Predicate getPredicate() const
Return the predicate for this instruction.
Predicate getFlippedStrictnessPredicate() const
For predicate of kind "is X or equal to 0" returns the predicate "is X".
This is the shared class of boolean and integer constants.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
This class represents an Operation in the Expression.
Analysis pass which computes a DominatorTree.
Core dominator tree base class.
Legacy analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
FunctionPass class - This class is used to implement most global optimizations.
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
A struct for saving information about induction variables.
BinaryOperator * getInductionBinOp() const
const SCEV * getStep() const
static bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr, SmallVectorImpl< Instruction * > *CastsToIgnore=nullptr)
Returns true if Phi is an induction in the loop L.
Instruction::BinaryOps getInductionOpcode() const
Returns binary opcode of the induction operator.
Value * getStartValue() const
ConstantInt * getConstIntStepValue() const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
This is an important class for using LLVM in a threaded context.
Analysis pass that exposes the LoopInfo for a function.
LoopInfo run(Function &F, FunctionAnalysisManager &AM)
Instances of this class are used to represent loops that are detected in the flow graph.
bool contains(const Loop *L) const
Return true if the specified loop is contained within in this loop.
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
BasicBlock * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
BasicBlock * getHeader() const
void getLoopLatches(SmallVectorImpl< BasicBlock * > &LoopLatches) const
Return all loop latch blocks 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.
std::vector< Loop * >::const_iterator iterator
iterator_range< block_iterator > blocks() const
bool isInvalid() const
Return true if this loop is no longer valid.
BasicBlock * getLoopPreheader() const
If there is a preheader for this loop, return it.
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.
BasicBlock * 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.
Store the result of a depth first search within basic blocks contained by a single loop.
std::vector< BasicBlock * >::const_iterator POIterator
Postorder list iterators.
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Traverse the blocks in a loop using a depth-first search.
POTIterator begin()
Postorder traversal over the graph.
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.
void print(raw_ostream &OS) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
std::vector< Loop * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
The legacy pass manager's analysis pass to compute loop information.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
void print(raw_ostream &O, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
bool wouldBeOutOfLoopUseRequiringLCSSA(const Value *V, const BasicBlock *ExitBB) const
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
static const BasicBlock & skipEmptyBlockUntil(const BasicBlock *From, const BasicBlock *End, bool CheckUniquePred=false)
Recursivelly traverse all empty 'single successor' basic blocks of From (if there are any).
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
A range representing the start and end location of a loop.
const DebugLoc & getStart() const
Represents a single loop in the control flow graph.
bool isCanonical(ScalarEvolution &SE) const
Return true if the loop induction variable starts at zero and increments by one each time through the...
bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens=true) const
Return true if the Loop is in LCSSA form.
std::optional< LoopBounds > getBounds(ScalarEvolution &SE) const
Return the struct LoopBounds collected if all struct members are found, else std::nullopt.
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
std::string getLocStr() const
Return a string containing the debug location of the loop (file name + line number if present,...
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
BranchInst * getLoopGuardBranch() const
Return the loop guard branch, if it exists.
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
LocRange getLocRange() const
Return the source code span of the loop.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
ICmpInst * getLatchCmpInst() const
Get the latch condition instruction.
bool getInductionDescriptor(ScalarEvolution &SE, InductionDescriptor &IndDesc) const
Get the loop induction descriptor for the loop induction variable.
bool isRotatedForm() const
Return true if the loop is in rotated form.
void setLoopMustProgress()
Add llvm.loop.mustprogress to this loop's loop id metadata.
PHINode * getInductionVariable(ScalarEvolution &SE) const
Return the loop induction variable if found, else return nullptr.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to,...
bool isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI, bool IgnoreTokens=true) const
Return true if this Loop and all inner subloops are in LCSSA form.
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr, MemorySSAUpdater *MSSAU=nullptr, ScalarEvolution *SE=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
bool getIncomingAndBackEdge(BasicBlock *&Incoming, BasicBlock *&Backedge) const
Obtain the unique incoming and back edge.
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
bool isAuxiliaryInductionVariable(PHINode &AuxIndVar, ScalarEvolution &SE) const
Return true if the given PHINode AuxIndVar is.
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
Tracking metadata reference owned by Metadata.
StringRef getString() const
static MDString * get(LLVMContext &Context, StringRef Str)
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Root of the metadata hierarchy.
A Module instance is used to store all the information related to an LLVM module.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
This node represents a polynomial recurrence on the trip count of the specified loop.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
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.
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.
StringRef - Represent a constant reference to a string, i.e.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
LLVM Value Representation.
iterator_range< user_iterator > users()
const ParentTy * getParent() const
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LocationClass< Ty > location(Ty &L)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
bool succ_empty(const Instruction *I)
bool forcePrintModuleIR()
void initializeLoopInfoWrapperPassPass(PassRegistry &)
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
std::optional< bool > getOptionalBoolLoopAttribute(const Loop *TheLoop, StringRef Name)
int getIntLoopAttribute(const Loop *TheLoop, StringRef Name, int Default=0)
Find named metadata for a loop with an integer value.
auto pred_end(const MachineBasicBlock *BB)
std::optional< const MDOperand * > findStringMetadataForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for loop.
auto successors(const MachineBasicBlock *BB)
MDNode * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a loop.
bool hasMustProgress(const Loop *L)
Look for the loop attribute that requires progress within the loop.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool VerifyLoopInfo
Enable verification of loop info.
std::optional< int > getOptionalIntLoopAttribute(const Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
auto pred_begin(const MachineBasicBlock *BB)
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.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
@ Default
The result values are uniform if and only if all operands are uniform.
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Below are some utilities to get the loop guard, loop bounds and induction variable,...
static std::optional< Loop::LoopBounds > getBounds(const Loop &L, PHINode &IndVar, ScalarEvolution &SE)
Return the LoopBounds object if.
Direction
An enum for the direction of the loop.
ICmpInst::Predicate getCanonicalPredicate() const
Return the canonical predicate for the latch compare instruction, if able to be calcuated.
Direction getDirection() const
Get the direction of the loop.