55 if (U->getType() == Ty)
56 if (
CastInst *CI = dyn_cast<CastInst>(U))
57 if (CI->getOpcode() ==
Op) {
66 CI->replaceAllUsesWith(Ret);
80 assert(SE.DT.dominates(Ret, &*BIP));
82 rememberInstruction(Ret);
89 if (
auto *II = dyn_cast<InvokeInst>(I))
90 IP = II->getNormalDest()->begin();
92 while (isa<PHINode>(IP))
95 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
97 }
else if (isa<CatchSwitchInst>(IP)) {
100 assert(!IP->isEHPad() &&
"unexpected eh pad!");
111 assert((Op == Instruction::BitCast ||
112 Op == Instruction::PtrToInt ||
113 Op == Instruction::IntToPtr) &&
114 "InsertNoopCastOfTo cannot perform non-noop casts!");
115 assert(SE.getTypeSizeInBits(V->
getType()) == SE.getTypeSizeInBits(Ty) &&
116 "InsertNoopCastOfTo cannot change sizes!");
119 if (Op == Instruction::BitCast) {
122 if (
CastInst *CI = dyn_cast<CastInst>(V)) {
123 if (CI->getOperand(0)->getType() == Ty)
124 return CI->getOperand(0);
128 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
129 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->
getType())) {
130 if (
CastInst *CI = dyn_cast<CastInst>(V))
131 if ((CI->getOpcode() == Instruction::PtrToInt ||
132 CI->getOpcode() == Instruction::IntToPtr) &&
133 SE.getTypeSizeInBits(CI->getType()) ==
134 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
135 return CI->getOperand(0);
137 if ((CE->getOpcode() == Instruction::PtrToInt ||
138 CE->getOpcode() == Instruction::IntToPtr) &&
139 SE.getTypeSizeInBits(CE->getType()) ==
140 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
141 return CE->getOperand(0);
150 if (
Argument *A = dyn_cast<Argument>(V)) {
152 while ((isa<BitCastInst>(IP) &&
153 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
154 cast<BitCastInst>(IP)->getOperand(0) != A) ||
155 isa<DbgInfoIntrinsic>(IP))
157 return ReuseOrCreateCast(A, Ty, Op, IP);
163 return ReuseOrCreateCast(I, Ty, Op, IP);
173 if (
Constant *CLHS = dyn_cast<Constant>(LHS))
174 if (
Constant *CRHS = dyn_cast<Constant>(RHS))
178 unsigned ScanLimit = 6;
182 if (IP != BlockBegin) {
184 for (; ScanLimit; --IP, --ScanLimit) {
187 if (isa<DbgInfoIntrinsic>(IP))
190 auto canGenerateIncompatiblePoison = [&Flags](
Instruction *
I) {
192 if (isa<OverflowingBinaryOperator>(
I)) {
200 if (isa<PossiblyExactOperator>(
I) &&
I->isExact())
204 if (IP->getOpcode() == (
unsigned)Opcode && IP->getOperand(0) == LHS &&
205 IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
207 if (IP == BlockBegin)
break;
212 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
213 SCEVInsertPointGuard Guard(Builder,
this);
217 while (
const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
218 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS))
break;
219 BasicBlock *Preheader = L->getLoopPreheader();
220 if (!Preheader)
break;
228 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
234 rememberInstruction(BO);
280 if (
const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
284 if (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(M->getOperand(0)))
285 if (!
C->getAPInt().srem(FC->
getAPInt())) {
295 const SCEV *Step = A->getStepRecurrence(SE);
301 const SCEV *Start = A->getStart();
319 unsigned NumAddRecs = 0;
320 for (
unsigned i = Ops.
size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
326 const SCEV *Sum = NoAddRecs.empty() ?
334 else if (!Sum->isZero())
337 Ops.
append(AddRecs.begin(), AddRecs.end());
350 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i)
351 while (
const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
352 const SCEV *Start = A->getStart();
353 if (Start->
isZero())
break;
356 A->getStepRecurrence(SE),
362 e +=
Add->getNumOperands();
367 if (!AddRecs.
empty()) {
402 Value *SCEVExpander::expandAddToGEP(
const SCEV *
const *op_begin,
403 const SCEV *
const *op_end,
408 Type *ElTy = OriginalElTy;
411 bool AnyNonZeroIndices =
false;
417 Type *IntIdxTy = DL.getIndexType(PTy);
429 const SCEV *ElSize = SE.getSizeOfExpr(IntIdxTy, ElTy);
432 for (
const SCEV *Op : Ops) {
433 const SCEV *Remainder = SE.getConstant(Ty, 0);
439 AnyNonZeroIndices =
true;
447 if (!ScaledOps.
empty()) {
460 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
464 while (
StructType *STy = dyn_cast<StructType>(ElTy)) {
465 bool FoundFieldNo =
false;
467 if (STy->getNumElements() == 0)
break;
473 if (SE.getTypeSizeInBits(
C->
getType()) <= 64) {
475 uint64_t FullOffset =
C->getValue()->getZExtValue();
480 ElTy = STy->getTypeAtIndex(ElIdx);
483 AnyNonZeroIndices =
true;
491 ElTy = STy->getTypeAtIndex(0u);
497 if (
ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
498 ElTy = ATy->getElementType();
506 if (!AnyNonZeroIndices) {
508 V = InsertNoopCastOfTo(V,
511 assert(!isa<Instruction>(V) ||
512 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
515 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
518 if (
Constant *CLHS = dyn_cast<Constant>(V))
519 if (
Constant *CRHS = dyn_cast<Constant>(Idx))
524 unsigned ScanLimit = 6;
528 if (IP != BlockBegin) {
530 for (; ScanLimit; --IP, --ScanLimit) {
533 if (isa<DbgInfoIntrinsic>(IP))
535 if (IP->getOpcode() == Instruction::GetElementPtr &&
536 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
538 if (IP == BlockBegin)
break;
543 SCEVInsertPointGuard Guard(Builder,
this);
546 while (
const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
547 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx))
break;
548 BasicBlock *Preheader = L->getLoopPreheader();
549 if (!Preheader)
break;
556 Value *
GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx,
"uglygep");
557 rememberInstruction(GEP);
563 SCEVInsertPointGuard Guard(Builder,
this);
566 while (
const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
567 if (!L->isLoopInvariant(V))
break;
569 bool AnyIndexNotLoopInvariant =
any_of(
570 GepIndices, [L](
Value *Op) {
return !L->isLoopInvariant(Op); });
572 if (AnyIndexNotLoopInvariant)
575 BasicBlock *Preheader = L->getLoopPreheader();
576 if (!Preheader)
break;
587 Casted = InsertNoopCastOfTo(Casted, PTy);
588 Value *
GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices,
"scevgep");
590 rememberInstruction(GEP);
593 return expand(SE.getAddExpr(Ops));
598 const SCEV *
const Ops[1] = {Op};
599 return expandAddToGEP(Ops, Ops + 1, PTy, Ty, V);
618 const Loop *SCEVExpander::getRelevantLoop(
const SCEV *S) {
620 auto Pair = RelevantLoops.insert(std::make_pair(S,
nullptr));
622 return Pair.first->second;
624 if (isa<SCEVConstant>(S))
627 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
628 if (
const Instruction *
I = dyn_cast<Instruction>(U->getValue()))
629 return Pair.first->second = SE.LI.getLoopFor(
I->getParent());
634 const Loop *L =
nullptr;
637 for (
const SCEV *Op :
N->operands())
639 return RelevantLoops[
N] = L;
643 return RelevantLoops[
C] = Result;
647 getRelevantLoop(
D->getLHS()), getRelevantLoop(
D->getRHS()), SE.DT);
648 return RelevantLoops[
D] = Result;
661 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
662 std::pair<const Loop *, const SCEV *> RHS)
const {
664 if (LHS.second->getType()->isPointerTy() !=
665 RHS.second->getType()->isPointerTy())
666 return LHS.second->getType()->isPointerTy();
669 if (LHS.first != RHS.first)
675 if (LHS.second->isNonConstantNegative()) {
676 if (!RHS.second->isNonConstantNegative())
678 }
else if (RHS.second->isNonConstantNegative())
696 for (std::reverse_iterator<SCEVAddExpr::op_iterator>
I(S->
op_end()),
698 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(*
I), *
I));
706 Value *Sum =
nullptr;
707 for (
auto I = OpsAndLoops.
begin(),
E = OpsAndLoops.
end();
I !=
E;) {
708 const Loop *CurLoop =
I->first;
709 const SCEV *Op =
I->second;
718 for (;
I !=
E &&
I->first == CurLoop; ++
I) {
721 const SCEV *
X =
I->second;
722 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
723 if (!isa<Instruction>(U->getValue()))
724 X = SE.getSCEV(U->getValue());
727 Sum = expandAddToGEP(NewOps.
begin(), NewOps.
end(), PTy, Ty, Sum);
733 NewOps.
push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
735 for (++
I;
I !=
E &&
I->first == CurLoop; ++
I)
737 Sum = expandAddToGEP(NewOps.
begin(), NewOps.
end(), PTy, Ty,
expand(Op));
740 Value *
W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
741 Sum = InsertNoopCastOfTo(Sum, Ty);
747 Value *
W = expandCodeFor(Op, Ty);
748 Sum = InsertNoopCastOfTo(Sum, Ty);
750 if (isa<Constant>(Sum))
std::swap(Sum, W);
766 for (std::reverse_iterator<SCEVMulExpr::op_iterator>
I(S->
op_end()),
768 OpsAndLoops.
push_back(std::make_pair(getRelevantLoop(*
I), *
I));
775 Value *Prod =
nullptr;
776 auto I = OpsAndLoops.
begin();
781 const auto ExpandOpBinPowN = [
this, &
I, &OpsAndLoops, &Ty]() {
791 while (
E != OpsAndLoops.end() && *
I == *
E && Exponent != MaxExponent) {
795 assert(Exponent > 0 &&
"Trying to calculate a zeroth exponent of operand?");
799 Value *
P = expandCodeFor(
I->second, Ty);
800 Value *Result =
nullptr;
803 for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
806 if (Exponent & BinExp)
807 Result = Result ? InsertBinop(Instruction::Mul, Result, P,
814 assert(Result &&
"Nothing was expanded?");
818 while (
I != OpsAndLoops.end()) {
821 Prod = ExpandOpBinPowN();
822 }
else if (
I->second->isAllOnesValue()) {
824 Prod = InsertNoopCastOfTo(Prod, Ty);
830 Value *
W = ExpandOpBinPowN();
831 Prod = InsertNoopCastOfTo(Prod, Ty);
833 if (isa<Constant>(Prod))
std::swap(Prod, W);
842 Prod = InsertBinop(Instruction::Shl, Prod,
846 Prod = InsertBinop(Instruction::Mul, Prod, W, S->
getNoWrapFlags(),
860 const APInt &RHS =
SC->getAPInt();
862 return InsertBinop(Instruction::LShr, LHS,
869 SE.isKnownNonZero(S->
getRHS()));
877 while (
const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
878 Base = A->getStart();
881 A->getStepRecurrence(SE),
885 if (
const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
886 Base = A->getOperand(A->getNumOperands()-1);
888 NewAddOps.
back() = Rest;
899 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
904 if (L == IVIncInsertLoop) {
906 OE = IncV->
op_end(); OI != OE; ++OI)
907 if (
Instruction *OInst = dyn_cast<Instruction>(OI))
908 if (!SE.DT.dominates(OInst, IVIncInsertPos))
922 return isNormalAddRecExprPHI(PN, IncV, L);
937 if (IncV == InsertPos)
945 case Instruction::Sub: {
947 if (!OInst || SE.DT.dominates(OInst, InsertPos))
948 return dyn_cast<Instruction>(IncV->
getOperand(0));
951 case Instruction::BitCast:
953 case Instruction::GetElementPtr:
955 if (isa<Constant>(*
I))
958 if (!SE.DT.dominates(OInst, InsertPos))
971 unsigned AS = cast<PointerType>(IncV->
getType())->getAddressSpace();
991 if (Builder.GetInsertPoint() == It)
992 Builder.SetInsertPoint(&*NewInsertPt);
993 for (
auto *InsertPtGuard : InsertPointGuards)
994 if (InsertPtGuard->GetInsertPoint() == It)
995 InsertPtGuard->SetInsertPoint(NewInsertPt);
1002 if (SE.DT.dominates(IncV, InsertPos))
1007 if (isa<PHINode>(InsertPos) ||
1011 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
1017 Instruction *Oper = getIVIncOperand(IncV, InsertPos,
true);
1023 if (SE.DT.dominates(IncV, InsertPos))
1026 for (
auto I = IVIncs.
rbegin(),
E = IVIncs.
rend(); I !=
E; ++
I) {
1027 fixupInsertPoints(*I);
1028 (*I)->moveBefore(InsertPos);
1058 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1061 if (!isa<ConstantInt>(StepV))
1064 IncV = expandAddToGEP(SE.getSCEV(StepV), GEPPtrTy, IntTy, PN);
1066 IncV = Builder.CreateBitCast(IncV, PN->
getType());
1067 rememberInstruction(IncV);
1070 IncV = useSubtract ?
1071 Builder.CreateSub(PN, StepV,
Twine(IVName) +
".iv.next") :
1072 Builder.CreateAdd(PN, StepV,
Twine(IVName) +
".iv.next");
1073 rememberInstruction(IncV);
1087 fixupInsertPoints(InstToHoist);
1090 InstToHoist = cast<Instruction>(InstToHoist->
getOperand(0));
1091 }
while (InstToHoist != LoopPhi);
1112 if (Phi == Requested) {
1128 if (!isa<IntegerType>(AR->
getType()))
1136 const SCEV *ExtendAfterOp =
1138 return ExtendAfterOp == OpAfterExtend;
1142 if (!isa<IntegerType>(AR->
getType()))
1150 const SCEV *ExtendAfterOp =
1152 return ExtendAfterOp == OpAfterExtend;
1159 SCEVExpander::getAddRecExprPHILiterally(
const SCEVAddRecExpr *Normalized,
1165 assert((!IVIncInsertLoop||IVIncInsertPos) &&
"Uninitialized insert position");
1170 PHINode *AddRecPhiMatch =
nullptr;
1177 bool TryNonMatchingSCEV =
1179 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1182 if (!SE.isSCEVable(PN.
getType()))
1189 bool IsMatchingSCEV = PhiSCEV == Normalized;
1193 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1204 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1206 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1209 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1214 if (IsMatchingSCEV) {
1218 AddRecPhiMatch = &PN;
1224 if ((!TruncTy || InvertStep) &&
1228 AddRecPhiMatch = &PN;
1230 TruncTy = SE.getEffectiveSCEVType(Normalized->
getType());
1234 if (AddRecPhiMatch) {
1237 if (L == IVIncInsertLoop)
1238 hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1242 InsertedValues.insert(AddRecPhiMatch);
1244 rememberInstruction(IncV);
1245 return AddRecPhiMatch;
1250 SCEVInsertPointGuard Guard(Builder,
this);
1260 PostIncLoops.
clear();
1264 "Can't expand add recurrences without a loop preheader!");
1265 Value *StartV = expandCodeFor(Normalized->
getStart(), ExpandTy,
1270 assert(!isa<Instruction>(StartV) ||
1271 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1282 Step = SE.getNegativeSCEV(Step);
1289 bool IncrementIsNUW = !useSubtract &&
IsIncrementNUW(SE, Normalized);
1290 bool IncrementIsNSW = !useSubtract &&
IsIncrementNSW(SE, Normalized);
1294 Builder.SetInsertPoint(Header, Header->
begin());
1296 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1297 Twine(IVName) +
".iv");
1298 rememberInstruction(PN);
1315 Builder.SetInsertPoint(InsertPos);
1316 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1318 if (isa<OverflowingBinaryOperator>(IncV)) {
1320 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1322 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1329 PostIncLoops = SavedPostIncLoops;
1332 InsertedValues.
insert(PN);
1339 Type *IntTy = SE.getEffectiveSCEVType(STy);
1345 if (PostIncLoops.count(L)) {
1353 const SCEV *PostLoopOffset =
nullptr;
1354 if (!SE.properlyDominates(Start, L->
getHeader())) {
1355 PostLoopOffset = Start;
1356 Start = SE.getConstant(Normalized->
getType(), 0);
1357 Normalized = cast<SCEVAddRecExpr>(
1365 const SCEV *PostLoopScale =
nullptr;
1366 if (!SE.dominates(Step, L->
getHeader())) {
1367 PostLoopScale = Step;
1368 Step = SE.getConstant(Normalized->
getType(), 1);
1369 if (!Start->isZero()) {
1372 assert(!PostLoopOffset &&
"Start not-null but PostLoopOffset set?");
1373 PostLoopOffset = Start;
1374 Start = SE.getConstant(Normalized->
getType(), 0);
1377 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1378 Start, Step, Normalized->
getLoop(),
1384 Type *ExpandTy = PostLoopScale ? IntTy : STy;
1387 Type *AddRecPHIExpandTy =
1388 DL.isNonIntegralPointerType(STy) ? Normalized->
getType() : ExpandTy;
1392 Type *TruncTy =
nullptr;
1393 bool InvertStep =
false;
1394 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, AddRecPHIExpandTy,
1395 IntTy, TruncTy, InvertStep);
1399 if (!PostIncLoops.count(L))
1404 assert(LatchBlock &&
"PostInc mode requires a unique loop latch!");
1410 if (isa<Instruction>(Result) &&
1411 !SE.DT.dominates(cast<Instruction>(Result),
1412 &*Builder.GetInsertPoint())) {
1425 Step = SE.getNegativeSCEV(Step);
1429 SCEVInsertPointGuard Guard(Builder,
this);
1432 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1441 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1442 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1444 if (TruncTy != Result->
getType()) {
1445 Result = Builder.CreateTrunc(Result, TruncTy);
1446 rememberInstruction(Result);
1450 Result = Builder.CreateSub(expandCodeFor(Normalized->
getStart(), TruncTy),
1452 rememberInstruction(Result);
1457 if (PostLoopScale) {
1458 assert(S->
isAffine() &&
"Can't linearly scale non-affine recurrences.");
1459 Result = InsertNoopCastOfTo(Result, IntTy);
1460 Result = Builder.CreateMul(Result,
1461 expandCodeFor(PostLoopScale, IntTy));
1462 rememberInstruction(Result);
1466 if (PostLoopOffset) {
1467 if (
PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1469 Value *
Base = expandCodeFor(PostLoopOffset, ExpandTy);
1470 Result = expandAddToGEP(SE.getUnknown(Result), PTy, IntTy, Base);
1472 Result = expandAddToGEP(PostLoopOffset, PTy, IntTy, Result);
1475 Result = InsertNoopCastOfTo(Result, IntTy);
1476 Result = Builder.CreateAdd(Result,
1477 expandCodeFor(PostLoopOffset, IntTy));
1478 rememberInstruction(Result);
1497 return expandAddRecExprLiterally(S);
1503 PHINode *CanonicalIV =
nullptr;
1505 if (SE.getTypeSizeInBits(PN->
getType()) >= SE.getTypeSizeInBits(Ty))
1511 SE.getTypeSizeInBits(CanonicalIV->
getType()) >
1512 SE.getTypeSizeInBits(Ty)) {
1515 NewOps[i] = SE.getAnyExtendExpr(S->
op_begin()[i], CanonicalIV->
getType());
1520 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty),
nullptr,
1528 NewOps[0] = SE.getConstant(Ty, 0);
1529 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1536 const SCEV *ExposedRest = Rest;
1543 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1545 assert(StartV->
getType() == PTy &&
"Pointer type mismatch for GEP!");
1546 return expandAddToGEP(ExposedRest, PTy, Ty, StartV);
1555 const SCEV *AddExprRHS = SE.getUnknown(
expand(Rest));
1556 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1567 rememberInstruction(CanonicalIV);
1573 if (!PredSeen.
insert(HP).second) {
1587 rememberInstruction(Add);
1597 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->
getType()) &&
1598 "IVs with types different from the canonical IV should " 1599 "already have been handled!");
1608 expand(SE.getTruncateOrNoop(
1609 SE.getMulExpr(SE.getUnknown(CanonicalIV),
1618 const SCEV *IH = SE.getUnknown(CanonicalIV);
1621 const SCEV *NewS = S;
1622 const SCEV *
Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->
getType());
1623 if (isa<SCEVAddRecExpr>(Ext))
1626 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1630 const SCEV *
T = SE.getTruncateOrNoop(V, Ty);
1638 Value *I = Builder.CreateTrunc(V, Ty);
1639 rememberInstruction(I);
1647 Value *I = Builder.CreateZExt(V, Ty);
1648 rememberInstruction(I);
1656 Value *I = Builder.CreateSExt(V, Ty);
1657 rememberInstruction(I);
1669 Ty = SE.getEffectiveSCEVType(Ty);
1670 LHS = InsertNoopCastOfTo(LHS, Ty);
1673 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1674 rememberInstruction(ICmp);
1675 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS,
"smax");
1676 rememberInstruction(Sel);
1682 LHS = InsertNoopCastOfTo(LHS, S->
getType());
1694 Ty = SE.getEffectiveSCEVType(Ty);
1695 LHS = InsertNoopCastOfTo(LHS, Ty);
1698 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1699 rememberInstruction(ICmp);
1700 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS,
"umax");
1701 rememberInstruction(Sel);
1707 LHS = InsertNoopCastOfTo(LHS, S->
getType());
1719 Ty = SE.getEffectiveSCEVType(Ty);
1720 LHS = InsertNoopCastOfTo(LHS, Ty);
1723 Value *ICmp = Builder.CreateICmpSLT(LHS, RHS);
1724 rememberInstruction(ICmp);
1725 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS,
"smin");
1726 rememberInstruction(Sel);
1732 LHS = InsertNoopCastOfTo(LHS, S->
getType());
1744 Ty = SE.getEffectiveSCEVType(Ty);
1745 LHS = InsertNoopCastOfTo(LHS, Ty);
1748 Value *ICmp = Builder.CreateICmpULT(LHS, RHS);
1749 rememberInstruction(ICmp);
1750 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS,
"umin");
1751 rememberInstruction(Sel);
1757 LHS = InsertNoopCastOfTo(LHS, S->
getType());
1764 return expandCodeFor(SH, Ty);
1771 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->
getType()) &&
1772 "non-trivial casts should be done with the SCEVs directly!");
1773 V = InsertNoopCastOfTo(V, Ty);
1778 ScalarEvolution::ValueOffsetPair
1779 SCEVExpander::FindValueInExprValueMap(
const SCEV *S,
1784 if (CanonicalMode || !SE.containsAddRecurrence(S)) {
1790 for (
auto const &VOPair : *Set) {
1791 Value *V = VOPair.first;
1794 if (V && isa<Instruction>(V) && (EntInst = cast<Instruction>(V)) &&
1797 SE.DT.dominates(EntInst, InsertPt) &&
1798 (SE.LI.getLoopFor(EntInst->
getParent()) ==
nullptr ||
1804 return {
nullptr,
nullptr};
1813 Value *SCEVExpander::expand(
const SCEV *S) {
1816 Instruction *InsertPt = &*Builder.GetInsertPoint();
1820 auto SafeToHoist = [](
const SCEV *S) {
1822 if (
const auto *
D = dyn_cast<SCEVUDivExpr>(S)) {
1823 if (
const auto *
SC = dyn_cast<SCEVConstant>(
D->getRHS()))
1825 return SC->getValue()->isZero();
1835 if (SafeToHoist(S)) {
1836 for (
Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1838 if (SE.isLoopInvariant(S, L)) {
1841 InsertPt = Preheader->getTerminator();
1851 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1853 while (InsertPt->
getIterator() != Builder.GetInsertPoint() &&
1854 (isInsertedInstruction(InsertPt) ||
1855 isa<DbgInfoIntrinsic>(InsertPt)))
1864 if (isa<PHINode>(*InsertPt))
1868 auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1869 if (I != InsertedExpressions.end())
1872 SCEVInsertPointGuard Guard(Builder,
this);
1873 Builder.SetInsertPoint(InsertPt);
1876 ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, InsertPt);
1877 Value *V = VO.first;
1881 else if (VO.second) {
1884 int64_t
Offset = VO.second->getSExtValue();
1885 int64_t ESize = SE.getTypeSizeInBits(Ety);
1886 if ((Offset * 8) % ESize == 0) {
1889 V = Builder.CreateGEP(Ety, V, Idx,
"scevgep");
1893 unsigned AS = Vty->getAddressSpace();
1897 V = Builder.CreateBitCast(V, Vty);
1900 V = Builder.CreateSub(V, VO.second);
1909 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1913 void SCEVExpander::rememberInstruction(
Value *I) {
1914 if (!PostIncLoops.empty())
1915 InsertedPostIncValues.insert(I);
1917 InsertedValues.insert(I);
1931 const SCEV *
H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1935 SCEVInsertPointGuard Guard(Builder,
this);
1937 cast<PHINode>(expandCodeFor(H,
nullptr, &L->
getHeader()->
front()));
1966 unsigned NumElim = 0;
1974 if (!SE.isSCEVable(PN->
getType()))
1979 return Const->getValue();
1985 if (V->
getType() != Phi->getType())
1987 Phi->replaceAllUsesWith(V);
1991 <<
"INDVARS: Eliminated constant iv: " << *Phi <<
'\n');
1995 if (!SE.isSCEVable(Phi->getType()))
1998 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
2001 if (Phi->getType()->isIntegerTy() && TTI &&
2005 const SCEV *TruncExpr =
2006 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
2007 ExprToIVMap[TruncExpr] = Phi;
2023 if (OrigInc && IsomorphicInc) {
2027 if (OrigPhiRef->
getType() == Phi->getType() &&
2028 !(ChainedPhis.count(Phi) ||
2029 isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
2030 (ChainedPhis.count(Phi) ||
2031 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
2042 const SCEV *TruncExpr =
2043 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
2044 if (OrigInc != IsomorphicInc &&
2045 TruncExpr == SE.getSCEV(IsomorphicInc) &&
2046 SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
2047 hoistIVInc(OrigInc, IsomorphicInc)) {
2049 dbgs() <<
"INDVARS: Eliminated congruent iv.inc: " 2050 << *IsomorphicInc <<
'\n');
2051 Value *NewInc = OrigInc;
2052 if (OrigInc->
getType() != IsomorphicInc->getType()) {
2054 if (
PHINode *PN = dyn_cast<PHINode>(OrigInc))
2062 OrigInc, IsomorphicInc->
getType(), IVName);
2072 Value *NewIV = OrigPhiRef;
2073 if (OrigPhiRef->
getType() != Phi->getType()) {
2076 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->
getType(), IVName);
2087 getRelatedExistingExpansion(S, At, L);
2088 if (VO && VO.
getValue().second ==
nullptr)
2106 if (!
match(BB->getTerminator(),
2111 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
2112 return ScalarEvolution::ValueOffsetPair(LHS,
nullptr);
2114 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
2115 return ScalarEvolution::ValueOffsetPair(RHS,
nullptr);
2120 ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, At);
2131 bool SCEVExpander::isHighCostExpansionHelper(
2137 if (At && getRelatedExistingExpansion(S, At, L))
2146 return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
2149 return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
2152 return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
2156 if (!Processed.
insert(S).second)
2159 if (
auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
2164 if (
auto *
SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
2165 if (
SC->getAPInt().isPowerOf2()) {
2166 if (isHighCostExpansionHelper(UDivExpr->getLHS(), L, At, Processed))
2187 At = &ExitingBB->
back();
2188 if (!getRelatedExistingExpansion(
2189 SE.getAddExpr(S, SE.getConstant(S->
getType(), 1)), At, L))
2195 if (isa<SCEVMinMaxExpr>(S))
2201 if (
const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
2202 for (
auto *Op : NAry->operands())
2203 if (isHighCostExpansionHelper(Op, L, At, Processed))
2217 return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2219 return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
2221 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2222 return expandWrapPredicate(AddRecPred, IP);
2233 Builder.SetInsertPoint(IP);
2234 auto *I = Builder.CreateICmpNE(Expr0, Expr1,
"ident.check");
2241 "non-affine expression");
2244 const SCEV *ExitCount =
2245 SE.getPredicatedBackedgeTakenCount(AR->
getLoop(), Pred);
2247 assert(ExitCount != SE.getCouldNotCompute() &&
"Invalid loop count");
2253 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->
getType());
2254 unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2262 Builder.SetInsertPoint(Loc);
2263 Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc);
2267 Type *ARExpandTy = DL.isNonIntegralPointerType(ARTy) ? ARTy : Ty;
2269 Value *StepValue = expandCodeFor(Step, Ty, Loc);
2270 Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc);
2271 Value *StartValue = expandCodeFor(Start, ARExpandTy, Loc);
2276 Builder.SetInsertPoint(Loc);
2279 Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2282 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2284 Intrinsic::umul_with_overflow, Ty);
2287 CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount},
"mul");
2288 Value *MulV = Builder.CreateExtractValue(Mul, 0,
"mul.result");
2289 Value *OfMul = Builder.CreateExtractValue(Mul, 1,
"mul.overflow");
2294 Value *
Add =
nullptr, *Sub =
nullptr;
2295 if (
PointerType *ARPtrTy = dyn_cast<PointerType>(ARExpandTy)) {
2296 const SCEV *MulS = SE.getSCEV(MulV);
2297 const SCEV *NegMulS = SE.getNegativeSCEV(MulS);
2298 Add = Builder.CreateBitCast(expandAddToGEP(MulS, ARPtrTy, Ty, StartValue),
2300 Sub = Builder.CreateBitCast(
2301 expandAddToGEP(NegMulS, ARPtrTy, Ty, StartValue), ARPtrTy);
2303 Add = Builder.CreateAdd(StartValue, MulV);
2304 Sub = Builder.CreateSub(StartValue, MulV);
2307 Value *EndCompareGT = Builder.CreateICmp(
2310 Value *EndCompareLT = Builder.CreateICmp(
2315 Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2320 if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2322 auto *BackedgeCheck =
2323 Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2325 BackedgeCheck = Builder.CreateAnd(
2328 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2331 EndCheck = Builder.CreateOr(EndCheck, OfMul);
2337 const auto *A = cast<SCEVAddRecExpr>(Pred->
getExpr());
2338 Value *NSSWCheck =
nullptr, *NUSWCheck =
nullptr;
2342 NUSWCheck = generateOverflowCheck(A, IP,
false);
2346 NSSWCheck = generateOverflowCheck(A, IP,
true);
2348 if (NUSWCheck && NSSWCheck)
2349 return Builder.CreateOr(NUSWCheck, NSSWCheck);
2367 auto *NextCheck = expandCodeForPredicate(Pred, IP);
2368 Builder.SetInsertPoint(IP);
2369 Check = Builder.CreateOr(Check, NextCheck);
2396 struct SCEVFindUnsafe {
2402 bool follow(
const SCEV *S) {
2411 const SCEV *Step = AR->getStepRecurrence(SE);
2412 if (!AR->isAffine() && !SE.
dominates(Step, AR->getLoop()->getHeader())) {
2419 bool isDone()
const {
return IsUnsafe; }
2425 SCEVFindUnsafe Search(SE);
2427 return !Search.IsUnsafe;
2445 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2447 if (V == U->getValue())
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static bool Check(DecodeStatus &Out, DecodeStatus In)
A parsed version of the target data layout string in and methods for querying it. ...
bool hoistIVInc(Instruction *IncV, Instruction *InsertPos)
Utility for hoisting an IV increment.
static ConstantInt * getFalse(LLVMContext &Context)
reference emplace_back(ArgTypes &&... Args)
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Value * getExactExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Try to find existing LLVM IR value for S available at the point At.
This class represents an incoming formal argument to a Function.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
const SCEV * getConstant(ConstantInt *V)
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
This class represents lattice values for constants.
Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are d...
const SCEV * normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE)
Normalize S to be post-increment for all loops present in Loops.
size_t getNumOperands() const
void push_back(const T &Elt)
The main scalar evolution driver.
APInt zext(unsigned width) const
Zero extend to a new width.
bool isZero() const
Return true if the expression is a constant zero.
This class represents a function call, abstracting a target machine's calling convention.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block...
Optional< ScalarEvolution::ValueOffsetPair > getRelatedExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Try to find the ValueOffsetPair for S.
LLVMContext & getContext() const
All values hold a context through their type.
This class represents a truncation of an integer value to a smaller integer value.
Value * expandWrapPredicate(const SCEVWrapPredicate *P, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
const SCEV * getOperand() const
static void SimplifyAddOperands(SmallVectorImpl< const SCEV *> &Ops, Type *Ty, ScalarEvolution &SE)
SimplifyAddOperands - Sort and simplify a list of add operands.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isVectorTy() const
True if this is an instance of VectorType.
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
This is the base class for unary cast operator classes.
unsigned getBitWidth() const
Return the number of bits in the APInt.
return AArch64::GPR64RegClass contains(Reg)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
#define DEBUG_WITH_TYPE(TYPE, X)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
bool match(Val *V, const Pattern &P)
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
Type * getPointerElementType() const
const Loop * getLoop() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
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...
This is the base class for all instructions that perform data casts.
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVMContext & getContext() const
This node represents multiplication of some number of SCEVs.
Value * generateOverflowCheck(const SCEVAddRecExpr *AR, Instruction *Loc, bool Signed)
Generates code that evaluates if the AR expression will overflow.
const APInt & getAPInt() const
BlockT * getHeader() const
ConstantInt * getValue() const
A constant value that is initialized with an expression using other constant values.
Type * getType() const
All values are typed, get the type of this value.
This node represents a polynomial recurrence on the trip count of the specified loop.
const T & getValue() const LLVM_LVALUE_FUNCTION
Class to represent array types.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
op_iterator op_begin() const
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
This class represents a signed minimum selection.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
Value * getOperand(unsigned i) const
Class to represent pointers.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
const SCEV * getOperand(unsigned i) const
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
SCEVPredicateKind getKind() const
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
This class represents a binary unsigned division operation.
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
This class represents an unsigned minimum selection.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
bool isPointerTy() const
True if this is an instance of PointerType.
const Instruction & front() const
const SCEV * getExpr() const override
Implementation of the SCEVPredicate interface.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
const SCEV * getLHS() const
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
const Instruction & back() const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder, const SCEV *Factor, ScalarEvolution &SE, const DataLayout &DL)
FactorOutConstant - Test if S is divisible by Factor, using signed division.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
op_iterator op_end() const
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Interval::pred_iterator pred_end(Interval *I)
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
unsigned getAddressSpace() const
Return the address space of the Pointer type.
self_iterator getIterator()
Class to represent integer types.
const SCEV * getStart() const
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
static LLVM_NODISCARD SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
static Expected< BitVector > expand(StringRef S, StringRef Original)
const Function * getFunction() const
Return the function this instruction belongs to.
const SCEV * getLHS() const
Returns the left hand side of the equality.
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
const SCEV * getRHS() const
Returns the right hand side of the equality.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
const SCEV * getMulExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static void SplitAddRecs(SmallVectorImpl< const SCEV *> &Ops, Type *Ty, ScalarEvolution &SE)
SplitAddRecs - Flatten a list of add operands, moving addrec start values out to the top level...
This class represents an assumption made using SCEV expressions which can be checked at run-time...
static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
void sort(IteratorTy Start, IteratorTy End)
static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest, ScalarEvolution &SE)
Move parts of Base into Rest to leave Base with the minimal expression that provides a pointer operan...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
unsigned getSCEVType() const
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
unsigned getNumOperands() const
static PointerType * getInt1PtrTy(LLVMContext &C, unsigned AS=0)
This is the shared class of boolean and integer constants.
Type * getType() const
Return the LLVM type of this SCEV expression.
PHINode * getOrInsertCanonicalInductionVariable(const Loop *L, Type *Ty)
This method returns the canonical induction variable of the specified type for the specified loop (in...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
uint64_t getSizeInBytes() const
CHAIN = SC CHAIN, Imm128 - System call.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
unsigned logBase2() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
This node represents an addition of some number of SCEVs.
static BasicBlock::iterator findInsertPointAfter(Instruction *I, BasicBlock *MustDominate)
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
This class represents a signed maximum selection.
iterator_range< user_iterator > users()
InstListType::iterator iterator
Instruction iterators...
Value * expandUnionPredicate(const SCEVUnionPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
This class represents a zero extension of a small integer value to a larger integer value...
Value * CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name="")
static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
LoopT * getParentLoop() const
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
uint64_t getElementOffset(unsigned Idx) const
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
unsigned getIntegerBitWidth() const
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
iterator_range< value_op_iterator > operand_values()
This class represents a sign extension of a small integer value to a larger integer value...
This class represents an unsigned maximum selection.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
class_match< BasicBlock > m_BasicBlock()
Match an arbitrary basic block value and ignore it.
Instruction * getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale)
Return the induction variable increment's IV operand.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const SCEV * getRHS() const
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
const SmallVectorImpl< const SCEVPredicate * > & getPredicates() const
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
reverse_iterator rbegin()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class represents a composition of other SCEV predicates, and is the class that most clients will...
bool isOne() const
Return true if the expression is a constant one.
void stable_sort(R &&Range)
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
Module * getParent()
Get the module that this global value is contained inside of...
Value * expandEqualPredicate(const SCEVEqualPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM Value Representation.
A vector that has set insertion semantics.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
static Value * SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q)
See if we can fold the given phi. If not, returns null.
bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block...
bool isIllegalInteger(uint64_t Width) const
static APInt getNullValue(unsigned numBits)
Get the '0' value.
This node is a base class providing common functionality for n'ary operators.
This class represents an assumption made on an AddRec expression.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
This class represents an assumption that two SCEV expressions are equal, and this can be checked at r...
static IntegerType * getInt8Ty(LLVMContext &C)
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
Type * getElementType() const
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const BasicBlock * getParent() const
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...
This class represents a constant integer value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.