32#if LLVM_ENABLE_ABI_BREAKING_CHECKS
33#define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
35#define SCEV_DEBUG_WITH_TYPE(TYPE, X)
42 cl::desc(
"When performing SCEV expansion only if it is cheap to do, this "
43 "controls the budget that is considered cheap (default = 4)"));
57 NUW = OBO->hasNoUnsignedWrap();
58 NSW = OBO->hasNoSignedWrap();
61 Exact = PEO->isExact();
65 NNeg = PNI->hasNonNeg();
67 NUW = TI->hasNoUnsignedWrap();
68 NSW = TI->hasNoSignedWrap();
78 I->setHasNoUnsignedWrap(
NUW);
79 I->setHasNoSignedWrap(
NSW);
88 I->setHasNoUnsignedWrap(
NUW);
89 I->setHasNoSignedWrap(
NSW);
114 Value *Ret =
nullptr;
119 if (U->getType() != Ty)
128 if (IP->getParent() == CI->
getParent() && &*BIP != CI &&
138 SCEVInsertPointGuard Guard(Builder,
this);
139 Builder.SetInsertPoint(&*IP);
140 Ret = Builder.CreateCast(
Op, V, Ty,
V->getName());
156 if (
auto MaybeIP =
I->getInsertionPointAfterDef()) {
159 assert(SE.DT.dominates(
I, MustDominate) &&
160 "instruction must dominate the insertion point");
177 while (!WorkList.
empty()) {
186 InsertedValues.erase(
I);
187 InsertedPostIncValues.erase(
I);
189 I->eraseFromParent();
194SCEVExpander::GetOptimalInsertionPointForCastOf(
Value *V)
const {
213 "Expected the cast argument to be a global/constant");
214 return Builder.GetInsertBlock()
217 .getFirstInsertionPt();
225 assert((
Op == Instruction::BitCast ||
226 Op == Instruction::PtrToInt ||
227 Op == Instruction::IntToPtr) &&
228 "InsertNoopCastOfTo cannot perform non-noop casts!");
229 assert(SE.getTypeSizeInBits(
V->getType()) == SE.getTypeSizeInBits(Ty) &&
230 "InsertNoopCastOfTo cannot change sizes!");
237 if (
Op == Instruction::IntToPtr) {
239 if (DL.isNonIntegralPointerType(PtrTy))
243 if (
Op == Instruction::BitCast) {
244 if (
V->getType() == Ty)
252 if ((
Op == Instruction::PtrToInt ||
Op == Instruction::IntToPtr) &&
253 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(
V->getType())) {
255 if ((CI->
getOpcode() == Instruction::PtrToInt ||
256 CI->
getOpcode() == Instruction::IntToPtr) &&
257 SE.getTypeSizeInBits(CI->
getType()) ==
261 if ((
CE->getOpcode() == Instruction::PtrToInt ||
262 CE->getOpcode() == Instruction::IntToPtr) &&
263 SE.getTypeSizeInBits(
CE->getType()) ==
264 SE.getTypeSizeInBits(
CE->getOperand(0)->getType()))
265 return CE->getOperand(0);
273 return ReuseOrCreateCast(V, Ty,
Op, GetOptimalInsertionPointForCastOf(V));
289 unsigned ScanLimit = 6;
293 if (IP != BlockBegin) {
295 for (; ScanLimit; --IP, --ScanLimit) {
310 if (IP->getOpcode() == (
unsigned)Opcode && IP->getOperand(0) ==
LHS &&
311 IP->getOperand(1) ==
RHS && !canGenerateIncompatiblePoison(&*IP))
313 if (IP == BlockBegin)
break;
318 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
319 SCEVInsertPointGuard Guard(Builder,
this);
323 while (
const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
324 if (!
L->isLoopInvariant(
LHS) || !
L->isLoopInvariant(
RHS))
break;
326 if (!Preheader)
break;
334 Builder.SetCurrentDebugLocation(Loc);
339 if (LSRMode && !PostIncLoops.empty() &&
340 all_of(PostIncLoops, [&](
const Loop *L) {
341 return !
L->contains(Builder.GetInsertBlock());
345 BO->setHasNoUnsignedWrap();
347 BO->setHasNoSignedWrap();
348 return Builder.Insert(BO);
350 return Builder.CreateNoWrapBinOp(Opcode,
LHS,
RHS, IsNUW, IsNSW);
388 : GEPNoWrapFlags::
none();
393 return Builder.CreatePtrAdd(CLHS, CRHS,
"", NW);
396 unsigned ScanLimit = 6;
400 if (IP != BlockBegin) {
402 for (; ScanLimit; --IP, --ScanLimit) {
404 if (
GEP->getPointerOperand() == V &&
405 GEP->getSourceElementType() == Builder.getInt8Ty() &&
406 GEP->getOperand(1) == Idx) {
408 GEP->setNoWrapFlags(
GEP->getNoWrapFlags() & NW);
412 if (IP == BlockBegin)
break;
417 SCEVInsertPointGuard Guard(Builder,
this);
420 while (
const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
421 if (!
L->isLoopInvariant(V) || !
L->isLoopInvariant(Idx))
break;
423 if (!Preheader)
break;
430 return Builder.CreatePtrAdd(V, Idx,
"scevgep", NW);
440 if (
A->contains(
B))
return B;
441 if (
B->contains(
A))
return A;
442 if (DT.
dominates(
A->getHeader(),
B->getHeader()))
return B;
443 if (DT.
dominates(
B->getHeader(),
A->getHeader()))
return A;
449const Loop *SCEVExpander::getRelevantLoop(
const SCEV *S) {
451 auto Pair = RelevantLoops.try_emplace(S);
453 return Pair.first->second;
473 const Loop *
L =
nullptr;
478 return RelevantLoops[S] =
L;
483 return Pair.first->second = SE.LI.getLoopFor(
I->getParent());
499 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
501 bool operator()(std::pair<const Loop *, const SCEV *>
LHS,
502 std::pair<const Loop *, const SCEV *>
RHS)
const {
509 if (
LHS.first !=
RHS.first)
515 if (
LHS.second->isNonConstantNegative()) {
516 if (!
RHS.second->isNonConstantNegative())
518 }
else if (
RHS.second->isNonConstantNegative())
530 const SCEV *URemLHS =
nullptr;
531 const SCEV *URemRHS =
nullptr;
544 for (
const SCEV *
Op :
reverse(S->operands()))
545 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
553 Value *Sum =
nullptr;
554 for (
auto I = OpsAndLoops.
begin(),
E = OpsAndLoops.
end();
I !=
E;) {
555 const Loop *CurLoop =
I->first;
556 const SCEV *
Op =
I->second;
564 assert(!
Op->getType()->isPointerTy() &&
"Only first op can be pointer");
569 for (;
I !=
E &&
I->first == CurLoop; ++
I) {
572 const SCEV *
X =
I->second;
575 X = SE.getSCEV(
U->getValue());
578 Sum = expandAddToGEP(SE.getAddExpr(NewOps), Sum, S.
getNoWrapFlags());
579 }
else if (
Op->isNonConstantNegative()) {
581 Value *
W = expand(SE.getNegativeSCEV(
Op));
601 Type *Ty = S->getType();
606 for (
const SCEV *
Op :
reverse(S->operands()))
607 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
614 Value *Prod =
nullptr;
615 auto I = OpsAndLoops.
begin();
620 const auto ExpandOpBinPowN = [
this, &
I, &OpsAndLoops]() {
630 while (
E != OpsAndLoops.
end() && *
I == *
E &&
Exponent != MaxExponent) {
634 assert(
Exponent > 0 &&
"Trying to calculate a zeroth exponent of operand?");
642 for (uint64_t BinExp = 2; BinExp <=
Exponent; BinExp <<= 1) {
653 assert(Result &&
"Nothing was expanded?");
657 while (
I != OpsAndLoops.
end()) {
660 Prod = ExpandOpBinPowN();
661 }
else if (
I->second->isAllOnesValue()) {
668 Value *
W = ExpandOpBinPowN();
677 if (
RHS->logBase2() ==
RHS->getBitWidth() - 1)
679 Prod = InsertBinop(Instruction::Shl, Prod,
680 ConstantInt::get(Ty,
RHS->logBase2()), NWFlags,
695 const APInt &
RHS = SC->getAPInt();
696 if (
RHS.isPowerOf2())
697 return InsertBinop(Instruction::LShr,
LHS,
698 ConstantInt::get(SC->getType(),
RHS.logBase2()),
702 const SCEV *RHSExpr = S->getRHS();
705 bool GuaranteedNotPoison =
707 if (!GuaranteedNotPoison)
708 RHS = Builder.CreateFreeze(
RHS);
713 if (!SE.isKnownNonZero(RHSExpr) || !GuaranteedNotPoison)
714 RHS = Builder.CreateIntrinsic(
RHS->
getType(), Intrinsic::umax,
715 {RHS, ConstantInt::get(RHS->getType(), 1)});
718 SE.isKnownNonZero(S->getRHS()));
731 if (L == IVIncInsertLoop) {
734 if (!SE.DT.dominates(OInst, IVIncInsertPos))
748 return isNormalAddRecExprPHI(PN, IncV, L);
763 if (IncV == InsertPos)
770 case Instruction::Add:
771 case Instruction::Sub: {
773 if (!OInst || SE.DT.dominates(OInst, InsertPos))
777 case Instruction::BitCast:
779 case Instruction::GetElementPtr:
784 if (!SE.DT.dominates(OInst, InsertPos))
810 if (Builder.GetInsertPoint() == It)
811 Builder.SetInsertPoint(&*NewInsertPt);
812 for (
auto *InsertPtGuard : InsertPointGuards)
813 if (InsertPtGuard->GetInsertPoint() == It)
814 InsertPtGuard->SetInsertPoint(NewInsertPt);
821 bool RecomputePoisonFlags) {
826 I->dropPoisonGeneratingFlags();
828 if (
auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
830 BO->setHasNoUnsignedWrap(
832 BO->setHasNoSignedWrap(
837 if (SE.DT.dominates(IncV, InsertPos)) {
838 if (RecomputePoisonFlags)
839 FixupPoisonFlags(IncV);
849 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
861 if (SE.DT.dominates(IncV, InsertPos))
865 fixupInsertPoints(
I);
867 if (RecomputePoisonFlags)
890 (IVOper =
getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
907 IncV = Builder.CreatePtrAdd(PN, StepV,
"scevgep");
910 Builder.CreateSub(PN, StepV, Twine(IVName) +
".iv.next") :
911 Builder.CreateAdd(PN, StepV, Twine(IVName) +
".iv.next");
923 Type *PhiTy = Phi->getType();
937 if (Phi == Requested) {
960 const SCEV *ExtendAfterOp =
962 return ExtendAfterOp == OpAfterExtend;
974 const SCEV *ExtendAfterOp =
976 return ExtendAfterOp == OpAfterExtend;
983SCEVExpander::getAddRecExprPHILiterally(
const SCEVAddRecExpr *Normalized,
986 assert((!IVIncInsertLoop || IVIncInsertPos) &&
987 "Uninitialized insert position");
992 PHINode *AddRecPhiMatch =
nullptr;
999 bool TryNonMatchingSCEV =
1001 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1003 for (PHINode &PN :
L->getHeader()->phis()) {
1004 if (!SE.isSCEVable(PN.
getType()))
1011 DebugType,
dbgs() <<
"One incomplete PHI is found: " << PN <<
"\n");
1019 bool IsMatchingSCEV = PhiSCEV == Normalized;
1023 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1034 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1037 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1042 if (IsMatchingSCEV) {
1046 AddRecPhiMatch = &PN;
1052 if ((!TruncTy || InvertStep) &&
1056 AddRecPhiMatch = &PN;
1058 TruncTy = Normalized->
getType();
1062 if (AddRecPhiMatch) {
1065 InsertedValues.insert(AddRecPhiMatch);
1067 rememberInstruction(IncV);
1069 ReusedValues.insert(AddRecPhiMatch);
1070 ReusedValues.insert(IncV);
1071 return AddRecPhiMatch;
1076 SCEVInsertPointGuard Guard(Builder,
this);
1086 PostIncLoops.
clear();
1089 assert(
L->getLoopPreheader() &&
1090 "Can't expand add recurrences without a loop preheader!");
1092 expand(Normalized->
getStart(),
L->getLoopPreheader()->getTerminator());
1109 Step = SE.getNegativeSCEV(Step);
1111 Value *StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1116 bool IncrementIsNUW = !useSubtract &&
IsIncrementNUW(SE, Normalized);
1117 bool IncrementIsNSW = !useSubtract &&
IsIncrementNSW(SE, Normalized);
1121 Builder.SetInsertPoint(Header, Header->begin());
1123 Builder.CreatePHI(ExpandTy,
pred_size(Header), Twine(IVName) +
".iv");
1128 if (!
L->contains(Pred)) {
1137 IVIncInsertPos : Pred->getTerminator();
1138 Builder.SetInsertPoint(InsertPos);
1139 Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1152 PostIncLoops = SavedPostIncLoops;
1156 InsertedValues.
insert(PN);
1157 InsertedIVs.push_back(PN);
1163 const Loop *
L = S->getLoop();
1167 const SCEVAddRecExpr *Normalized = S;
1168 if (PostIncLoops.count(L)) {
1175 [[maybe_unused]]
const SCEV *
Start = Normalized->
getStart();
1177 assert(SE.properlyDominates(Start,
L->getHeader()) &&
1178 "Start does not properly dominate loop header");
1179 assert(SE.dominates(Step,
L->getHeader()) &&
"Step not dominate loop header");
1183 Type *TruncTy =
nullptr;
1184 bool InvertStep =
false;
1185 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1189 if (!PostIncLoops.count(L))
1194 assert(LatchBlock &&
"PostInc mode requires a unique loop latch!");
1202 if (!S->hasNoUnsignedWrap())
1203 I->setHasNoUnsignedWrap(
false);
1204 if (!S->hasNoSignedWrap())
1205 I->setHasNoSignedWrap(
false);
1213 &*Builder.GetInsertPoint())) {
1226 Step = SE.getNegativeSCEV(Step);
1230 SCEVInsertPointGuard Guard(Builder,
this);
1231 StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1233 Result = expandIVInc(PN, StepV, L, useSubtract);
1240 if (TruncTy !=
Result->getType() || InvertStep)
1241 Result = fixupLCSSAFormFor(Result);
1243 if (TruncTy !=
Result->getType())
1244 Result = Builder.CreateTrunc(Result, TruncTy);
1248 Result = Builder.CreateSub(expand(Normalized->
getStart()), Result);
1255 Type *STy = S->getType();
1256 const Loop *
L = S->getLoop();
1259 !SE.DT.dominates(EB, Builder.GetInsertBlock()))
1264 auto CanReuse = [&](
const SCEV *ExitSCEV) ->
const SCEV * {
1267 const SCEV *Diff = SE.getMinusSCEV(S, ExitSCEV);
1268 const SCEV *
Op = Diff;
1277 for (
auto &PN : EB->
phis()) {
1278 if (!SE.isSCEVable(PN.
getType()))
1280 auto *ExitSCEV = SE.getSCEV(&PN);
1284 const SCEV *Diff =
nullptr;
1286 DL.getAddressType(PhiTy) == STy) {
1287 const SCEV *AddrSCEV = SE.getPtrToAddrExpr(ExitSCEV);
1288 Diff = CanReuse(AddrSCEV);
1289 }
else if (STy == PhiTy) {
1290 Diff = CanReuse(ExitSCEV);
1296 "difference must be of integer type");
1297 Value *DiffV = expand(Diff);
1298 Value *BaseV = fixupLCSSAFormFor(&PN);
1301 return Builder.CreatePtrAdd(BaseV, DiffV);
1302 BaseV = Builder.CreatePtrToAddr(BaseV);
1304 return Builder.CreateAdd(BaseV, DiffV);
1321 if (!CanonicalMode || (S->getNumOperands() > 2))
1322 return expandAddRecExprLiterally(S);
1324 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1325 const Loop *
L = S->getLoop();
1328 PHINode *CanonicalIV =
nullptr;
1329 if (PHINode *PN =
L->getCanonicalInductionVariable())
1330 if (SE.getTypeSizeInBits(PN->
getType()) >= SE.getTypeSizeInBits(Ty))
1336 SE.getTypeSizeInBits(CanonicalIV->
getType()) > SE.getTypeSizeInBits(Ty) &&
1337 !S->getType()->isPointerTy()) {
1339 for (
unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1340 NewOps[i] = SE.getAnyExtendExpr(S->getOperand(i), CanonicalIV->
getType());
1345 &*Builder.GetInsertPoint())
1346 : Builder.GetInsertPoint();
1347 V = expand(SE.getTruncateExpr(SE.getUnknown(V), Ty), NewInsertPt);
1353 if (
Value *V = tryToReuseLCSSAPhi(S))
1357 if (!S->getStart()->isZero()) {
1359 Value *StartV = expand(SE.getPointerBase(S));
1360 return expandAddToGEP(SE.removePointerBase(S), StartV,
1365 NewOps[0] = SE.getConstant(Ty, 0);
1373 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1374 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1375 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1386 rememberInstruction(CanonicalIV);
1388 SmallPtrSet<BasicBlock *, 4> PredSeen;
1389 Constant *One = ConstantInt::get(Ty, 1);
1392 if (!PredSeen.
insert(HP).second) {
1399 if (
L->contains(HP)) {
1406 rememberInstruction(
Add);
1415 if (S->isAffine() && S->getOperand(1)->isOne()) {
1416 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->
getType()) &&
1417 "IVs with types different from the canonical IV should "
1418 "already have been handled!");
1427 expand(SE.getTruncateOrNoop(
1428 SE.getMulExpr(SE.getUnknown(CanonicalIV),
1429 SE.getNoopOrAnyExtend(S->getOperand(1),
1437 const SCEV *IH = SE.getUnknown(CanonicalIV);
1440 const SCEV *NewS = S;
1441 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->
getType());
1448 const SCEV *
T = SE.getTruncateOrNoop(V, Ty);
1458 if (CI->
getOpcode() == CastInst::PtrToAddr)
1460 if (CI->
getOpcode() != CastInst::PtrToInt)
1463 return DL.getPointerSizeInBits(AS) ==
DL.getIndexSizeInBits(AS);
1484 Type *Ty = S->getType();
1490 return &*BIP != CI && SE.DT.
dominates(CI, &*BIP);
1494 return ReuseOrCreateCast(V, Ty, CastInst::PtrToAddr,
1495 GetOptimalInsertionPointForCastOf(V));
1499 Value *
V = expand(S->getOperand());
1500 return ReuseOrCreateCast(V, S->getType(), CastInst::PtrToInt,
1501 GetOptimalInsertionPointForCastOf(V));
1505 Type *Ty = S->getType();
1511 Value *PtrOp = expand(PtrToAddr->getOperand());
1514 for (User *U : PtrOp->
users()) {
1516 if (CI && CI->
getType() == Ty &&
1517 CI->
getOpcode() == CastInst::PtrToInt && &*BIP != CI &&
1518 SE.DT.dominates(CI, &*BIP))
1524 Value *
V = expand(S->getOperand());
1525 return Builder.CreateTrunc(V, S->getType());
1530 Value *
V = expand(S->getOperand());
1531 return Builder.CreateZExt(V, S->getType(),
"",
1532 SE.isKnownNonNegative(S->getOperand()));
1537 Value *
V = expand(S->getOperand());
1538 return Builder.CreateSExt(V, S->getType());
1543 bool IsSequential) {
1544 bool PrevSafeMode = SafeUDivMode;
1545 SafeUDivMode |= IsSequential;
1546 Value *
LHS = expand(S->getOperand(S->getNumOperands() - 1));
1549 LHS = Builder.CreateFreeze(
LHS);
1550 for (
int i = S->getNumOperands() - 2; i >= 0; --i) {
1551 SafeUDivMode = (IsSequential && i != 0) || PrevSafeMode;
1552 Value *
RHS = expand(S->getOperand(i));
1553 if (IsSequential && i != 0)
1554 RHS = Builder.CreateFreeze(
RHS);
1557 Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {
LHS,
RHS},
1562 Sel = Builder.CreateSelect(ICmp,
LHS,
RHS, Name);
1566 SafeUDivMode = PrevSafeMode;
1571 return expandMinMaxExpr(S, Intrinsic::smax,
"smax");
1575 return expandMinMaxExpr(S, Intrinsic::umax,
"umax");
1579 return expandMinMaxExpr(S, Intrinsic::smin,
"smin");
1583 return expandMinMaxExpr(S, Intrinsic::umin,
"umin");
1586Value *SCEVExpander::visitSequentialUMinExpr(
1588 return expandMinMaxExpr(S, Intrinsic::umin,
"umin",
1593 return Builder.CreateVScale(S->getType());
1604 Value *V = expand(SH);
1606 if (Ty && Ty != V->getType()) {
1607 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->
getType()) &&
1608 "non-trivial casts should be done with the SCEVs directly!");
1609 V = InsertNoopCastOfTo(V, Ty);
1614Value *SCEVExpander::FindValueInExprValueMap(
1626 for (
Value *V : SE.getSCEVValues(S)) {
1643 DropPoisonGeneratingInsts.
clear();
1661 auto SafeToHoist = [](
const SCEV *S) {
1666 return SC->getValue()->isZero();
1676 if (SafeToHoist(S)) {
1677 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1678 L =
L->getParentLoop()) {
1679 if (SE.isLoopInvariant(S, L)) {
1681 if (BasicBlock *Preheader =
L->getLoopPreheader()) {
1687 InsertPt =
L->getHeader()->getFirstInsertionPt();
1693 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1694 InsertPt =
L->getHeader()->getFirstInsertionPt();
1696 while (InsertPt != Builder.GetInsertPoint() &&
1698 InsertPt = std::next(InsertPt);
1706 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1707 if (
I != InsertedExpressions.end())
1710 SCEVInsertPointGuard Guard(Builder,
this);
1711 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1714 SmallVector<Instruction *> DropPoisonGeneratingInsts;
1715 Value *
V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts);
1718 V = fixupLCSSAFormFor(V);
1720 for (Instruction *
I : DropPoisonGeneratingInsts) {
1731 InsertedExpressions[std::make_pair(S, &*InsertPt)] =
V;
1735void SCEVExpander::rememberInstruction(
Value *
I) {
1736 auto DoInsert = [
this](
Value *
V) {
1737 if (!PostIncLoops.empty())
1738 InsertedPostIncValues.insert(V);
1740 InsertedValues.insert(V);
1747 OrigFlags.try_emplace(
I, PoisonFlags(
I));
1752 I->dropPoisonGeneratingAnnotations();
1756 if (
auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
1758 BO->setHasNoUnsignedWrap(
1760 BO->setHasNoSignedWrap(
1764 auto *Src = NNI->getOperand(0);
1769 NNI->setNonNeg(
true);
1773void SCEVExpander::replaceCongruentIVInc(
1784 if (!OrigInc || !IsomorphicInc)
1790 if (OrigPhi->
getType() == Phi->getType()) {
1791 bool Chained = ChainedPhis.contains(Phi);
1792 if (!(Chained || isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) &&
1793 (Chained || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1808 const SCEV *TruncExpr =
1809 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->
getType());
1810 if (OrigInc == IsomorphicInc || TruncExpr != SE.getSCEV(IsomorphicInc) ||
1811 !SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc))
1814 bool BothHaveNUW =
false;
1815 bool BothHaveNSW =
false;
1818 if (OBOIncV && OBOIsomorphic) {
1820 OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap();
1822 OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap();
1835 "Should only replace an increment with a wider one.");
1836 if (BothHaveNUW || BothHaveNSW) {
1842 dbgs() <<
"INDVARS: Eliminated congruent iv.inc: "
1843 << *IsomorphicInc <<
'\n');
1844 Value *NewInc = OrigInc;
1848 IP = PN->
getParent()->getFirstInsertionPt();
1853 Builder.SetCurrentDebugLocation(IsomorphicInc->
getDebugLoc());
1855 Builder.CreateTruncOrBitCast(OrigInc, IsomorphicInc->
getType(), IVName);
1880 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1881 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1882 return RHS->getType()->getPrimitiveSizeInBits().getFixedValue() <
1883 LHS->getType()->getPrimitiveSizeInBits().getFixedValue();
1886 unsigned NumElim = 0;
1894 if (!SE.isSCEVable(PN->
getType()))
1899 return Const->getValue();
1904 if (
Value *V = SimplifyPHINode(Phi)) {
1905 if (V->getType() != Phi->getType())
1907 SE.forgetValue(Phi);
1908 Phi->replaceAllUsesWith(V);
1912 dbgs() <<
"INDVARS: Eliminated constant iv: " << *Phi
1917 if (!SE.isSCEVable(Phi->getType()))
1920 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1923 if (Phi->getType()->isIntegerTy() &&
TTI &&
1924 TTI->isTruncateFree(Phi->getType(), Phis.
back()->getType())) {
1928 const SCEV *PhiExpr = SE.getSCEV(Phi);
1932 const SCEV *TruncExpr =
1933 SE.getTruncateExpr(PhiExpr, Phis.
back()->getType());
1934 ExprToIVMap[TruncExpr] = Phi;
1945 replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts);
1947 dbgs() <<
"INDVARS: Eliminated congruent iv: " << *Phi
1950 DebugType,
dbgs() <<
"INDVARS: Original iv: " << *OrigPhiRef <<
'\n');
1952 Value *NewIV = OrigPhiRef;
1953 if (OrigPhiRef->
getType() != Phi->getType()) {
1955 L->getHeader()->getFirstInsertionPt());
1956 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1957 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1959 Phi->replaceAllUsesWith(NewIV);
1971 L->getExitingBlocks(ExitingBlocks);
1978 if (!
match(BB->getTerminator(),
1983 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1986 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1995 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) !=
nullptr;
2006 struct OperationIndices {
2007 OperationIndices(
unsigned Opc,
size_t min,
size_t max) :
2008 Opcode(
Opc), MinIdx(
min), MaxIdx(
max) { }
2021 return TTI.getCastInstrCost(Opcode, S->getType(),
2022 S->getOperand(0)->getType(),
2026 auto ArithCost = [&](
unsigned Opcode,
unsigned NumRequired,
2027 unsigned MinIdx = 0,
2030 return NumRequired *
2031 TTI.getArithmeticInstrCost(Opcode, S->getType(),
CostKind);
2034 auto CmpSelCost = [&](
unsigned Opcode,
unsigned NumRequired,
unsigned MinIdx,
2037 Type *OpType = S->getType();
2038 return NumRequired *
TTI.getCmpSelInstrCost(
2043 switch (S->getSCEVType()) {
2051 Cost = CastCost(Instruction::PtrToAddr);
2054 Cost = CastCost(Instruction::PtrToInt);
2057 Cost = CastCost(Instruction::Trunc);
2060 Cost = CastCost(Instruction::ZExt);
2063 Cost = CastCost(Instruction::SExt);
2066 unsigned Opcode = Instruction::UDiv;
2068 if (SC->getAPInt().isPowerOf2())
2069 Opcode = Instruction::LShr;
2070 Cost = ArithCost(Opcode, 1);
2074 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
2085 unsigned OpCode = Instruction::Mul;
2086 if (S->getNumOperands() == 2)
2088 if (SC->getAPInt().isAllOnes())
2089 OpCode = Instruction::Sub;
2090 else if (SC->getAPInt().isPowerOf2())
2091 OpCode = Instruction::Shl;
2093 Cost = ArithCost(OpCode, S->getNumOperands() - 1);
2103 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
2104 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
2105 switch (S->getSCEVType()) {
2109 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
2110 Cost += ArithCost(Instruction::Or,
2111 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
2112 Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
2117 "Unhandled SCEV expression type?");
2124 unsigned NumRecurrences = S->getNumOperands() - 1;
2125 Cost +=
TTI.getCFInstrCost(Instruction::PHI,
CostKind) * NumRecurrences;
2127 TTI.getArithmeticInstrCost(Instruction::Add, S->getType(),
CostKind) *
2130 Worklist.
emplace_back(Instruction::PHI, 0, S->getOperand(0));
2132 for (
const SCEV *
Op : S->operands().drop_front())
2138 for (
auto &CostOp : Operations) {
2139 for (
auto SCEVOp :
enumerate(S->operands())) {
2141 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
2142 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
2149bool SCEVExpander::isHighCostExpansionHelper(
2157 const SCEV *S = WorkItem.
S;
2168 L->getHeader()->getParent()->hasMinSize()
2187 return Cost > Budget;
2208 SE.getAddExpr(S, SE.getConstant(S->
getType(), 1)), &At, L))
2223 "Nary expr should have more than 1 operand.");
2228 return Cost > Budget;
2232 "Polynomial should be at least linear");
2235 return Cost > Budget;
2244 switch (Pred->getKind()) {
2259 Value *Expr0 = expand(Pred->getLHS(), IP);
2260 Value *Expr1 = expand(Pred->getRHS(), IP);
2262 Builder.SetInsertPoint(IP);
2264 auto *
I = Builder.CreateICmp(InvPred, Expr0, Expr1,
"ident.check");
2271 "non-affine expression");
2275 const SCEV *ExitCount =
2276 SE.getPredicatedSymbolicMaxBackedgeTakenCount(AR->
getLoop(), Pred);
2284 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->
getType());
2285 unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2292 Builder.SetInsertPoint(
Loc);
2293 Value *TripCountVal = expand(ExitCount,
Loc);
2298 Value *StepValue = expand(Step,
Loc);
2299 Value *NegStepValue = expand(SE.getNegativeSCEV(Step),
Loc);
2300 Value *StartValue = expand(Start,
Loc);
2305 Builder.SetInsertPoint(
Loc);
2308 Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2318 auto ComputeEndCheck = [&]() ->
Value * {
2320 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2322 Value *
Mul = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow, Ty,
2323 {AbsStep, TruncTripCount},
2325 Value *MulV = Builder.CreateExtractValue(
Mul, 0,
"mul.result");
2326 Value *OfMul = Builder.CreateExtractValue(
Mul, 1,
"mul.overflow");
2329 bool NeedPosCheck = !SE.isKnownNegative(Step);
2330 bool NeedNegCheck = !SE.isKnownPositive(Step);
2333 Value *NegMulV = Builder.CreateNeg(MulV);
2335 Add = Builder.CreatePtrAdd(StartValue, MulV);
2337 Sub = Builder.CreatePtrAdd(StartValue, NegMulV);
2340 Add = Builder.CreateAdd(StartValue, MulV);
2342 Sub = Builder.CreateSub(StartValue, MulV);
2345 Value *EndCompareLT =
nullptr;
2346 Value *EndCompareGT =
nullptr;
2347 Value *EndCheck =
nullptr;
2349 EndCheck = EndCompareLT = Builder.CreateICmp(
2352 EndCheck = EndCompareGT = Builder.CreateICmp(
2354 if (NeedPosCheck && NeedNegCheck) {
2356 EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2358 return Builder.CreateOr(EndCheck, OfMul);
2360 Value *EndCheck = ComputeEndCheck();
2365 if (SrcBits > DstBits) {
2367 auto *BackedgeCheck =
2369 ConstantInt::get(
Loc->getContext(), MaxVal));
2370 BackedgeCheck = Builder.CreateAnd(
2373 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2382 Value *NSSWCheck =
nullptr, *NUSWCheck =
nullptr;
2392 if (NUSWCheck && NSSWCheck)
2393 return Builder.CreateOr(NUSWCheck, NSSWCheck);
2408 for (
const auto *Pred : Union->getPredicates()) {
2410 Builder.SetInsertPoint(IP);
2415 return Builder.CreateOr(Checks);
2418Value *SCEVExpander::fixupLCSSAFormFor(
Value *V) {
2420 if (!PreserveLCSSA || !DefI)
2426 if (!DefLoop || UseLoop == DefLoop || DefLoop->
contains(UseLoop))
2437 if (DefI->getType()->isIntegerTy())
2451 for (
PHINode *PN : InsertedPHIs)
2452 rememberInstruction(PN);
2453 for (
PHINode *PN : PHIsToRemove) {
2456 InsertedValues.erase(PN);
2457 InsertedPostIncValues.erase(PN);
2461 return User->getOperand(0);
2483struct SCEVFindUnsafe {
2484 ScalarEvolution &SE;
2486 bool IsUnsafe =
false;
2488 SCEVFindUnsafe(ScalarEvolution &SE,
bool CanonicalMode)
2489 : SE(SE), CanonicalMode(CanonicalMode) {}
2491 bool follow(
const SCEV *S) {
2502 if (!AR->getLoop()->getLoopPreheader() &&
2503 (!CanonicalMode || !AR->isAffine())) {
2510 bool isDone()
const {
return IsUnsafe; }
2515 SCEVFindUnsafe Search(SE, CanonicalMode);
2517 return !Search.IsUnsafe;
2548 for (
auto [
I, Flags] : Expander.OrigFlags)
2551 auto InsertedInstructions = Expander.getAllInsertedInstructions();
2554 InsertedInstructions);
2564 [&InsertedSet](
Value *U) {
2565 return InsertedSet.contains(cast<Instruction>(U));
2567 "removed instruction should only be used by instructions inserted "
2568 "during expansion");
2570 assert(!
I->getType()->isVoidTy() &&
2571 "inserted instruction should have non-void types");
2573 I->eraseFromParent();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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 GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static Expected< BitVector > expand(StringRef S, StringRef Original)
MachineInstr unsigned OpIdx
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 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)
static bool canReuseCastForPtrToAddr(const CastInst *CI, Type *Ty, const DataLayout &DL)
Return true if CI computes the same value as a ptrtoaddr of its pointer operand to Ty.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
LLVM_ABI 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_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
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 BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This is the base class for all instructions that perform data casts.
Type * getSrcTy() const
Return the source type, as a convenience.
static LLVM_ABI 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.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
static LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
@ ICMP_SLT
signed less than
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
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...
static LLVM_ABI 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 LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
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 GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags none()
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Class to represent integer types.
static LLVM_ABI 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 this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
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 ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
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...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This node represents a polynomial recurrence on the trip count of the specified loop.
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 an assumption that the expression LHS Pred RHS evaluates to true,...
LLVM_ABI Value * generateOverflowCheck(const SCEVAddRecExpr *AR, Instruction *Loc, bool Signed)
Generates code that evaluates if the AR expression will overflow.
LLVM_ABI 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.
LLVM_ABI 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...
LLVM_ABI 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...
LLVM_ABI unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
static LLVM_ABI void dropPoisonGeneratingAnnotationsAndReinfer(ScalarEvolution &SE, Instruction *I)
Drop poison-generating flags from I, then try re-infer via SCEV.
LLVM_ABI Value * expandUnionPredicate(const SCEVUnionPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
static LLVM_ABI CastInst * findReusableCastForPtrToAddr(Value *PtrOp, Type *Ty, const DataLayout &DL, function_ref< bool(const CastInst *)> Dominates)
Find an existing cast among PtrOp's users that computes the same value as a ptrtoaddr of PtrOp to Ty ...
LLVM_ABI bool hoistIVInc(Instruction *IncV, Instruction *InsertPos, bool RecomputePoisonFlags=false)
Utility for hoisting IncV (with all subexpressions requried for its computation) before InsertPos.
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
LLVM_ABI Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
static LLVM_ABI bool canReuseFlagsFromOriginalIVInc(PHINode *OrigPhi, PHINode *WidePhi, Instruction *OrigInc, Instruction *WideInc)
Return true if both increments directly increment the corresponding IV PHI nodes and have the same op...
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
LLVM_ABI Value * expandComparePredicate(const SCEVComparePredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM_ABI Value * expandWrapPredicate(const SCEVWrapPredicate *P, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM_ABI Instruction * getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale)
Return the induction variable increment's IV operand.
LLVM_ABI void eraseDeadInstructions(Value *Root)
Remove inserted instructions that are dead, e.g.
LLVM_ABI 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 class represents an assumption made using SCEV expressions which can be checked at run-time.
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 an assumption made on an AddRec expression.
This class represents an analyzed expression in the program.
SCEVNoWrapFlags NoWrapFlags
static constexpr auto FlagNUW
static constexpr auto FlagAnyWrap
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags Mask)
Convenient NoWrapFlags manipulation.
LLVM_ABI const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
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 canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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...
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.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI 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.
iterator_range< user_iterator > users()
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr bool any(E Val)
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
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)
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVPtrToAddrExpr, Op0_t > m_scev_PtrToAddr(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ CE
Windows NT (Windows on ARM)
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
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.
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.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
constexpr from_range_t from_range
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
auto pred_size(const MachineBasicBlock *BB)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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...
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI 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.
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
constexpr unsigned BitWidth
LLVM_ABI 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 pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
SmallPtrSet< const Loop *, 2 > PostIncLoopSet
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
SCEVUseT< const SCEV * > SCEVUse
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.
LLVM_ABI void apply(Instruction *I)
LLVM_ABI PoisonFlags(const Instruction *I)
struct for holding enough information to help calculate the cost of the given SCEV when expanded into...
const SCEV * S
The SCEV operand to be costed.
unsigned ParentOpcode
LLVM instruction opcode that uses the operand.
int OperandIdx
The use index of an expanded instruction.
SCEVNoWrapFlags getNoWrapFlags(SCEVNoWrapFlags Mask=SCEVNoWrapFlags::NoWrapMask) const
Return the no-wrap flags for this SCEVUse, which is the union of the use-specific flags and the under...