33#if LLVM_ENABLE_ABI_BREAKING_CHECKS
34#define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
36#define SCEV_DEBUG_WITH_TYPE(TYPE, X)
43 cl::desc(
"When performing SCEV expansion only if it is cheap to do, this "
44 "controls the budget that is considered cheap (default = 4)"));
58 NUW = OBO->hasNoUnsignedWrap();
59 NSW = OBO->hasNoSignedWrap();
62 Exact = PEO->isExact();
66 NNeg = PNI->hasNonNeg();
68 NUW = TI->hasNoUnsignedWrap();
69 NSW = TI->hasNoSignedWrap();
79 I->setHasNoUnsignedWrap(
NUW);
80 I->setHasNoSignedWrap(
NSW);
89 I->setHasNoUnsignedWrap(
NUW);
90 I->setHasNoSignedWrap(
NSW);
115 Value *Ret =
nullptr;
120 if (U->getType() != Ty)
129 if (IP->getParent() == CI->
getParent() && &*BIP != CI &&
139 SCEVInsertPointGuard Guard(Builder,
this);
140 Builder.SetInsertPoint(&*IP);
141 Ret = Builder.CreateCast(
Op, V, Ty,
V->getName());
157 if (
auto MaybeIP =
I->getInsertionPointAfterDef()) {
160 assert(SE.DT.dominates(
I, MustDominate) &&
161 "instruction must dominate the insertion point");
178 while (!WorkList.
empty()) {
187 InsertedValues.erase(
I);
188 InsertedPostIncValues.erase(
I);
190 I->eraseFromParent();
195SCEVExpander::GetOptimalInsertionPointForCastOf(
Value *V)
const {
214 "Expected the cast argument to be a global/constant");
215 return Builder.GetInsertBlock()
218 .getFirstInsertionPt();
226 assert((
Op == Instruction::BitCast ||
227 Op == Instruction::PtrToInt ||
228 Op == Instruction::IntToPtr) &&
229 "InsertNoopCastOfTo cannot perform non-noop casts!");
230 assert(SE.getTypeSizeInBits(
V->getType()) == SE.getTypeSizeInBits(Ty) &&
231 "InsertNoopCastOfTo cannot change sizes!");
238 if (
Op == Instruction::IntToPtr) {
240 if (DL.isNonIntegralPointerType(PtrTy))
244 if (
Op == Instruction::BitCast) {
245 if (
V->getType() == Ty)
253 if ((
Op == Instruction::PtrToInt ||
Op == Instruction::IntToPtr) &&
254 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(
V->getType())) {
256 if ((CI->
getOpcode() == Instruction::PtrToInt ||
257 CI->
getOpcode() == Instruction::IntToPtr) &&
258 SE.getTypeSizeInBits(CI->
getType()) ==
262 if ((
CE->getOpcode() == Instruction::PtrToInt ||
263 CE->getOpcode() == Instruction::IntToPtr) &&
264 SE.getTypeSizeInBits(
CE->getType()) ==
265 SE.getTypeSizeInBits(
CE->getOperand(0)->getType()))
266 return CE->getOperand(0);
274 return ReuseOrCreateCast(V, Ty,
Op, GetOptimalInsertionPointForCastOf(V));
282 bool IsSafeToHoist) {
290 unsigned ScanLimit = 6;
294 if (IP != BlockBegin) {
296 for (; ScanLimit; --IP, --ScanLimit) {
311 if (IP->getOpcode() == (
unsigned)Opcode && IP->getOperand(0) ==
LHS &&
312 IP->getOperand(1) ==
RHS && !canGenerateIncompatiblePoison(&*IP))
314 if (IP == BlockBegin)
break;
319 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
320 SCEVInsertPointGuard Guard(Builder,
this);
324 while (
const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
325 if (!
L->isLoopInvariant(
LHS) || !
L->isLoopInvariant(
RHS))
break;
327 if (!Preheader)
break;
335 Builder.SetCurrentDebugLocation(Loc);
340 if (LSRMode && !PostIncLoops.empty() &&
342 return !
L->contains(Builder.GetInsertBlock());
346 BO->setHasNoUnsignedWrap();
348 BO->setHasNoSignedWrap();
349 return Builder.Insert(BO);
351 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;
472 const Loop *
L =
nullptr;
477 return RelevantLoops[S] =
L;
482 return Pair.first->second = SE.LI.getLoopFor(
I->getParent());
498 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
500 bool operator()(std::pair<const Loop *, SCEVUse>
LHS,
501 std::pair<const Loop *, SCEVUse>
RHS)
const {
508 if (
LHS.first !=
RHS.first)
514 if (
LHS.second->isNonConstantNegative()) {
515 if (!
RHS.second->isNonConstantNegative())
517 }
else if (
RHS.second->isNonConstantNegative())
529 const SCEV *URemLHS =
nullptr;
530 const SCEV *URemRHS =
nullptr;
539 const SCEV *UMaxRHS =
nullptr;
540 const SCEVConstant *C1, *C2;
546 return Builder.CreateIntrinsic(Intrinsic::usub_sat, {S->getType()},
556 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
564 Value *Sum =
nullptr;
565 for (
auto I = OpsAndLoops.
begin(),
E = OpsAndLoops.
end();
I !=
E;) {
566 const Loop *CurLoop =
I->first;
575 assert(!
Op->getType()->isPointerTy() &&
"Only first op can be pointer");
580 for (;
I !=
E &&
I->first == CurLoop; ++
I) {
586 X = SE.getSCEV(
U->getValue());
589 Sum = expandAddToGEP(SE.getAddExpr(NewOps), Sum, S.
getNoWrapFlags());
590 }
else if (
Op->isNonConstantNegative()) {
592 Value *
W = expand(SE.getNegativeSCEV(
Op));
612 Type *Ty = S->getType();
614 const SCEVConstant *C1, *C2;
625 Value *Res = InsertBinop(Instruction::And,
LHS, ConstantInt::get(Ty, Mask),
633 for (
const SCEV *
Op :
reverse(S->operands()))
634 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(
Op),
Op));
641 Value *Prod =
nullptr;
642 auto I = OpsAndLoops.
begin();
647 const auto ExpandOpBinPowN = [
this, &
I, &OpsAndLoops]() {
657 while (
E != OpsAndLoops.
end() && *
I == *
E &&
Exponent != MaxExponent) {
661 assert(
Exponent > 0 &&
"Trying to calculate a zeroth exponent of operand?");
680 assert(Result &&
"Nothing was expanded?");
684 while (
I != OpsAndLoops.
end()) {
687 Prod = ExpandOpBinPowN();
688 }
else if (
I->second->isAllOnesValue()) {
695 Value *
W = ExpandOpBinPowN();
704 if (
RHS->logBase2() ==
RHS->getBitWidth() - 1)
706 Prod = InsertBinop(Instruction::Shl, Prod,
707 ConstantInt::get(Ty,
RHS->logBase2()), NWFlags,
722 const APInt &
RHS = SC->getAPInt();
723 if (
RHS.isPowerOf2())
724 return InsertBinop(Instruction::LShr,
LHS,
725 ConstantInt::get(SC->getType(),
RHS.logBase2()),
729 const SCEV *RHSExpr = S->getRHS();
732 bool GuaranteedNotPoison =
734 if (!GuaranteedNotPoison)
735 RHS = Builder.CreateFreeze(
RHS);
740 if (!SE.isKnownNonZero(RHSExpr) || !GuaranteedNotPoison)
741 RHS = Builder.CreateIntrinsic(
RHS->
getType(), Intrinsic::umax,
742 {RHS, ConstantInt::get(RHS->getType(), 1)});
745 SE.isKnownNonZero(S->getRHS()));
758 if (L == IVIncInsertLoop) {
761 if (!SE.DT.dominates(OInst, IVIncInsertPos))
775 return isNormalAddRecExprPHI(PN, IncV, L);
790 if (IncV == InsertPos)
797 case Instruction::Add:
798 case Instruction::Sub: {
800 if (!OInst || SE.DT.dominates(OInst, InsertPos))
804 case Instruction::BitCast:
806 case Instruction::GetElementPtr:
811 if (!SE.DT.dominates(OInst, InsertPos))
837 if (Builder.GetInsertPoint() == It)
838 Builder.SetInsertPoint(&*NewInsertPt);
839 for (
auto *InsertPtGuard : InsertPointGuards)
840 if (InsertPtGuard->GetInsertPoint() == It)
841 InsertPtGuard->SetInsertPoint(NewInsertPt);
848 bool RecomputePoisonFlags) {
853 I->dropPoisonGeneratingFlags();
855 if (
auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
857 BO->setHasNoUnsignedWrap(
859 BO->setHasNoSignedWrap(
864 if (SE.DT.dominates(IncV, InsertPos)) {
865 if (RecomputePoisonFlags)
866 FixupPoisonFlags(IncV);
876 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
888 if (SE.DT.dominates(IncV, InsertPos))
892 fixupInsertPoints(
I);
894 if (RecomputePoisonFlags)
917 (IVOper =
getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
934 IncV = Builder.CreatePtrAdd(PN, StepV,
"scevgep");
937 Builder.CreateSub(PN, StepV, Twine(IVName) +
".iv.next") :
938 Builder.CreateAdd(PN, StepV, Twine(IVName) +
".iv.next");
950 Type *PhiTy = Phi->getType();
964 if (Phi == Requested) {
987 const SCEV *ExtendAfterOp =
989 return ExtendAfterOp == OpAfterExtend;
1001 const SCEV *ExtendAfterOp =
1003 return ExtendAfterOp == OpAfterExtend;
1010SCEVExpander::getAddRecExprPHILiterally(
const SCEVAddRecExpr *Normalized,
1013 assert((!IVIncInsertLoop || IVIncInsertPos) &&
1014 "Uninitialized insert position");
1019 PHINode *AddRecPhiMatch =
nullptr;
1026 bool TryNonMatchingSCEV =
1028 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1030 for (PHINode &PN :
L->getHeader()->phis()) {
1031 if (!SE.isSCEVable(PN.
getType()))
1038 DebugType,
dbgs() <<
"One incomplete PHI is found: " << PN <<
"\n");
1046 bool IsMatchingSCEV = PhiSCEV == Normalized;
1050 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1061 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1064 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1069 if (IsMatchingSCEV) {
1073 AddRecPhiMatch = &PN;
1079 if ((!TruncTy || InvertStep) &&
1083 AddRecPhiMatch = &PN;
1085 TruncTy = Normalized->
getType();
1089 if (AddRecPhiMatch) {
1092 InsertedValues.insert(AddRecPhiMatch);
1094 rememberInstruction(IncV);
1096 ReusedValues.insert(AddRecPhiMatch);
1097 ReusedValues.insert(IncV);
1098 return AddRecPhiMatch;
1103 SCEVInsertPointGuard Guard(Builder,
this);
1113 PostIncLoops.
clear();
1116 assert(
L->getLoopPreheader() &&
1117 "Can't expand add recurrences without a loop preheader!");
1119 expand(Normalized->
getStart(),
L->getLoopPreheader()->getTerminator());
1136 Step = SE.getNegativeSCEV(Step);
1138 Value *StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1143 bool IncrementIsNUW = !useSubtract &&
IsIncrementNUW(SE, Normalized);
1144 bool IncrementIsNSW = !useSubtract &&
IsIncrementNSW(SE, Normalized);
1148 Builder.SetInsertPoint(Header->begin());
1150 Builder.CreatePHI(ExpandTy,
pred_size(Header), Twine(IVName) +
".iv");
1155 if (!
L->contains(Pred)) {
1164 IVIncInsertPos : Pred->getTerminator();
1165 Builder.SetInsertPoint(InsertPos);
1166 Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1179 PostIncLoops = SavedPostIncLoops;
1183 InsertedValues.
insert(PN);
1184 InsertedIVs.push_back(PN);
1190 const Loop *
L = S->getLoop();
1194 const SCEVAddRecExpr *Normalized = S;
1195 if (PostIncLoops.count(L)) {
1202 [[maybe_unused]]
const SCEV *
Start = Normalized->
getStart();
1204 assert(SE.properlyDominates(Start,
L->getHeader()) &&
1205 "Start does not properly dominate loop header");
1206 assert(SE.dominates(Step,
L->getHeader()) &&
"Step not dominate loop header");
1210 Type *TruncTy =
nullptr;
1211 bool InvertStep =
false;
1212 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1216 if (!PostIncLoops.count(L))
1221 assert(LatchBlock &&
"PostInc mode requires a unique loop latch!");
1229 if (!S->hasNoUnsignedWrap())
1230 I->setHasNoUnsignedWrap(
false);
1231 if (!S->hasNoSignedWrap())
1232 I->setHasNoSignedWrap(
false);
1240 &*Builder.GetInsertPoint())) {
1253 Step = SE.getNegativeSCEV(Step);
1257 SCEVInsertPointGuard Guard(Builder,
this);
1258 StepV = expand(Step,
L->getHeader()->getFirstInsertionPt());
1260 Result = expandIVInc(PN, StepV, L, useSubtract);
1267 if (TruncTy !=
Result->getType() || InvertStep)
1268 Result = fixupLCSSAFormFor(Result);
1270 if (TruncTy !=
Result->getType())
1271 Result = Builder.CreateTrunc(Result, TruncTy);
1275 Result = Builder.CreateSub(expand(Normalized->
getStart()), Result);
1281std::pair<PHINode *, const SCEV *>
1285 Type *STy = S->getType();
1286 const Loop *L = S->getLoop();
1289 return {
nullptr,
nullptr};
1293 auto CanReuse = [&](
const SCEV *ExitSCEV) ->
const SCEV * {
1296 const SCEV *Diff = SE.getMinusSCEV(S, ExitSCEV);
1306 for (
auto &PN : EB->
phis()) {
1307 if (!SE.isSCEVable(PN.
getType()))
1309 auto *ExitSCEV = SE.getSCEV(&PN);
1313 const SCEV *Diff =
nullptr;
1315 SE.getDataLayout().getAddressType(PhiTy) == STy) {
1316 const SCEV *AddrSCEV = SE.getPtrToAddrExpr(ExitSCEV);
1317 Diff = CanReuse(AddrSCEV);
1318 }
else if (STy == PhiTy) {
1319 Diff = CanReuse(ExitSCEV);
1325 "difference must be of integer type");
1329 return {
nullptr,
nullptr};
1337 Value *BaseV = fixupLCSSAFormFor(PN);
1339 if (S->getType()->isPointerTy())
1340 return Builder.CreatePtrAdd(BaseV, DiffV);
1341 BaseV = Builder.CreatePtrToAddr(BaseV);
1343 return Builder.CreateAdd(BaseV, DiffV);
1356 if (!CanonicalMode || (S->getNumOperands() > 2))
1357 return expandAddRecExprLiterally(S);
1359 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1360 const Loop *
L = S->getLoop();
1363 PHINode *CanonicalIV =
nullptr;
1364 if (PHINode *PN =
L->getCanonicalInductionVariable())
1365 if (SE.getTypeSizeInBits(PN->
getType()) >= SE.getTypeSizeInBits(Ty))
1371 SE.getTypeSizeInBits(CanonicalIV->
getType()) > SE.getTypeSizeInBits(Ty) &&
1372 !S->getType()->isPointerTy()) {
1374 for (
unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1375 NewOps[i] = SE.getAnyExtendExpr(S->getOperand(i), CanonicalIV->
getType());
1380 &*Builder.GetInsertPoint())
1381 : Builder.GetInsertPoint();
1382 V = expand(SE.getTruncateExpr(SE.getUnknown(V), Ty), NewInsertPt);
1388 if (
Value *V = tryToReuseLCSSAPhi(S))
1393 Value *StartV = expand(SE.getPointerBase(S));
1394 return expandAddToGEP(SE.removePointerBase(S), StartV,
1399 if (!S->getStart()->isZero()) {
1400 const SCEV *Rest = SE.getAddRecExpr(SE.getZero(Ty), S->getOperand(1), L,
1407 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1408 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1409 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1420 rememberInstruction(CanonicalIV);
1422 SmallPtrSet<BasicBlock *, 4> PredSeen;
1423 Constant *One = ConstantInt::get(Ty, 1);
1426 if (!PredSeen.
insert(HP).second) {
1433 if (
L->contains(HP)) {
1440 rememberInstruction(
Add);
1449 return expand(SE.getMulExpr(SE.getUnknown(CanonicalIV), S->getOperand(1)));
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 Type *Ty = S->getType();
1505 Value *PtrOp = expand(PtrToAddr->getOperand());
1508 for (User *U : PtrOp->
users()) {
1510 if (CI && CI->
getType() == Ty &&
1511 CI->
getOpcode() == CastInst::PtrToInt && &*BIP != CI &&
1512 SE.DT.dominates(CI, &*BIP))
1518 Value *
V = expand(S->getOperand());
1519 return Builder.CreateTrunc(V, S->getType());
1524 Value *
V = expand(S->getOperand());
1525 return Builder.CreateZExt(V, S->getType(),
"",
1526 SE.isKnownNonNegative(S->getOperand()));
1531 Value *
V = expand(S->getOperand());
1532 return Builder.CreateSExt(V, S->getType());
1537 bool IsSequential) {
1538 bool PrevSafeMode = SafeUDivMode;
1539 SafeUDivMode |= IsSequential;
1540 Value *
LHS = expand(S->getOperand(S->getNumOperands() - 1));
1543 LHS = Builder.CreateFreeze(
LHS);
1544 for (
int i = S->getNumOperands() - 2; i >= 0; --i) {
1545 SafeUDivMode = (IsSequential && i != 0) || PrevSafeMode;
1546 Value *
RHS = expand(S->getOperand(i));
1547 if (IsSequential && i != 0)
1548 RHS = Builder.CreateFreeze(
RHS);
1551 Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {
LHS,
RHS},
1556 Sel = Builder.CreateSelectWithUnknownProfile(ICmp,
LHS,
RHS,
1557 "scev-expander", Name);
1561 SafeUDivMode = PrevSafeMode;
1566 return expandMinMaxExpr(S, Intrinsic::smax,
"smax");
1570 return expandMinMaxExpr(S, Intrinsic::umax,
"umax");
1574 return expandMinMaxExpr(S, Intrinsic::smin,
"smin");
1578 return expandMinMaxExpr(S, Intrinsic::umin,
"umin");
1581Value *SCEVExpander::visitSequentialUMinExpr(
1583 return expandMinMaxExpr(S, Intrinsic::umin,
"umin",
1588 return Builder.CreateVScale(S->getType());
1599 Value *V = expand(SH);
1601 if (Ty && Ty != V->getType()) {
1602 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->
getType()) &&
1603 "non-trivial casts should be done with the SCEVs directly!");
1604 V = InsertNoopCastOfTo(V, Ty);
1609Value *SCEVExpander::FindValueInExprValueMap(
1621 for (
Value *V : SE.getSCEVValues(S)) {
1638 DropPoisonGeneratingInsts.
clear();
1643Value *SCEVExpander::findExistingExpansionAndDropPoisonFlags(
1645 SmallVector<Instruction *> DropPoisonGeneratingInsts;
1646 Value *
V = FindValueInExprValueMap(S, InsertPt, DropPoisonGeneratingInsts);
1649 for (Instruction *
I : DropPoisonGeneratingInsts) {
1670 auto SafeToHoist = [](
const SCEV *S) {
1675 return SC->getValue()->isZero();
1685 if (SafeToHoist(S)) {
1686 for (
Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1687 L =
L->getParentLoop()) {
1688 if (SE.isLoopInvariant(S, L)) {
1690 if (BasicBlock *Preheader =
L->getLoopPreheader()) {
1696 InsertPt =
L->getHeader()->getFirstInsertionPt();
1702 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1703 InsertPt =
L->getHeader()->getFirstInsertionPt();
1705 while (InsertPt != Builder.GetInsertPoint() &&
1707 InsertPt = std::next(InsertPt);
1715 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1716 if (
I != InsertedExpressions.end())
1719 SCEVInsertPointGuard Guard(Builder,
this);
1720 Builder.SetInsertPoint(InsertPt);
1723 Value *
V = findExistingExpansionAndDropPoisonFlags(S, &*InsertPt);
1725 if (!V && InsertPt != OrigInsertPt && PostIncLoops.empty()) {
1729 V = findExistingExpansionAndDropPoisonFlags(S, &*OrigInsertPt);
1731 CacheAt = OrigInsertPt;
1735 V = fixupLCSSAFormFor(V);
1743 InsertedExpressions[std::make_pair(S, &*CacheAt)] =
V;
1747void SCEVExpander::rememberInstruction(
Value *
I) {
1748 auto DoInsert = [
this](
Value *
V) {
1749 if (!PostIncLoops.empty())
1750 InsertedPostIncValues.insert(V);
1752 InsertedValues.insert(V);
1759 OrigFlags.try_emplace(
I, PoisonFlags(
I));
1764 I->dropPoisonGeneratingAnnotations();
1768 if (SE.isSCEVable(OBO->getType()))
1769 if (
auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
1771 BO->setHasNoUnsignedWrap(
1773 BO->setHasNoSignedWrap(
1777 auto *Src = NNI->getOperand(0);
1782 NNI->setNonNeg(
true);
1786void SCEVExpander::replaceCongruentIVInc(
1797 if (!OrigInc || !IsomorphicInc)
1803 if (OrigPhi->
getType() == Phi->getType()) {
1804 bool Chained = ChainedPhis.contains(Phi);
1805 if (!(Chained || isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) &&
1806 (Chained || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1821 const SCEV *TruncExpr =
1822 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->
getType());
1823 if (OrigInc == IsomorphicInc || TruncExpr != SE.getSCEV(IsomorphicInc) ||
1824 !SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc))
1827 bool BothHaveNUW =
false;
1828 bool BothHaveNSW =
false;
1831 if (OBOIncV && OBOIsomorphic) {
1833 OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap();
1835 OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap();
1848 "Should only replace an increment with a wider one.");
1849 if (BothHaveNUW || BothHaveNSW) {
1855 dbgs() <<
"INDVARS: Eliminated congruent iv.inc: "
1856 << *IsomorphicInc <<
'\n');
1857 Value *NewInc = OrigInc;
1861 IP = PN->
getParent()->getFirstInsertionPt();
1866 Builder.SetCurrentDebugLocation(IsomorphicInc->
getDebugLoc());
1868 Builder.CreateTruncOrBitCast(OrigInc, IsomorphicInc->
getType(), IVName);
1893 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1894 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1895 return RHS->getType()->getPrimitiveSizeInBits().getFixedValue() <
1896 LHS->getType()->getPrimitiveSizeInBits().getFixedValue();
1899 unsigned NumElim = 0;
1907 if (!SE.isSCEVable(PN->
getType()))
1912 return Const->getValue();
1917 if (
Value *V = SimplifyPHINode(Phi)) {
1918 if (V->getType() != Phi->getType())
1920 SE.forgetValue(Phi);
1921 Phi->replaceAllUsesWith(V);
1925 dbgs() <<
"INDVARS: Eliminated constant iv: " << *Phi
1930 if (!SE.isSCEVable(Phi->getType()))
1933 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1936 if (Phi->getType()->isIntegerTy() &&
TTI &&
1937 TTI->isTruncateFree(Phi->getType(), Phis.
back()->getType())) {
1941 const SCEV *PhiExpr = SE.getSCEV(Phi);
1945 const SCEV *TruncExpr =
1946 SE.getTruncateExpr(PhiExpr, Phis.
back()->getType());
1947 ExprToIVMap[TruncExpr] = Phi;
1958 replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts);
1960 dbgs() <<
"INDVARS: Eliminated congruent iv: " << *Phi
1963 DebugType,
dbgs() <<
"INDVARS: Original iv: " << *OrigPhiRef <<
'\n');
1965 Value *NewIV = OrigPhiRef;
1966 if (OrigPhiRef->
getType() != Phi->getType()) {
1967 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1968 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1969 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1971 Phi->replaceAllUsesWith(NewIV);
1983 L->getExitingBlocks(ExitingBlocks);
1990 if (!
match(BB->getTerminator(),
1995 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1998 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
2007 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) !=
nullptr;
2018 struct OperationIndices {
2019 OperationIndices(
unsigned Opc,
size_t min,
size_t max) :
2020 Opcode(
Opc), MinIdx(
min), MaxIdx(
max) { }
2033 return TTI.getCastInstrCost(Opcode, S->getType(),
2034 S->getOperand(0)->getType(),
2038 auto ArithCost = [&](
unsigned Opcode,
unsigned NumRequired,
2039 unsigned MinIdx = 0,
2042 return NumRequired *
2043 TTI.getArithmeticInstrCost(Opcode, S->getType(),
CostKind);
2046 auto CmpSelCost = [&](
unsigned Opcode,
unsigned NumRequired,
unsigned MinIdx,
2049 Type *OpType = S->getType();
2050 return NumRequired *
TTI.getCmpSelInstrCost(
2055 switch (S->getSCEVType()) {
2063 Cost = CastCost(Instruction::PtrToAddr);
2066 Cost = CastCost(Instruction::Trunc);
2069 Cost = CastCost(Instruction::ZExt);
2072 Cost = CastCost(Instruction::SExt);
2075 unsigned Opcode = Instruction::UDiv;
2077 if (SC->getAPInt().isPowerOf2())
2078 Opcode = Instruction::LShr;
2079 Cost = ArithCost(Opcode, 1);
2083 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
2094 unsigned OpCode = Instruction::Mul;
2095 if (S->getNumOperands() == 2)
2097 if (SC->getAPInt().isAllOnes())
2098 OpCode = Instruction::Sub;
2099 else if (SC->getAPInt().isPowerOf2())
2100 OpCode = Instruction::Shl;
2102 Cost = ArithCost(OpCode, S->getNumOperands() - 1);
2112 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
2113 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
2114 switch (S->getSCEVType()) {
2118 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
2119 Cost += ArithCost(Instruction::Or,
2120 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
2121 Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
2126 "Unhandled SCEV expression type?");
2133 unsigned NumRecurrences = S->getNumOperands() - 1;
2134 Cost +=
TTI.getCFInstrCost(Instruction::PHI,
CostKind) * NumRecurrences;
2136 TTI.getArithmeticInstrCost(Instruction::Add, S->getType(),
CostKind) *
2139 Worklist.
emplace_back(Instruction::PHI, 0, S->getOperand(0));
2141 for (
const SCEV *
Op : S->operands().drop_front())
2147 for (
auto &CostOp : Operations) {
2148 for (
auto SCEVOp :
enumerate(S->operands())) {
2150 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
2151 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
2152 Worklist.
emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
2158bool SCEVExpander::isHighCostExpansionHelper(
2166 const SCEV *S = WorkItem.
S;
2177 L->getHeader()->getParent()->hasMinSize()
2196 return Cost > Budget;
2216 SE.getAddExpr(S, SE.getConstant(S->
getType(), 1)), &At, L))
2231 "Nary expr should have more than 1 operand.");
2236 return Cost > Budget;
2240 "Polynomial should be at least linear");
2243 return Cost > Budget;
2252 switch (Pred->getKind()) {
2267 Value *Expr0 = expand(Pred->getLHS(), IP);
2268 Value *Expr1 = expand(Pred->getRHS(), IP);
2270 Builder.SetInsertPoint(IP);
2272 auto *
I = Builder.CreateICmp(InvPred, Expr0, Expr1,
"ident.check");
2279 "non-affine expression");
2283 const SCEV *ExitCount =
2284 SE.getPredicatedSymbolicMaxBackedgeTakenCount(AR->
getLoop(), Pred);
2292 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->
getType());
2293 unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2300 Builder.SetInsertPoint(
Loc);
2301 Value *TripCountVal = expand(ExitCount,
Loc);
2306 Value *StepValue = expand(Step,
Loc);
2307 Value *NegStepValue = expand(SE.getNegativeSCEV(Step),
Loc);
2308 Value *StartValue = expand(Start,
Loc);
2313 Builder.SetInsertPoint(
Loc);
2316 Value *AbsStep = Builder.CreateSelectWithUnknownProfile(
2317 StepCompare, NegStepValue, StepValue,
"scev-expander");
2327 auto ComputeEndCheck = [&]() ->
Value * {
2329 Value *MulV, *OfMul;
2330 auto Key = std::make_tuple(TripCountVal, AbsStep,
Loc);
2331 auto I = InsertedOverflowChecks.find(
Key);
2332 if (
I != InsertedOverflowChecks.end()) {
2333 MulV =
I->second.first;
2334 OfMul =
I->second.second;
2337 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2338 Value *
Mul = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow, Ty,
2339 {AbsStep, TruncTripCount},
2341 MulV = Builder.CreateExtractValue(
Mul, 0,
"mul.result");
2342 OfMul = Builder.CreateExtractValue(
Mul, 1,
"mul.overflow");
2345 InsertedOverflowChecks[
Key] = {MulV, OfMul};
2349 bool NeedPosCheck = !SE.isKnownNegative(Step);
2350 bool NeedNegCheck = !SE.isKnownPositive(Step);
2353 Value *NegMulV = Builder.CreateNeg(MulV);
2355 Add = Builder.CreatePtrAdd(StartValue, MulV);
2357 Sub = Builder.CreatePtrAdd(StartValue, NegMulV);
2360 Add = Builder.CreateAdd(StartValue, MulV);
2362 Sub = Builder.CreateSub(StartValue, MulV);
2365 Value *EndCompareLT =
nullptr;
2366 Value *EndCompareGT =
nullptr;
2367 Value *EndCheck =
nullptr;
2369 EndCheck = EndCompareLT = Builder.CreateICmp(
2372 EndCheck = EndCompareGT = Builder.CreateICmp(
2374 if (NeedPosCheck && NeedNegCheck) {
2376 EndCheck = Builder.CreateSelectWithUnknownProfile(
2377 StepCompare, EndCompareGT, EndCompareLT,
"scev-expander");
2379 return Builder.CreateOr(EndCheck, OfMul);
2381 Value *EndCheck = ComputeEndCheck();
2386 if (SrcBits > DstBits) {
2388 auto *BackedgeCheck =
2390 ConstantInt::get(
Loc->getContext(), MaxVal));
2391 BackedgeCheck = Builder.CreateAnd(
2394 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2403 Value *NSSWCheck =
nullptr, *NUSWCheck =
nullptr;
2413 if (NUSWCheck && NSSWCheck)
2414 return Builder.CreateOr(NUSWCheck, NSSWCheck);
2429 for (
const auto *Pred : Union->getPredicates()) {
2431 Builder.SetInsertPoint(IP);
2436 return Builder.CreateOr(Checks);
2439Value *SCEVExpander::fixupLCSSAFormFor(
Value *V) {
2441 if (!PreserveLCSSA || !DefI)
2447 if (!DefLoop || UseLoop == DefLoop || DefLoop->
contains(UseLoop))
2458 if (DefI->getType()->isIntegerTy())
2472 for (
PHINode *PN : InsertedPHIs)
2473 rememberInstruction(PN);
2474 for (
PHINode *PN : PHIsToRemove) {
2477 InsertedValues.erase(PN);
2478 InsertedPostIncValues.erase(PN);
2482 return User->getOperand(0);
2504struct SCEVFindUnsafe {
2505 ScalarEvolution &SE;
2507 bool IsUnsafe =
false;
2509 SCEVFindUnsafe(ScalarEvolution &SE,
bool CanonicalMode)
2510 : SE(SE), CanonicalMode(CanonicalMode) {}
2512 bool follow(
const SCEV *S) {
2523 if (!AR->getLoop()->getLoopPreheader() &&
2524 (!CanonicalMode || !AR->isAffine())) {
2531 bool isDone()
const {
return IsUnsafe; }
2536 SCEVFindUnsafe Search(SE, CanonicalMode);
2538 return !Search.IsUnsafe;
2569 for (
auto [
I, Flags] : Expander.OrigFlags)
2572 auto InsertedInstructions = Expander.getAllInsertedInstructions();
2575 InsertedInstructions);
2585 [&InsertedSet](
Value *U) {
2586 return InsertedSet.contains(cast<Instruction>(U));
2588 "removed instruction should only be used by instructions inserted "
2589 "during expansion");
2591 assert(!
I->getType()->isVoidTy() &&
2592 "inserted instruction should have non-void types");
2594 I->eraseFromParent();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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)
This file contains the declarations for profiling metadata utility functions.
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 scope_exit class, which executes user-defined cleanup logic at scope exit.
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.
unsigned logBase2() const
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
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(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object 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,...
ConstantInt * getValue() const
const APInt & getAPInt() const
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.
static LLVM_ABI std::pair< PHINode *, const SCEV * > findReusableLCSSAPhi(ScalarEvolution &SE, SCEVUseT< const SCEVAddRecExpr * > S, const BasicBlock *InsertBB)
Find a phi in the exit block of S's loop, which must dominate InsertBB, such that S can be expanded i...
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.
static constexpr auto FlagNUW
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.
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
The main scalar evolution driver.
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
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, SCEVFlags Flags=SCEV::FlagNone, 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.
static SCEVFlags clearFlags(SCEVFlags Flags, SCEVFlags OffFlags)
static SCEVFlags maskFlags(SCEVFlags Flags, SCEVFlags Mask)
Convenient SCEVFlags manipulation.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
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)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ 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)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVUMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_UMax(const Op0_t &Op0, const Op1_t &Op1)
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.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
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_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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.
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
SCEVFlags
SCEVFlags are bitfield indices into SCEV's SubclassData.
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.
SCEVFlags getNoWrapFlags(SCEVFlags Mask=SCEVFlags::FlagsNoWrapMask) const
Return the flags for this SCEVUse, which is the union of the use-specific flags and the underlying SC...