31#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
32#define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
34#define SCEV_DEBUG_WITH_TYPE(TYPE, X)
41 cl::desc(
"When performing SCEV expansion only if it is cheap to do, this "
42 "controls the budget that is considered cheap (default = 4)"));
44using namespace PatternMatch;
66 for (
User *U : V->users()) {
67 if (U->getType() != Ty)
69 CastInst *CI = dyn_cast<CastInst>(U);
75 if (IP->getParent() == CI->
getParent() && &*BIP != CI &&
84 SCEVInsertPointGuard Guard(Builder,
this);
92 assert(!isa<Instruction>(Ret) ||
93 SE.DT.
dominates(cast<Instruction>(Ret), &*BIP));
102 if (
auto *II = dyn_cast<InvokeInst>(
I))
103 IP = II->getNormalDest()->begin();
105 while (isa<PHINode>(IP))
108 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
110 }
else if (isa<CatchSwitchInst>(IP)) {
113 assert(!IP->isEHPad() &&
"unexpected eh pad!");
126SCEVExpander::GetOptimalInsertionPointForCastOf(
Value *V)
const {
129 if (
Argument *
A = dyn_cast<Argument>(V)) {
131 while ((isa<BitCastInst>(IP) &&
132 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
133 cast<BitCastInst>(IP)->getOperand(0) !=
A) ||
134 isa<DbgInfoIntrinsic>(IP))
145 assert(isa<Constant>(V) &&
146 "Expected the cast argument to be a global/constant");
158 assert((
Op == Instruction::BitCast ||
159 Op == Instruction::PtrToInt ||
160 Op == Instruction::IntToPtr) &&
161 "InsertNoopCastOfTo cannot perform non-noop casts!");
163 "InsertNoopCastOfTo cannot change sizes!");
170 if (
Op == Instruction::IntToPtr) {
171 auto *PtrTy = cast<PointerType>(Ty);
174 "alloc size of i8 must by 1 byte for the GEP to be correct");
180 if (
Op == Instruction::BitCast) {
181 if (
V->getType() == Ty)
183 if (
CastInst *CI = dyn_cast<CastInst>(V)) {
189 if ((
Op == Instruction::PtrToInt ||
Op == Instruction::IntToPtr) &&
191 if (
CastInst *CI = dyn_cast<CastInst>(V))
192 if ((CI->
getOpcode() == Instruction::PtrToInt ||
193 CI->
getOpcode() == Instruction::IntToPtr) &&
198 if ((
CE->getOpcode() == Instruction::PtrToInt ||
199 CE->getOpcode() == Instruction::IntToPtr) &&
202 return CE->getOperand(0);
210 return ReuseOrCreateCast(V, Ty,
Op, GetOptimalInsertionPointForCastOf(V));
220 if (
Constant *CLHS = dyn_cast<Constant>(LHS))
221 if (
Constant *CRHS = dyn_cast<Constant>(RHS))
226 unsigned ScanLimit = 6;
230 if (IP != BlockBegin) {
232 for (; ScanLimit; --IP, --ScanLimit) {
235 if (isa<DbgInfoIntrinsic>(IP))
240 if (isa<OverflowingBinaryOperator>(
I)) {
248 if (isa<PossiblyExactOperator>(
I) &&
I->isExact())
253 IP->getOperand(1) ==
RHS && !canGenerateIncompatiblePoison(&*IP))
255 if (IP == BlockBegin)
break;
261 SCEVInsertPointGuard Guard(Builder,
this);
266 if (!
L->isLoopInvariant(LHS) || !
L->isLoopInvariant(RHS))
break;
268 if (!Preheader)
break;
316 assert(!isa<Instruction>(V) ||
322 if (
Constant *CLHS = dyn_cast<Constant>(V))
327 unsigned ScanLimit = 6;
331 if (IP != BlockBegin) {
333 for (; ScanLimit; --IP, --ScanLimit) {
336 if (isa<DbgInfoIntrinsic>(IP))
338 if (IP->getOpcode() == Instruction::GetElementPtr &&
339 IP->getOperand(0) == V && IP->getOperand(1) ==
Idx &&
340 cast<GEPOperator>(&*IP)->getSourceElementType() ==
343 if (IP == BlockBegin)
break;
348 SCEVInsertPointGuard Guard(Builder,
this);
352 if (!
L->isLoopInvariant(V) || !
L->isLoopInvariant(
Idx))
break;
354 if (!Preheader)
break;
371 if (
A->contains(
B))
return B;
372 if (
B->contains(
A))
return A;
373 if (DT.
dominates(
A->getHeader(),
B->getHeader()))
return B;
374 if (DT.
dominates(
B->getHeader(),
A->getHeader()))
return A;
380const Loop *SCEVExpander::getRelevantLoop(
const SCEV *S) {
382 auto Pair = RelevantLoops.insert(std::make_pair(S,
nullptr));
384 return Pair.first->second;
403 const Loop *
L =
nullptr;
408 return RelevantLoops[S] =
L;
412 if (
const Instruction *
I = dyn_cast<Instruction>(
U->getValue()))
413 return Pair.first->second = SE.LI.
getLoopFor(
I->getParent());
431 bool operator()(std::pair<const Loop *, const SCEV *>
LHS,
432 std::pair<const Loop *, const SCEV *>
RHS)
const {
439 if (
LHS.first !=
RHS.first)
445 if (
LHS.second->isNonConstantNegative()) {
446 if (!
RHS.second->isNonConstantNegative())
448 }
else if (
RHS.second->isNonConstantNegative())
465 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
473 Value *Sum =
nullptr;
474 for (
auto I = OpsAndLoops.
begin(),
E = OpsAndLoops.
end();
I !=
E;) {
475 const Loop *CurLoop =
I->first;
484 assert(!
Op->getType()->isPointerTy() &&
"Only first op can be pointer");
485 if (isa<PointerType>(Sum->
getType())) {
489 for (;
I !=
E &&
I->first == CurLoop; ++
I) {
492 const SCEV *
X =
I->second;
494 if (!isa<Instruction>(
U->getValue()))
498 Sum = expandAddToGEP(SE.
getAddExpr(NewOps), Sum);
499 }
else if (
Op->isNonConstantNegative()) {
509 if (isa<Constant>(Sum))
527 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
534 Value *Prod =
nullptr;
535 auto I = OpsAndLoops.
begin();
540 const auto ExpandOpBinPowN = [
this, &
I, &OpsAndLoops]() {
550 while (
E != OpsAndLoops.
end() && *
I == *
E &&
Exponent != MaxExponent) {
554 assert(
Exponent > 0 &&
"Trying to calculate a zeroth exponent of operand?");
573 assert(Result &&
"Nothing was expanded?");
577 while (
I != OpsAndLoops.
end()) {
580 Prod = ExpandOpBinPowN();
581 }
else if (
I->second->isAllOnesValue()) {
588 Value *
W = ExpandOpBinPowN();
590 if (isa<Constant>(Prod))
std::swap(Prod, W);
597 if (
RHS->logBase2() ==
RHS->getBitWidth() - 1)
599 Prod = InsertBinop(Instruction::Shl, Prod,
603 Prod = InsertBinop(Instruction::Mul, Prod, W, S->
getNoWrapFlags(),
616 if (
RHS.isPowerOf2())
617 return InsertBinop(Instruction::LShr, LHS,
632 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
637 if (L == IVIncInsertLoop) {
640 if (!SE.DT.
dominates(OInst, IVIncInsertPos))
644 IncV = dyn_cast<Instruction>(IncV->
getOperand(0));
654 return isNormalAddRecExprPHI(PN, IncV, L);
669 if (IncV == InsertPos)
676 case Instruction::Add:
677 case Instruction::Sub: {
679 if (!OInst || SE.DT.
dominates(OInst, InsertPos))
680 return dyn_cast<Instruction>(IncV->
getOperand(0));
683 case Instruction::BitCast:
684 return dyn_cast<Instruction>(IncV->
getOperand(0));
685 case Instruction::GetElementPtr:
687 if (isa<Constant>(U))
689 if (
Instruction *OInst = dyn_cast<Instruction>(U)) {
698 if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8))
702 return dyn_cast<Instruction>(IncV->
getOperand(0));
718 for (
auto *InsertPtGuard : InsertPointGuards)
719 if (InsertPtGuard->GetInsertPoint() == It)
720 InsertPtGuard->SetInsertPoint(NewInsertPt);
727 bool RecomputePoisonFlags) {
731 I->dropPoisonGeneratingFlags();
732 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(
I))
734 auto *BO = cast<BinaryOperator>(
I);
743 if (RecomputePoisonFlags)
744 FixupPoisonFlags(IncV);
750 if (isa<PHINode>(InsertPos) ||
770 fixupInsertPoints(
I);
771 I->moveBefore(InsertPos);
772 if (RecomputePoisonFlags)
786 (IVOper =
getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
802 IncV = expandAddToGEP(SE.
getSCEV(StepV), PN);
818 Type *PhiTy = Phi->getType();
832 if (Phi == Requested) {
847 if (!isa<IntegerType>(AR->
getType()))
855 const SCEV *ExtendAfterOp =
857 return ExtendAfterOp == OpAfterExtend;
861 if (!isa<IntegerType>(AR->
getType()))
869 const SCEV *ExtendAfterOp =
871 return ExtendAfterOp == OpAfterExtend;
878SCEVExpander::getAddRecExprPHILiterally(
const SCEVAddRecExpr *Normalized,
881 assert((!IVIncInsertLoop || IVIncInsertPos) &&
882 "Uninitialized insert position");
887 PHINode *AddRecPhiMatch =
nullptr;
894 bool TryNonMatchingSCEV =
898 for (
PHINode &PN :
L->getHeader()->phis()) {
906 DebugType,
dbgs() <<
"One incomplete PHI is found: " << PN <<
"\n");
914 bool IsMatchingSCEV = PhiSCEV == Normalized;
918 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
929 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
932 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
937 if (IsMatchingSCEV) {
941 AddRecPhiMatch = &PN;
947 if ((!TruncTy || InvertStep) &&
951 AddRecPhiMatch = &PN;
953 TruncTy = Normalized->
getType();
957 if (AddRecPhiMatch) {
960 InsertedValues.insert(AddRecPhiMatch);
962 rememberInstruction(IncV);
964 ReusedValues.
insert(AddRecPhiMatch);
965 ReusedValues.
insert(IncV);
966 return AddRecPhiMatch;
971 SCEVInsertPointGuard Guard(Builder,
this);
981 PostIncLoops.
clear();
984 assert(
L->getLoopPreheader() &&
985 "Can't expand add recurrences without a loop preheader!");
987 expand(Normalized->
getStart(),
L->getLoopPreheader()->getTerminator());
991 assert(!isa<Instruction>(StartV) ||
1006 Value *StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1011 bool IncrementIsNUW = !useSubtract &&
IsIncrementNUW(SE, Normalized);
1012 bool IncrementIsNSW = !useSubtract &&
IsIncrementNSW(SE, Normalized);
1019 Twine(IVName) +
".iv");
1026 if (!
L->contains(Pred)) {
1037 Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1039 if (isa<OverflowingBinaryOperator>(IncV)) {
1041 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1043 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1050 PostIncLoops = SavedPostIncLoops;
1054 InsertedValues.insert(PN);
1055 InsertedIVs.push_back(PN);
1065 if (PostIncLoops.
count(L)) {
1068 Normalized = cast<SCEVAddRecExpr>(
1072 [[maybe_unused]]
const SCEV *Start = Normalized->
getStart();
1075 "Start does not properly dominate loop header");
1076 assert(SE.
dominates(Step,
L->getHeader()) &&
"Step not dominate loop header");
1080 Type *TruncTy =
nullptr;
1081 bool InvertStep =
false;
1082 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1086 if (!PostIncLoops.
count(L))
1091 assert(LatchBlock &&
"PostInc mode requires a unique loop latch!");
1097 if (isa<OverflowingBinaryOperator>(Result)) {
1098 auto *
I = cast<Instruction>(Result);
1100 I->setHasNoUnsignedWrap(
false);
1102 I->setHasNoSignedWrap(
false);
1108 if (isa<Instruction>(Result) &&
1109 !SE.DT.
dominates(cast<Instruction>(Result),
1127 SCEVInsertPointGuard Guard(Builder,
this);
1128 StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1130 Result = expandIVInc(PN, StepV, L, useSubtract);
1138 if (TruncTy !=
Result->getType())
1161 return expandAddRecExprLiterally(S);
1167 PHINode *CanonicalIV =
nullptr;
1168 if (
PHINode *PN =
L->getCanonicalInductionVariable())
1190 if (isa<PointerType>(S->
getType())) {
1206 return expand(SE.
getAddExpr(AddExprLHS, AddExprRHS));
1217 rememberInstruction(CanonicalIV);
1223 if (!PredSeen.
insert(HP).second) {
1230 if (
L->contains(HP)) {
1237 rememberInstruction(
Add);
1248 "IVs with types different from the canonical IV should "
1249 "already have been handled!");
1271 const SCEV *NewS = S;
1273 if (isa<SCEVAddRecExpr>(Ext))
1276 const SCEV *
V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1285 return ReuseOrCreateCast(V, S->
getType(), CastInst::PtrToInt,
1286 GetOptimalInsertionPointForCastOf(V));
1307 bool IsSequential) {
1314 if (IsSequential && i != 0)
1331 return expandMinMaxExpr(S, Intrinsic::smax,
"smax");
1335 return expandMinMaxExpr(S, Intrinsic::umax,
"umax");
1339 return expandMinMaxExpr(S, Intrinsic::smin,
"smin");
1343 return expandMinMaxExpr(S, Intrinsic::umin,
"umin");
1347 return expandMinMaxExpr(S, Intrinsic::umin,
"umin",
true);
1363 Value *V = expand(SH);
1367 "non-trivial casts should be done with the SCEVs directly!");
1368 V = InsertNoopCastOfTo(V, Ty);
1390 while (!Worklist.
empty()) {
1392 if (!Visited.
insert(V).second)
1396 if (Visited.
size() > 16)
1404 auto *
I = dyn_cast<Instruction>(V);
1411 if (
auto *II = dyn_cast<IntrinsicInst>(
I);
1412 II && II->getIntrinsicID() == Intrinsic::vscale)
1419 if (
I->hasPoisonGeneratingFlagsOrMetadata())
1428Value *SCEVExpander::FindValueInExprValueMap(
1437 if (isa<SCEVConstant>(S))
1440 for (
Value *V : SE.getSCEVValues(S)) {
1457 DropPoisonGeneratingInsts.
clear();
1468Value *SCEVExpander::expand(
const SCEV *S) {
1475 auto SafeToHoist = [](
const SCEV *S) {
1477 if (
const auto *
D = dyn_cast<SCEVUDivExpr>(S)) {
1478 if (
const auto *SC = dyn_cast<SCEVConstant>(
D->getRHS()))
1480 return SC->getValue()->isZero();
1490 if (SafeToHoist(S)) {
1492 L =
L->getParentLoop()) {
1495 if (
BasicBlock *Preheader =
L->getLoopPreheader()) {
1501 InsertPt =
L->getHeader()->getFirstInsertionPt();
1508 InsertPt =
L->getHeader()->getFirstInsertionPt();
1512 isa<DbgInfoIntrinsic>(&*InsertPt))) {
1513 InsertPt = std::next(InsertPt);
1521 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1522 if (
I != InsertedExpressions.end())
1525 SCEVInsertPointGuard Guard(Builder,
this);
1530 Value *
V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts);
1533 V = fixupLCSSAFormFor(V);
1536 I->dropPoisonGeneratingFlagsAndMetadata();
1544 InsertedExpressions[std::make_pair(S, &*InsertPt)] =
V;
1548void SCEVExpander::rememberInstruction(
Value *
I) {
1549 auto DoInsert = [
this](
Value *
V) {
1550 if (!PostIncLoops.
empty())
1551 InsertedPostIncValues.insert(V);
1553 InsertedValues.insert(V);
1570 for (
PHINode &PN : L->getHeader()->phis())
1584 unsigned NumElim = 0;
1594 auto *Const = dyn_cast<SCEVConstant>(SE.
getSCEV(PN));
1597 return Const->getValue();
1602 if (
Value *V = SimplifyPHINode(Phi)) {
1603 if (V->getType() != Phi->getType())
1606 Phi->replaceAllUsesWith(V);
1610 dbgs() <<
"INDVARS: Eliminated constant iv: " << *Phi
1621 if (Phi->getType()->isIntegerTy() &&
TTI &&
1627 if (isa<SCEVAddRecExpr>(PhiExpr)) {
1630 const SCEV *TruncExpr =
1632 ExprToIVMap[TruncExpr] = Phi;
1643 if (
BasicBlock *LatchBlock = L->getLoopLatch()) {
1647 dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1649 if (OrigInc && IsomorphicInc) {
1653 if (OrigPhiRef->
getType() == Phi->getType() &&
1654 !(ChainedPhis.count(Phi) ||
1655 isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
1656 (ChainedPhis.count(Phi) ||
1657 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1670 const SCEV *TruncExpr =
1672 if (OrigInc != IsomorphicInc &&
1673 TruncExpr == SE.
getSCEV(IsomorphicInc) &&
1677 DebugType,
dbgs() <<
"INDVARS: Eliminated congruent iv.inc: "
1678 << *IsomorphicInc <<
'\n');
1679 Value *NewInc = OrigInc;
1682 if (
PHINode *PN = dyn_cast<PHINode>(OrigInc))
1690 OrigInc, IsomorphicInc->
getType(), IVName);
1698 dbgs() <<
"INDVARS: Eliminated congruent iv: " << *Phi
1701 DebugType,
dbgs() <<
"INDVARS: Original iv: " << *OrigPhiRef <<
'\n');
1703 Value *NewIV = OrigPhiRef;
1704 if (OrigPhiRef->
getType() != Phi->getType()) {
1706 L->getHeader()->getFirstInsertionPt());
1710 Phi->replaceAllUsesWith(NewIV);
1722 L->getExitingBlocks(ExitingBlocks);
1729 if (!
match(BB->getTerminator(),
1746 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) !=
nullptr;
1757 struct OperationIndices {
1758 OperationIndices(
unsigned Opc,
size_t min,
size_t max) :
1759 Opcode(Opc), MinIdx(min), MaxIdx(
max) { }
1773 S->getOperand(0)->getType(),
1777 auto ArithCost = [&](
unsigned Opcode,
unsigned NumRequired,
1778 unsigned MinIdx = 0,
1781 return NumRequired *
1785 auto CmpSelCost = [&](
unsigned Opcode,
unsigned NumRequired,
unsigned MinIdx,
1788 Type *OpType = S->getType();
1794 switch (S->getSCEVType()) {
1802 Cost = CastCost(Instruction::PtrToInt);
1805 Cost = CastCost(Instruction::Trunc);
1808 Cost = CastCost(Instruction::ZExt);
1811 Cost = CastCost(Instruction::SExt);
1814 unsigned Opcode = Instruction::UDiv;
1815 if (
auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1816 if (SC->getAPInt().isPowerOf2())
1817 Opcode = Instruction::LShr;
1822 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
1828 Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
1837 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
1838 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
1839 switch (S->getSCEVType()) {
1843 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
1844 Cost += ArithCost(Instruction::Or,
1845 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
1846 Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
1850 assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
1851 "Unhandled SCEV expression type?");
1860 return !Op->isZero();
1863 assert(NumTerms >= 1 &&
"Polynominal should have at least one term.");
1864 assert(!(*std::prev(S->operands().end()))->isZero() &&
1865 "Last operand should not be zero");
1868 int NumNonZeroDegreeNonOneTerms =
1870 auto *SConst = dyn_cast<SCEVConstant>(Op);
1871 return !SConst || SConst->getAPInt().ugt(1);
1880 ArithCost(Instruction::Mul, NumNonZeroDegreeNonOneTerms);
1881 Cost = AddCost + MulCost;
1884 int PolyDegree = S->getNumOperands() - 1;
1885 assert(PolyDegree >= 1 &&
"Should be at least affine.");
1893 Cost += MulCost * (PolyDegree - 1);
1898 for (
auto &CostOp : Operations) {
1899 for (
auto SCEVOp :
enumerate(S->operands())) {
1901 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
1902 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
1903 Worklist.
emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
1909bool SCEVExpander::isHighCostExpansionHelper(
1919 if (!isa<SCEVConstant>(S) && !Processed.
insert(S).second)
1928 L->getHeader()->getParent()->hasMinSize()
1943 const APInt &
Imm = cast<SCEVConstant>(S)->getAPInt();
1947 return Cost > Budget;
1981 assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
1982 "Nary expr should have more than 1 operand.");
1987 return Cost > Budget;
1990 assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
1991 "Polynomial should be at least linear");
1992 Cost += costAndCollectOperands<SCEVAddRecExpr>(
1994 return Cost > Budget;
2009 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2023 auto *
I = Builder.
CreateICmp(InvPred, Expr0, Expr1,
"ident.check");
2030 "non-affine expression");
2034 const SCEV *ExitCount =
2037 assert(!isa<SCEVCouldNotCompute>(ExitCount) &&
"Invalid loop count");
2052 Value *TripCountVal = expand(ExitCount, Loc);
2057 Value *StepValue = expand(Step, Loc);
2059 Value *StartValue = expand(Start, Loc);
2077 auto ComputeEndCheck = [&]() ->
Value * {
2085 Value *MulV, *OfMul;
2086 if (Step->
isOne()) {
2090 MulV = TruncTripCount;
2094 Intrinsic::umul_with_overflow, Ty);
2096 Builder.
CreateCall(MulF, {AbsStep, TruncTripCount},
"mul");
2101 Value *
Add =
nullptr, *Sub =
nullptr;
2105 if (isa<PointerType>(ARTy)) {
2115 Sub = Builder.
CreateSub(StartValue, MulV);
2118 Value *EndCompareLT =
nullptr;
2119 Value *EndCompareGT =
nullptr;
2120 Value *EndCheck =
nullptr;
2122 EndCheck = EndCompareLT = Builder.
CreateICmp(
2125 EndCheck = EndCompareGT = Builder.
CreateICmp(
2127 if (NeedPosCheck && NeedNegCheck) {
2129 EndCheck = Builder.
CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2131 return Builder.
CreateOr(EndCheck, OfMul);
2133 Value *EndCheck = ComputeEndCheck();
2138 if (SrcBits > DstBits) {
2140 auto *BackedgeCheck =
2146 EndCheck = Builder.
CreateOr(EndCheck, BackedgeCheck);
2154 const auto *
A = cast<SCEVAddRecExpr>(Pred->
getExpr());
2155 Value *NSSWCheck =
nullptr, *NUSWCheck =
nullptr;
2165 if (NUSWCheck && NSSWCheck)
2166 return Builder.
CreateOr(NUSWCheck, NSSWCheck);
2181 for (
const auto *Pred : Union->getPredicates()) {
2191Value *SCEVExpander::fixupLCSSAFormFor(
Value *V) {
2192 auto *DefI = dyn_cast<Instruction>(V);
2193 if (!PreserveLCSSA || !DefI)
2199 if (!DefLoop || UseLoop == DefLoop || DefLoop->
contains(UseLoop))
2210 if (DefI->getType()->isIntegerTy())
2216 auto RemoveUserOnExit =
2225 for (
PHINode *PN : InsertedPHIs)
2226 rememberInstruction(PN);
2227 for (
PHINode *PN : PHIsToRemove) {
2230 InsertedValues.erase(PN);
2231 InsertedPostIncValues.erase(PN);
2257struct SCEVFindUnsafe {
2260 bool IsUnsafe =
false;
2263 : SE(SE), CanonicalMode(CanonicalMode) {}
2265 bool follow(
const SCEV *S) {
2275 if (!AR->getLoop()->getLoopPreheader() &&
2276 (!CanonicalMode || !AR->isAffine())) {
2283 bool isDone()
const {
return IsUnsafe; }
2288 SCEVFindUnsafe Search(SE, CanonicalMode);
2290 return !Search.IsUnsafe;
2308 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2323 InsertedInstructions.end());
2333 [&InsertedSet](
Value *U) {
2334 return InsertedSet.contains(cast<Instruction>(U));
2336 "removed instruction should only be used by instructions inserted "
2337 "during expansion");
2339 assert(!
I->getType()->isVoidTy() &&
2340 "inserted instruction should have non-void types");
2342 I->eraseFromParent();
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static cl::opt< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
static const Loop * PickMostRelevantLoop(const Loop *A, const Loop *B, DominatorTree &DT)
PickMostRelevantLoop - Given two loops pick the one that's most relevant for SCEV expansion.
static bool canReuseInstruction(ScalarEvolution &SE, const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
static InstructionCost costAndCollectOperands(const SCEVOperand &WorkItem, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, SmallVectorImpl< SCEVOperand > &Worklist)
static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
static bool canBeCheaplyTransformed(ScalarEvolution &SE, const SCEVAddRecExpr *Phi, const SCEVAddRecExpr *Requested, bool &InvertStep)
Check whether we can cheaply express the requested SCEV in terms of the available PHI SCEV by truncat...
#define SCEV_DEBUG_WITH_TYPE(TYPE, X)
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallSet class.
static constexpr uint32_t Opcode
Class for arbitrary precision integers.
APInt zext(unsigned width) const
Zero extend to a new width.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
This class represents an incoming formal argument to a Function.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
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...
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
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 getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
A constant value that is initialized with an expression using other constant values.
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
This is the shared class of boolean and integer constants.
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
This class represents an Operation in the Expression.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
bool isNonIntegralPointerType(PointerType *PT) const
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
const BasicBlock & getEntryBlock() const
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateVScale(Constant *Scaling, const Twine &Name="")
Create a call to llvm.vscale, multiplied by Scaling.
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
BasicBlock::iterator GetInsertPoint() const
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateFreeze(Value *V, const Twine &Name="")
BasicBlock * GetInsertBlock() const
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", bool IsInBounds=false)
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
const BasicBlock * getParent() const
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const Function * getFunction() const
Return the function this instruction belongs to.
bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
const Instruction * getNextNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the next non-debug instruction in the same basic block as 'this',...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for 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.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc)
Checks if moving a specific instruction can break LCSSA in any loop.
Represents a single loop in the control flow graph.
ICmpInst::Predicate getPredicate() const
Returns the comparison predicate underlying the intrinsic.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
bool isComplete() const
If the PHI node is complete which means all of its parent's predecessors have incoming value in this ...
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This node represents an addition of some number of SCEVs.
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.
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
const SCEV * getOperand() const
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
const SCEV * getRHS() const
Returns the right hand side of the predicate.
ICmpInst::Predicate getPredicate() const
const SCEV * getLHS() const
Returns the left hand side of the predicate.
This class represents a constant integer value.
Value * generateOverflowCheck(const SCEVAddRecExpr *AR, Instruction *Loc, bool Signed)
Generates code that evaluates if the AR expression will overflow.
bool hasRelatedExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Determine whether there is an existing expansion of S that can be reused.
SmallVector< Instruction *, 32 > getAllInsertedInstructions() const
Return a vector containing all instructions inserted during expansion.
bool isSafeToExpand(const SCEV *S) const
Return true if the given expression is safe to expand in the sense that all materialized values are s...
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...
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
Value * expandUnionPredicate(const SCEVUnionPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
bool hoistIVInc(Instruction *IncV, Instruction *InsertPos, bool RecomputePoisonFlags=false)
Utility for hoisting IncV (with all subexpressions requried for its computation) before InsertPos.
void clear()
Erase the contents of the InsertedExpressions map so that users trying to expand the same expression ...
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
Value * expandComparePredicate(const SCEVComparePredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
Value * expandCodeFor(const SCEV *SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
Value * expandWrapPredicate(const SCEVWrapPredicate *P, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
Instruction * getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale)
Return the induction variable increment's IV operand.
BasicBlock::iterator findInsertPointAfter(Instruction *I, Instruction *MustDominate) const
Returns a suitable insert point after I, that dominates MustDominate.
void setInsertPoint(Instruction *IP)
Set the current insertion point.
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
bool hasNoUnsignedWrap() const
size_t getNumOperands() const
bool hasNoSignedWrap() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
const SCEV * getOperand(unsigned i) const
ArrayRef< const SCEV * > operands() const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicateKind getKind() const
This class represents a cast from a pointer to a pointer-sized integer value.
This class represents a signed maximum selection.
This class represents a signed minimum selection.
This class represents a sequential/in-order unsigned minimum selection.
This class represents a sign extension of a small integer value to a larger integer value.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
const SCEV * getLHS() const
const SCEV * getRHS() const
This class represents an unsigned maximum selection.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
ArrayRef< const SCEV * > operands() const
Return operands of this SCEV expression.
bool isOne() const
Return true if the expression is a constant one.
bool isZero() const
Return true if the expression is a constant zero.
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
SCEVTypes getSCEVType() const
Type * getType() const
Return the LLVM type of this SCEV expression.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
The main scalar evolution driver.
bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
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.
const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
const SCEV * getConstant(ConstantInt *V)
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVector< const SCEVPredicate *, 4 > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
const SCEV * getAnyExtendExpr(const SCEV *Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
std::optional< SCEV::NoWrapFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
const SCEV * getMulExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
const SCEV * getUnknown(Value *V)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask)
Convenient NoWrapFlags manipulation that hides enum casts and is visible in the ScalarEvolution name ...
bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
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.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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.
bool contains(ConstPtrType Ptr) const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
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...
The instances of the Type class are immutable: once they are created, they are never changed.
unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static IntegerType * getInt32Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
iterator_range< value_op_iterator > operand_values()
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
constexpr ScalarTy getFixedValue() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
bool match(Val *V, const Pattern &P)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
@ CE
Windows NT (Windows on ARM)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void stable_sort(R &&Range)
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 canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are are tuples (A,...
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
Interval::pred_iterator pred_end(Interval *I)
auto reverse(ContainerTy &&C)
bool programUndefinedIfPoison(const Instruction *Inst)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
cl::opt< unsigned > SCEVCheapExpansionBudget
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
const SCEV * normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE, bool CheckInvertible=true)
Normalize S to be post-increment for all loops present in Loops.
@ Mul
Product of integers.
constexpr unsigned BitWidth
bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
struct for holding enough information to help calculate the cost of the given SCEV when expanded into...
Value * visit(const SCEV *S)