54#define DEBUG_TYPE "loop-peel"
57STATISTIC(NumPeeledEnd,
"Number of loops peeled from end");
62 cl::desc(
"Set the unroll peeling count, for testing purposes"));
66 cl::desc(
"Allows loops to be peeled when the dynamic "
67 "trip count is known to be low."));
72 cl::desc(
"Allows loop nests to be peeled."));
76 cl::desc(
"Max average trip count which will cause loop peeling."));
80 cl::desc(
"Force a peel count regardless of profiling information."));
85 "Disable advance peeling. Issues for convergent targets (D134803)."));
89 cl::desc(
"Enable peeling to convert Phi nodes into IVs"));
99 if (!L->isLoopSimplifyForm())
105 L->getUniqueNonLatchExitBlocks(Exits);
199 PhiAnalyzer(
const Loop &L,
unsigned MaxIterations,
bool PeelForIV);
203 std::optional<unsigned> calculateIterationsToPeel();
206 enum class PeelCounterType {
211 using PeelCounterValue = std::pair<unsigned, PeelCounterType>;
212 using PeelCounter = std::optional<PeelCounterValue>;
213 const PeelCounter Unknown = std::nullopt;
216 PeelCounter addOne(PeelCounter PC)
const {
219 auto [Val, Ty] = *PC;
220 return (Val + 1 <= MaxIterations) ? PeelCounter({Val + 1, Ty}) : Unknown;
224 PeelCounter makeZero(PeelCounterType Ty)
const {
225 return PeelCounter({0, Ty});
230 PeelCounter calculate(
const Value &);
234 PeelCounter mergeTwoCounters(
const Instruction &CmpOrBinaryOp,
235 const PeelCounterValue &
LHS,
236 const PeelCounterValue &
RHS)
const;
240 bool isInductionPHI(
const PHINode *Phi)
const;
243 const unsigned MaxIterations;
244 const bool PeelForIV;
247 SmallDenseMap<const Value *, PeelCounter> IterationsToInvarianceOrInduction;
250PhiAnalyzer::PhiAnalyzer(
const Loop &L,
unsigned MaxIterations,
bool PeelForIV)
251 :
L(
L), MaxIterations(MaxIterations), PeelForIV(PeelForIV) {
253 assert(MaxIterations > 0 &&
"no peeling is allowed?");
260bool PhiAnalyzer::isInductionPHI(
const PHINode *Phi)
const {
263 if (Latch ==
nullptr)
266 Value *Cur =
Phi->getIncomingValueForBlock(Latch);
267 SmallPtrSet<Value *, 4> Visited;
268 bool VisitBinOp =
false;
278 if (!Visited.
insert(Cur).second)
282 if (!
I || !
L.contains(
I))
286 Cur = Cast->getOperand(0);
288 if (BinOp->getOpcode() != Instruction::Add &&
289 BinOp->getOpcode() != Instruction::Sub)
295 Cur = BinOp->getOperand(0);
311PhiAnalyzer::PeelCounter
312PhiAnalyzer::mergeTwoCounters(
const Instruction &CmpOrBinaryOp,
313 const PeelCounterValue &
LHS,
314 const PeelCounterValue &
RHS)
const {
315 auto &[LVal, LTy] =
LHS;
316 auto &[RVal, RTy] =
RHS;
317 unsigned NewVal = std::max(LVal, RVal);
319 if (LTy == PeelCounterType::Induction || RTy == PeelCounterType::Induction) {
321 if (BinOp->getOpcode() == Instruction::Add ||
322 BinOp->getOpcode() == Instruction::Sub)
323 return PeelCounter({NewVal, PeelCounterType::Induction});
327 return PeelCounter({NewVal, PeelCounterType::Invariant});
344PhiAnalyzer::PeelCounter PhiAnalyzer::calculate(
const Value &V) {
349 IterationsToInvarianceOrInduction.try_emplace(&V,
Unknown);
353 if (
L.isLoopInvariant(&V))
355 return (IterationsToInvarianceOrInduction[&V] =
356 makeZero(PeelCounterType::Invariant));
358 if (
Phi->getParent() !=
L.getHeader()) {
361 "unexpected value saved");
366 if (PeelForIV && isInductionPHI(Phi))
367 return (IterationsToInvarianceOrInduction[&V] =
368 makeZero(PeelCounterType::Induction));
371 Value *Input =
Phi->getIncomingValueForBlock(
L.getLoopLatch());
372 PeelCounter Iterations = calculate(*Input);
373 assert(IterationsToInvarianceOrInduction[Input] == Iterations &&
374 "unexpected value saved");
375 return (IterationsToInvarianceOrInduction[Phi] = addOne(Iterations));
380 PeelCounter
LHS = calculate(*
I->getOperand(0));
383 PeelCounter
RHS = calculate(*
I->getOperand(1));
386 return (IterationsToInvarianceOrInduction[
I] =
387 mergeTwoCounters(*
I, *
LHS, *
RHS));
391 return (IterationsToInvarianceOrInduction[
I] =
392 calculate(*
I->getOperand(0)));
398 "unexpected value saved");
402std::optional<unsigned> PhiAnalyzer::calculateIterationsToPeel() {
403 unsigned Iterations = 0;
404 for (
auto &
PHI :
L.getHeader()->phis()) {
405 PeelCounter ToInvarianceOrInduction = calculate(
PHI);
406 if (ToInvarianceOrInduction !=
Unknown) {
407 unsigned Val = ToInvarianceOrInduction->first;
408 assert(Val <= MaxIterations &&
"bad result in phi analysis");
409 Iterations = std::max(Iterations, Val);
410 if (Iterations == MaxIterations)
414 assert((Iterations <= MaxIterations) &&
"bad result in phi analysis");
415 return Iterations ? std::optional<unsigned>(Iterations) : std::nullopt;
429 if (L.getExitingBlock())
435 L.getUniqueNonLatchExitBlocks(Exits);
453 if (
I.mayWriteToMemory() &&
465 Value *Ptr = LI->getPointerOperand();
466 if (DT.
dominates(BB, Latch) && L.isLoopInvariant(Ptr) &&
473 L.getExitingBlocks(ExitingBlocks);
497 return Latch && Latch == L.getExitingBlock() &&
523 L.getLoopPredecessor()->getTerminator()))
549static std::pair<unsigned, unsigned>
552 assert(L.isLoopSimplifyForm() &&
"Loop needs to be in loop simplify form");
553 unsigned DesiredPeelCount = 0;
554 unsigned DesiredPeelCountLast = 0;
560 std::min((
unsigned)SC->getAPInt().getLimitedValue() - 1, MaxPeelCount);
565 auto PeelWhilePredicateIsKnown =
566 [&](
unsigned &PeelCount,
const SCEV *&IterVal,
const SCEV *BoundSCEV,
568 while (PeelCount < MaxPeelCount &&
577 const unsigned MaxDepth = 4;
578 std::function<void(
Value *,
unsigned)> ComputePeelCount =
579 [&](
Value *Condition,
unsigned Depth) ->
void {
583 Value *LeftVal, *RightVal;
586 ComputePeelCount(LeftVal,
Depth + 1);
587 ComputePeelCount(RightVal,
Depth + 1);
625 unsigned NewPeelCount = DesiredPeelCount;
637 if (!PeelWhilePredicateIsKnown(NewPeelCount, IterVal, RightSCEV, Step,
640 DesiredPeelCountLast = 1;
653 if (NewPeelCount >= MaxPeelCount)
658 DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount);
659 DesiredPeelCountLast = std::max(DesiredPeelCountLast, NewPeelCount);
663 if (!
MinMax->getType()->isIntegerTy())
666 const SCEV *BoundSCEV, *IterSCEV;
667 if (L.isLoopInvariant(
LHS)) {
670 }
else if (L.isLoopInvariant(
RHS)) {
677 if (!AddRec || !AddRec->isAffine() || AddRec->getLoop() != &L)
679 const SCEV *Step = AddRec->getStepRecurrence(SE);
680 bool IsSigned =
MinMax->isSigned();
691 if (!(IsSigned ? AddRec->hasNoSignedWrap() : AddRec->hasNoUnsignedWrap()))
693 unsigned NewPeelCount = DesiredPeelCount;
694 const SCEV *IterVal = AddRec->evaluateAtIteration(
695 SE.
getConstant(AddRec->getType(), NewPeelCount), SE);
696 if (!PeelWhilePredicateIsKnown(NewPeelCount, IterVal, BoundSCEV, Step,
699 DesiredPeelCountLast = 1;
702 DesiredPeelCount = NewPeelCount;
708 ComputePeelCount(
SI->getCondition(), 0);
710 ComputePeelCountMinMax(
MinMax);
718 if (L.getLoopLatch() == BB)
721 ComputePeelCount(BI->getCondition(), 0);
724 return {DesiredPeelCount, DesiredPeelCountLast};
737 if (!LatchBR || !L->isLoopExiting(Latch))
742 "At least one edge out of the latch must go to the header");
745 L->getUniqueNonLatchExitBlocks(ExitBlocks);
758 assert(LoopSize > 0 &&
"Zero loop size is not allowed!");
777 <<
" iterations.\n");
788 if (2 * LoopSize > Threshold)
791 unsigned AlreadyPeeled = 0;
793 AlreadyPeeled = *Peeled;
800 MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1);
804 unsigned DesiredPeelCount = TargetPeelCount;
811 if (MaxPeelCount > DesiredPeelCount) {
814 .calculateIterationsToPeel();
816 DesiredPeelCount = std::max(DesiredPeelCount, *NumPeels);
819 const auto &[CountToEliminateCmps, CountToEliminateCmpsLast] =
821 DesiredPeelCount = std::max(DesiredPeelCount, CountToEliminateCmps);
823 if (DesiredPeelCount == 0)
826 if (DesiredPeelCount > 0) {
827 DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount);
829 assert(DesiredPeelCount > 0 &&
"Wrong loop size estimation?");
832 <<
" iteration(s) to turn"
833 <<
" some Phis into invariants or inductions.\n");
841 if (CountToEliminateCmpsLast > 0) {
842 unsigned DesiredPeelCountLast =
843 std::min(CountToEliminateCmpsLast, MaxPeelCount);
845 assert(DesiredPeelCountLast > 0 &&
"Wrong loop size estimation?");
848 <<
" iteration(s) to turn"
849 <<
" some Phis into invariants.\n");
870 if (L->getHeader()->getParent()->hasProfileData()) {
874 if (!EstimatedTripCount)
878 << *EstimatedTripCount <<
"\n");
880 std::optional<unsigned> TotalPeeled =
882 if (TotalPeeled && *TotalPeeled <= MaxPeelCount) {
883 unsigned PeelCount = *EstimatedTripCount;
884 LLVM_DEBUG(
dbgs() <<
"Peeling first " << PeelCount <<
" iterations.\n");
888 LLVM_DEBUG(
dbgs() <<
"Already peel count: " << AlreadyPeeled <<
"\n");
893 << (Threshold / LoopSize - 1) <<
"\n");
909 Loop *L,
unsigned IterNumber,
bool PeelLast,
BasicBlock *InsertTop,
918 BasicBlock *PreHeader = L->getLoopPreheader();
923 Loop *ParentLoop = L->getParentLoop();
955 std::string Ext = (
Twine(
"Peel") +
Twine(IterNumber)).str();
957 Header->getContext(), Ext);
962 for (
Loop *ChildLoop : *L) {
963 cloneLoop(ChildLoop, ParentLoop, VMap, LI,
nullptr);
978 assert(IterNumber == 0 &&
"Only peeling a single iteration implemented.");
980 LatchTerm->setSuccessor(0, InsertBot);
981 LatchTerm->setSuccessor(1, InsertBot);
987 for (
unsigned idx = 0, e = LatchTerm->getNumSuccessors(); idx < e; ++idx) {
988 if (LatchTerm->getSuccessor(idx) == Header) {
989 LatchTerm->setSuccessor(idx, InsertBot);
1026 if (IterNumber == 0) {
1031 if (LatchInst && L->contains(LatchInst))
1032 VMap[&*
I] = LVMap[LatchInst];
1034 VMap[&*
I] = LatchVal;
1044 for (
auto Edge : ExitEdges)
1046 Value *LatchVal =
PHI.getIncomingValueForBlock(Edge.first);
1048 if (LatchInst && L->contains(LatchInst))
1049 LatchVal = VMap[LatchVal];
1056 for (
auto KV : VMap)
1057 LVMap[KV.first] = KV.second;
1060TargetTransformInfo::PeelingPreferences
1063 std::optional<bool> UserAllowPeeling,
1064 std::optional<bool> UserAllowProfileBasedPeeling,
1065 bool UnrollingSpecficValues) {
1076 TTI.getPeelingPreferences(L, SE, PP);
1079 if (UnrollingSpecficValues) {
1089 if (UserAllowPeeling)
1091 if (UserAllowProfileBasedPeeling)
1109 assert(PeelCount > 0 &&
"Attempt to peel out zero iterations?");
1110 assert(
canPeel(L) &&
"Attempt to peel a loop which is not peelable?");
1112 "when peeling the last iteration, the loop must be supported and can "
1113 "only peel a single iteration");
1119 BasicBlock *PreHeader = L->getLoopPreheader();
1122 L->getExitEdges(ExitEdges);
1129 for (
auto *BB : L->blocks()) {
1130 auto *BBDomNode = DT.
getNode(BB);
1132 for (
auto *ChildDomNode : BBDomNode->children()) {
1133 auto *ChildBB = ChildDomNode->getBlock();
1134 if (!L->contains(ChildBB))
1142 for (
auto *ChildBB : ChildrenToUpdate)
1143 NonLoopBlocksIDom[ChildBB] = NewIDom;
1180 ExitValues[&
P] =
P.getIncomingValueForBlock(Latch);
1184 InsertTop =
SplitEdge(Latch, Exit, &DT, LI);
1187 InsertTop->
setName(Exit->getName() +
".peel.begin");
1188 InsertBot->
setName(Exit->getName() +
".peel.next");
1189 NewPreHeader =
nullptr;
1210 double Freq = 1 / ExitP.toDouble();
1214 assert(Freq >= 1.0 &&
"expected freq >= 1 due to initial iteration");
1215 double NewFreq = std::max(Freq - 1, 1.0);
1221 NewPreHeader =
SplitEdge(PreHeader, Header, &DT, LI);
1229 B.CreateICmpNE(BTCValue, ConstantInt::get(BTCValue->
getType(), 0));
1230 auto *BI =
B.CreateCondBr(
Cond, NewPreHeader, InsertTop);
1235 if (HasBranchWeights) {
1244 if (L->getExitBlock() == OrigLatchBr->getSuccessor(0))
1299 InsertTop =
SplitEdge(PreHeader, Header, &DT, LI);
1303 InsertTop->
setName(Header->getName() +
".peel.begin");
1304 InsertBot->
setName(Header->getName() +
".peel.next");
1318 for (
unsigned Iter = 0; Iter < PeelCount; ++Iter) {
1322 NewPreHeader ? PreHeader :
nullptr, ExitEdges, NewBlocks,
1323 LoopBlocks, VMap, LVMap, &DT, LI,
1324 LoopLocalNoAliasDeclScopes, *SE);
1339 cast<ICmpInst>(L->getLoopLatch()->getTerminator()->getOperand(0));
1342 1,
B.CreateSub(Cmp->getOperand(1),
1343 ConstantInt::get(Cmp->getOperand(1)->getType(), 1)));
1346 for (
auto BBIDom : NonLoopBlocksIDom)
1352#ifdef EXPENSIVE_CHECKS
1353 assert(DT.
verify(DominatorTree::VerificationLevel::Fast));
1359 LatchTermCopy->setMetadata(LLVMContext::MD_loop,
nullptr);
1361 InsertTop = InsertBot;
1363 InsertBot->
setName(Header->getName() +
".peel.next");
1365 F->splice(InsertTop->
getIterator(),
F, NewBlocks[0]->getIterator(),
1372 for (
const auto &[
P, E] : ExitValues) {
1374 if (ExitInst && L->contains(ExitInst))
1375 P->replaceAllUsesWith(&*VMap[ExitInst]);
1377 P->replaceAllUsesWith(E);
1378 P->eraseFromParent();
1386 Value *NewVal =
PHI->getIncomingValueForBlock(Latch);
1388 if (LatchInst && L->contains(LatchInst))
1389 NewVal = LVMap[LatchInst];
1391 PHI->setIncomingValueForBlock(NewPreHeader, NewVal);
1396 unsigned AlreadyPeeled = 0;
1398 AlreadyPeeled = *Peeled;
1399 unsigned TotalPeeled = AlreadyPeeled + PeelCount;
1420 unsigned EstimatedTripCountNew = *EstimatedTripCount;
1421 if (EstimatedTripCountNew < TotalPeeled)
1422 EstimatedTripCountNew = 0;
1424 EstimatedTripCountNew -= TotalPeeled;
1428 if (
Loop *ParentLoop = L->getParentLoop())
1435#ifdef EXPENSIVE_CHECKS
1437 assert(DT.
verify(DominatorTree::VerificationLevel::Fast));
1441 simplifyLoop(L, &DT, LI, SE, AC,
nullptr, PreserveLCSSA);
1444 NumPeeledEnd += PeelLast;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
static bool shouldPeelLastIteration(Loop &L, CmpPredicate Pred, const SCEVAddRecExpr *LeftAR, const SCEV *RightSCEV, ScalarEvolution &SE, const TargetTransformInfo &TTI)
Returns true if the last iteration can be peeled off and the condition (Pred LeftAR,...
static bool violatesLegacyMultiExitLoopCheck(Loop *L)
This "heuristic" exactly matches implicit behavior which used to exist inside getLoopEstimatedTripCou...
static std::pair< unsigned, unsigned > countToEliminateCompares(Loop &L, unsigned MaxPeelCount, ScalarEvolution &SE, const TargetTransformInfo &TTI)
static void cloneLoopBlocks(Loop *L, unsigned IterNumber, bool PeelLast, BasicBlock *InsertTop, BasicBlock *InsertBot, BasicBlock *OrigPreHeader, SmallVectorImpl< std::pair< BasicBlock *, BasicBlock * > > &ExitEdges, SmallVectorImpl< BasicBlock * > &NewBlocks, LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, LoopInfo *LI, ArrayRef< MDNode * > LoopLocalNoAliasDeclScopes, ScalarEvolution &SE)
Clones the body of the loop L, putting it between InsertTop and InsertBot.
static unsigned peelToTurnInvariantLoadsDereferenceable(Loop &L, DominatorTree &DT, AssumptionCache *AC)
This file implements a map that provides insertion order iteration.
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
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 getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
A parsed version of the target data layout string in and methods for querying it.
DomTreeNodeBase * getIDom() const
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
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...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
Store the result of a depth first search within basic blocks contained by a single loop.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
This class implements a map that also provides access to all stored values in a deterministic order.
This class represents min/max intrinsics.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
const Loop * getLoop() const
SCEVUse 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 isHighCostExpansion(ArrayRef< const SCEV * > Exprs, Loop *L, unsigned Budget, const TargetTransformInfo *TTI, const Instruction *At)
Return true for expressions that can't be evaluated at runtime within given Budget.
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
bool hasNoSelfWrap() const
This class represents an analyzed expression in the program.
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
The main scalar evolution driver.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI 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...
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
This class represents the LLVM 'select' instruction.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
self_iterator getIterator()
@ BasicBlock
Various leaf nodes.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
bool match(const SCEV *S, const Pattern &P)
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
initializer< Ty > init(const Ty &Val)
NodeAddr< PhiNode * > Phi
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
FunctionAddr VTableAddr Value
cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
static cl::opt< bool > DisableAdvancedPeeling("disable-advanced-peeling", cl::init(false), cl::Hidden, cl::desc("Disable advance peeling. Issues for convergent targets (D134803)."))
static cl::opt< bool > UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, cl::desc("Allows loops to be peeled when the dynamic " "trip count is known to be low."))
LLVM_ABI bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB)
Check if we can prove that all paths starting from this block converge to a block that either has a @...
static cl::opt< bool > EnablePeelingForIV("enable-peeling-for-iv", cl::init(false), cl::Hidden, cl::desc("Enable peeling to convert Phi nodes into IVs"))
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
bool canPeel(const Loop *L)
bool canPeelLastIteration(const Loop &L, ScalarEvolution &SE)
Returns true if the last iteration of L can be peeled off.
LLVM_ABI void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
static const char * PeeledCountMetaData
DomTreeNodeBase< BasicBlock > DomTreeNode
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
TargetTransformInfo::PeelingPreferences gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, std::optional< bool > UserAllowPeeling, std::optional< bool > UserAllowProfileBasedPeeling, bool UnrollingSpecficValues=false)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void computePeelCount(Loop *L, unsigned LoopSize, TargetTransformInfo::PeelingPreferences &PP, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, const TargetTransformInfo &TTI, AssumptionCache *AC=nullptr, unsigned Threshold=UINT_MAX)
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
BranchProbability getLoopProbability(Loop *L)
Based on branch weight metadata, return either:
static cl::opt< unsigned > UnrollForcePeelCount("unroll-force-peel-count", cl::init(0), cl::Hidden, cl::desc("Force a peel count regardless of profiling information."))
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
void peelLoop(Loop *L, unsigned PeelCount, bool PeelLast, LoopInfo *LI, ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, bool PreserveLCSSA, ValueToValueMapTy &VMap)
VMap is the value-map that maps instructions from the original loop to instructions in the last peele...
LLVM_ABI std::optional< int > getOptionalIntLoopAttribute(const Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
bool setLoopProbability(Loop *L, BranchProbability P)
Set branch weight metadata for the latch of L to indicate that, at the end of any iteration,...
static cl::opt< bool > UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling", cl::init(false), cl::Hidden, cl::desc("Allows loop nests to be peeled."))
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
static cl::opt< unsigned > UnrollPeelMaxCount("unroll-peel-max-count", cl::init(7), cl::Hidden, cl::desc("Max average trip count which will cause loop peeling."))
LLVM_ABI void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
LLVM_ABI void remapInstructionsInBlocks(ArrayRef< BasicBlock * > Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.
std::enable_if_t< std::is_unsigned_v< T >, std::optional< T > > checkedAddUnsigned(T LHS, T RHS)
Add two unsigned integers LHS and RHS.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if this is always a dereferenceable pointer.
LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, std::optional< unsigned > EstimatedLoopInvocationWeight=std::nullopt)
Set llvm.loop.estimated_trip_count with the value EstimatedTripCount in the loop metadata of L.
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI bool formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
static cl::opt< unsigned > UnrollPeelCount("unroll-peel-count", cl::Hidden, cl::desc("Set the unroll peeling count, for testing purposes"))
LLVM_ABI Loop * cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, LoopInfo *LI, LPPassManager *LPM)
Recursively clone the specified loop and all of its children, mapping the blocks with the specified m...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.