15#define DEBUG_TYPE "loop-constrainer" 17/// Given a loop with an deccreasing induction variable, is it possible to 18/// safely calculate the bounds of a new loop using the given Predicate. 21unsigned LatchBrExitIdx,
Loop *L,
23if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
24 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
39bool IsSigned = ICmpInst::isSigned(Pred);
40// The predicate that we need to check that the induction variable lies 48if (LatchBrExitIdx == 1)
51assert(LatchBrExitIdx == 0 &&
"LatchBrExitIdx should be either 0 or 1");
54unsignedBitWidth = cast<IntegerType>(BoundSCEV->
getType())->getBitWidth();
66/// Given a loop with an increasing induction variable, is it possible to 67/// safely calculate the bounds of a new loop using the given Predicate. 70unsigned LatchBrExitIdx,
Loop *L,
72if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
73 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
86bool IsSigned = ICmpInst::isSigned(Pred);
87// The predicate that we need to check that the induction variable lies 95if (LatchBrExitIdx == 1)
98assert(LatchBrExitIdx == 0 &&
"LatchBrExitIdx should be 0 or 1");
101unsignedBitWidth = cast<IntegerType>(BoundSCEV->
getType())->getBitWidth();
111/// Returns estimate for max latch taken count of the loop of the narrowest 112/// available type. If the latch block has such estimate, it is returned. 113/// Otherwise, we use max exit count of whole loop (that is potentially of wider 114/// type than latch check itself), which is still better than no estimate. 117constSCEV *FromBlock =
119if (isa<SCEVCouldNotCompute>(FromBlock))
124std::optional<LoopStructure>
126bool AllowUnsignedLatchCond,
127constchar *&FailureReason) {
128if (!L.isLoopSimplifyForm()) {
129 FailureReason =
"loop not in LoopSimplify form";
134assert(
Latch &&
"Simplified loops only have one latch!");
137 FailureReason =
"loop has already been cloned";
141if (!L.isLoopExiting(
Latch)) {
142 FailureReason =
"no loop latch";
149 FailureReason =
"no preheader";
155 FailureReason =
"latch terminator not conditional branch";
163 FailureReason =
"latch terminator branch not conditional on integral icmp";
168if (isa<SCEVCouldNotCompute>(MaxBETakenCount)) {
169 FailureReason =
"could not compute latch count";
174"loop variant exit count doesn't make sense!");
184// We canonicalize `ICI` such that `LeftSCEV` is an add recurrence. 185if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
186if (isa<SCEVAddRecExpr>(RightSCEV)) {
191 FailureReason =
"no add recurrences in the icmp";
208constSCEV *ExtendedStep =
211bool NoSignedWrap = ExtendAfterOp->
getStart() == ExtendedStart &&
218// We may have proved this when computing the sign extension above. 222// `ICI` is interpreted as taking the backedge if the *next* value of the 223// induction variable satisfies some constraint. 227 FailureReason =
"LHS in cmp is not an AddRec for this loop";
231 FailureReason =
"LHS in icmp not induction variable";
235if (!isa<SCEVConstant>(StepRec)) {
236 FailureReason =
"LHS in icmp not induction variable";
242 FailureReason =
"LHS in icmp needs nsw for equality predicates";
254constSCEV *FixedRightSCEV =
nullptr;
256// If RightValue resides within loop (but still being loop invariant), 257// regenerate it as preheader. 258if (
auto *
I = dyn_cast<Instruction>(RightValue))
259if (L.contains(
I->getParent()))
260 FixedRightSCEV = RightSCEV;
263bool DecreasedRightValueByOne =
false;
264if (StepCI->
isOne()) {
265// Try to turn eq/ne predicates to those we can work with. 267// while (++i != len) { while (++i < len) { 270// If both parts are known non-negative, it is profitable to use 271// unsigned comparison in increasing loop. This allows us to make the 272// comparison check against "RightSCEV + 1" more optimistic. 279// while (true) { while (true) { 280// if (++i == len) ---> if (++i > len - 1) 289 DecreasedRightValueByOne =
true;
294 DecreasedRightValueByOne =
true;
301bool FoundExpectedPred =
304if (!FoundExpectedPred) {
305 FailureReason =
"expected icmp slt semantically, found something else";
311 FailureReason =
"unsigned latch conditions are explicitly prohibited";
317 FailureReason =
"Unsafe loop bounds";
321// We need to increase the right value unless we have already decreased 322// it virtually when we replaced EQ with SGT. 323if (!DecreasedRightValueByOne)
327assert(!DecreasedRightValueByOne &&
328"Right value can be decreased only for LatchBrExitIdx == 0!");
331bool IncreasedRightValueByOne =
false;
333// Try to turn eq/ne predicates to those we can work with. 335// while (--i != len) { while (--i > len) { 338// We intentionally don't turn the predicate into UGT even if we know 339// that both operands are non-negative, because it will only pessimize 340// our check against "RightSCEV - 1". 343// while (true) { while (true) { 344// if (--i == len) ---> if (--i < len + 1) 352 IncreasedRightValueByOne =
true;
356 IncreasedRightValueByOne =
true;
364bool FoundExpectedPred =
367if (!FoundExpectedPred) {
368 FailureReason =
"expected icmp sgt semantically, found something else";
376 FailureReason =
"unsigned latch conditions are explicitly prohibited";
382 FailureReason =
"Unsafe bounds";
387// We need to decrease the right value unless we have already increased 388// it virtually when we replaced EQ with SLT. 389if (!IncreasedRightValueByOne)
393assert(!IncreasedRightValueByOne &&
394"Right value can be increased only for LatchBrExitIdx == 0!");
409 IndVarStartV->
setName(
"indvar.start");
419 Result.IndVarStart = IndVarStartV;
420 Result.IndVarStep = StepCI;
421 Result.IndVarBase = LeftValue;
422 Result.IndVarIncreasing = IsIncreasing;
423 Result.LoopExitAt = RightValue;
425 Result.ExitCountTy = cast<IntegerType>(MaxBETakenCount->
getType());
427 FailureReason =
nullptr;
432// Add metadata to the loop L to disable loop optimizations. Callers need to 433// confirm that optimizing loop L is not beneficial. 435// We do not care about any existing loopID related metadata for L, since we 436// are setting all loop metadata to false. 438// Reserve first location for self reference to the LoopID metadata node. 441 Context, {
MDString::get(Context,
"llvm.loop.unroll.disable")});
446 {
MDString::get(Context,
"llvm.loop.vectorize.enable"), FalseVal});
448 Context, {
MDString::get(Context,
"llvm.loop.licm_versioning.disable")});
451 {
MDString::get(Context,
"llvm.loop.distribute.enable"), FalseVal});
453MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
454 DisableLICMVersioning, DisableDistribution});
455// Set operand 0 to refer to the loop id itself. 457 L.setLoopID(NewLoopID);
464 :
F(*L.getHeader()->
getParent()), Ctx(L.getHeader()->getContext()), SE(SE),
465 DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L), RangeTy(
T),
466 MainLoopStructure(LS), SR(SR) {}
468void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
469constchar *
Tag)
const{
472 Result.Blocks.push_back(Clone);
473 Result.Map[BB] = Clone;
476auto GetClonedValue = [&Result](
Value *V) {
477assert(V &&
"null values not in domain!");
478auto It = Result.Map.find(V);
479if (It == Result.Map.end())
481returnstatic_cast<Value *
>(It->second);
485 cast<BasicBlock>(GetClonedValue(OriginalLoop.
getLoopLatch()));
489Result.Structure = MainLoopStructure.
map(GetClonedValue);
492for (
unsigned i = 0, e =
Result.Blocks.size(); i != e; ++i) {
496assert(
Result.Map[OriginalBB] == ClonedBB &&
"invariant!");
502// Exit blocks will now have one more predecessor and their PHI nodes need 503// to be edited to reflect that. No phi nodes need to be introduced because 504// the loop is in LCSSA. 508continue;
// not an exit block 511Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
512 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
519LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
522// We start with a loop with a single latch: 524// +--------------------+ 528// +--------+-----------+ 529// | ----------------\ 531// +--------v----v------+ | 535// +--------------------+ | 539// +--------------------+ | 541// | latch >----------/ 543// +-------v------------+ 546// | +--------------------+ 548// +---> original exit | 550// +--------------------+ 552// We change the control flow to look like 555// +--------------------+ 557// | preheader >-------------------------+ 559// +--------v-----------+ | 560// | /-------------+ | 562// +--------v--v--------+ | | 564// | header | | +--------+ | 566// +--------------------+ | | +-----v-----v-----------+ 568// | | | .pseudo.exit | 570// | | +-----------v-----------+ 573// | | +--------v-------------+ 574// +--------------------+ | | | | 575// | | | | | ContinuationBlock | 576// | latch >------+ | | | 577// | | | +----------------------+ 578// +---------v----------+ | 581// | +---------------^-----+ 583// +-----> .exit.selector | 585// +----------v----------+ 587// +--------------------+ | 589// | original exit <----+ 591// +--------------------+ 593 RewrittenRangeInfo RRI;
597 &F, BBInsertLocation);
602bool Increasing =
LS.IndVarIncreasing;
603bool IsSignedPredicate =
LS.IsSignedPredicate;
606auto NoopOrExt = [&](
Value *
V) {
607if (
V->getType() == RangeTy)
609return IsSignedPredicate ?
B.CreateSExt(V, RangeTy,
"wide." +
V->getName())
610 :
B.CreateZExt(V, RangeTy,
"wide." +
V->getName());
613// EnterLoopCond - is it okay to start executing this `LS'? 614Value *EnterLoopCond =
nullptr;
619Value *IndVarStart = NoopOrExt(
LS.IndVarStart);
620 EnterLoopCond =
B.CreateICmp(Pred, IndVarStart, ExitSubloopAt);
622B.CreateCondBr(EnterLoopCond,
LS.Header, RRI.PseudoExit);
625LS.LatchBr->setSuccessor(
LS.LatchBrExitIdx, RRI.ExitSelector);
626B.SetInsertPoint(
LS.LatchBr);
627Value *IndVarBase = NoopOrExt(
LS.IndVarBase);
628Value *TakeBackedgeLoopCond =
B.CreateICmp(Pred, IndVarBase, ExitSubloopAt);
630Value *CondForBranch =
LS.LatchBrExitIdx == 1
631 ? TakeBackedgeLoopCond
632 :
B.CreateNot(TakeBackedgeLoopCond);
634LS.LatchBr->setCondition(CondForBranch);
636B.SetInsertPoint(RRI.ExitSelector);
638// IterationsLeft - are there any more iterations left, given the original 639// upper bound on the induction variable? If not, we branch to the "real" 641Value *LoopExitAt = NoopOrExt(
LS.LoopExitAt);
642Value *IterationsLeft =
B.CreateICmp(Pred, IndVarBase, LoopExitAt);
643B.CreateCondBr(IterationsLeft, RRI.PseudoExit,
LS.LatchExit);
648// We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of 649// each of the PHI nodes in the loop header. This feeds into the initial 650// value of the same PHI nodes if/when we continue execution. 655 NewPHI->
addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
658 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
663 RRI.IndVarEnd->addIncoming(IndVarStart, Preheader);
664 RRI.IndVarEnd->addIncoming(IndVarBase, RRI.ExitSelector);
666// The latch exit now has a branch from `RRI.ExitSelector' instead of 667// `LS.Latch'. The PHI nodes need to be updated to reflect that. 668LS.LatchExit->replacePhiUsesWith(
LS.Latch, RRI.ExitSelector);
673void LoopConstrainer::rewriteIncomingValuesForPHIs(
675const LoopConstrainer::RewrittenRangeInfo &RRI)
const{
676unsigned PHIIndex = 0;
678 PN.setIncomingValueForBlock(ContinuationBlock,
679 RRI.PHIValuesAtPseudoExit[PHIIndex++]);
681LS.IndVarStart = RRI.IndVarEnd;
686constchar *
Tag)
const{
690LS.Header->replacePhiUsesWith(OldPreheader, Preheader);
704Loop *LoopConstrainer::createClonedLoopStructure(
Loop *Original,
Loop *Parent,
712 LPMAddNewLoop(&New, IsSubloop);
714// Add all of the blocks in Original to the new loop. 715for (
auto *BB : Original->
blocks())
717New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
719// Add all of the subloops to the new loop. 720for (
Loop *SubLoop : *Original)
721 createClonedLoopStructure(SubLoop, &New, VM,
/* IsSubloop */true);
728assert(Preheader !=
nullptr &&
"precondition!");
730 OriginalPreheader = Preheader;
731 MainLoopPreheader = Preheader;
739// It would have been better to make `PreLoop' and `PostLoop' 740// `std::optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy 742 ClonedLoop PreLoop, PostLoop;
748Value *ExitPreLoopAt =
nullptr;
749Value *ExitMainLoopAt =
nullptr;
751 cast<SCEVConstant>(SE.
getConstant(IVTy, -1,
true/* isSigned */));
754constSCEV *ExitPreLoopAtSCEV =
nullptr;
763 <<
"preloop exit limit. HighLimit = " 769LLVM_DEBUG(
dbgs() <<
"could not prove that it is safe to expand the" 770 <<
" preloop exit limit " << *ExitPreLoopAtSCEV
771 <<
" at block " << InsertPt->
getParent()->getName()
776 ExitPreLoopAt = Expander.
expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
777 ExitPreLoopAt->
setName(
"exit.preloop.at");
781constSCEV *ExitMainLoopAtSCEV =
nullptr;
790 <<
"mainloop exit limit. LowLimit = " 796LLVM_DEBUG(
dbgs() <<
"could not prove that it is safe to expand the" 797 <<
" main loop exit limit " << *ExitMainLoopAtSCEV
798 <<
" at block " << InsertPt->
getParent()->getName()
803 ExitMainLoopAt = Expander.
expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
804 ExitMainLoopAt->
setName(
"exit.mainloop.at");
807// We clone these ahead of time so that we don't have to deal with changing 808// and temporarily invalid IR as we transform the loops. 810 cloneLoop(PreLoop,
"preloop");
812 cloneLoop(PostLoop,
"postloop");
814 RewrittenRangeInfo PreLoopRRI;
818 PreLoop.Structure.Header);
821 createPreheader(MainLoopStructure, Preheader,
"mainloop");
822 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
823 ExitPreLoopAt, MainLoopPreheader);
824 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
829 RewrittenRangeInfo PostLoopRRI;
833 createPreheader(PostLoop.Structure, Preheader,
"postloop");
834 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
835 ExitMainLoopAt, PostLoopPreheader);
836 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
841 MainLoopPreheader != Preheader ? MainLoopPreheader :
nullptr;
842BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
843 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
844 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
846// Some of the above may be nullptr, filter them out before passing to 847// addToParentLoopIfNeeded. 849 std::remove(std::begin(NewBlocks), std::end(NewBlocks),
nullptr);
851 addToParentLoopIfNeeded(
ArrayRef(std::begin(NewBlocks), NewBlocksEnd));
855// We need to first add all the pre and post loop blocks into the loop 856// structures (as part of createClonedLoopStructure), and then update the 857// LCSSA form and LoopSimplifyForm. This is necessary for correctly updating 858// LI when LoopSimplifyForm is generated. 859Loop *PreL =
nullptr, *PostL =
nullptr;
860if (!PreLoop.Blocks.empty()) {
861 PreL = createClonedLoopStructure(&OriginalLoop,
863/* IsSubLoop */false);
866if (!PostLoop.Blocks.empty()) {
868 createClonedLoopStructure(&OriginalLoop, OriginalLoop.
getParentLoop(),
869 PostLoop.Map,
/* IsSubLoop */false);
872// This function canonicalizes the loop into Loop-Simplify and LCSSA forms. 873auto CanonicalizeLoop = [&](
Loop *L,
bool IsOriginalLoop) {
876// Pre/post loops are slow paths, we do not need to perform any loop 877// optimizations on them. 882 CanonicalizeLoop(PreL,
false);
884 CanonicalizeLoop(PostL,
false);
885 CanonicalizeLoop(&OriginalLoop,
true);
888 /// - We've broken a "main loop" out of the loop in a way that the "main loop" 889 /// runs with the induction variable in a subset of [Begin, End). 890 /// - There is no overflow when computing "main loop" exit limit. 891 /// - Max latch taken count of the loop is limited. 892 /// It guarantees that induction variable will not overflow iterating in the 894if (isa<OverflowingBinaryOperator>(MainLoopStructure.
IndVarBase))
895if (IsSignedPredicate)
896 cast<BinaryOperator>(MainLoopStructure.
IndVarBase)
897 ->setHasNoSignedWrap(
true);
898 /// TODO: support unsigned predicate. 899 /// To add NUW flag we need to prove that both operands of BO are 900 /// non-negative. E.g: 902 /// %iv.next = add nsw i32 %iv, -1 903 /// %cmp = icmp ult i32 %iv.next, %n 904 /// br i1 %cmp, label %loopexit, label %loop 906 /// -1 is MAX_UINT in terms of unsigned int. Adding anything but zero will 907 /// overflow, therefore NUW flag is not legal here. MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static const char * ClonedLoopTag
static const SCEV * getNarrowestLatchMaxTakenCountEstimate(ScalarEvolution &SE, const Loop &L)
Returns estimate for max latch taken count of the loop of the narrowest available type.
static bool isSafeDecreasingBound(const SCEV *Start, const SCEV *BoundSCEV, const SCEV *Step, ICmpInst::Predicate Pred, unsigned LatchBrExitIdx, Loop *L, ScalarEvolution &SE)
Given a loop with an deccreasing induction variable, is it possible to safely calculate the bounds of...
static void DisableAllLoopOptsOnLoop(Loop &L)
static bool isSafeIncreasingBound(const SCEV *Start, const SCEV *BoundSCEV, const SCEV *Step, ICmpInst::Predicate Pred, unsigned LatchBrExitIdx, Loop *L, ScalarEvolution &SE)
Given a loop with an increasing induction variable, is it possible to safely calculate the bounds of ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Class for arbitrary precision integers.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM Basic Block Representation.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
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.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Value * getCondition() const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Predicate getPredicate() const
Return the predicate for this instruction.
static ConstantAsMetadata * get(Constant *C)
This is the shared class of boolean and integer constants.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
const APInt & getValue() const
Return the constant as an APInt value reference.
A parsed version of the target data layout string in and methods for querying it.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Class to represent integer types.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
This is an important class for using LLVM in a threaded context.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopConstrainer(Loop &L, LoopInfo &LI, function_ref< void(Loop *, bool)> LPMAddNewLoop, const LoopStructure &LS, ScalarEvolution &SE, DominatorTree &DT, Type *T, SubRanges SR)
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LoopT * AllocateLoop(ArgsTy &&...Args)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDString * get(LLVMContext &Context, StringRef Str)
Root of the metadata hierarchy.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
This node represents a polynomial recurrence on the trip count of the specified loop.
const SCEV * getStart() const
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
This class uses information about analyze scalars to rewrite expressions in canonical form.
bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint) const
Return true if the given expression is safe to expand in the sense that all materialized values are d...
Value * expandCodeFor(const SCEV *SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
const SCEV * getConstant(ConstantInt *V)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
@ LoopInvariant
The SCEV is loop-invariant.
void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static IntegerType * getInt1Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void setName(const Twine &Name)
Change the name of the value.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
This is an optimization pass for GlobalISel generic memory operations.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
auto successors(const MachineBasicBlock *BB)
bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
bool cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned max.
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataSetTy *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
constexpr unsigned BitWidth
bool cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned min.
bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always non-negative in loop L.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
std::optional< const SCEV * > LowLimit
std::optional< const SCEV * > HighLimit
LoopStructure map(M Map) const
static std::optional< LoopStructure > parseLoopStructure(ScalarEvolution &, Loop &, bool, const char *&)