34using namespace PatternMatch;
36#define DEBUG_TYPE "instcombine"
45 const APInt &In2,
bool IsSigned =
false) {
48 Result = In1.
sadd_ov(In2, Overflow);
50 Result = In1.
uadd_ov(In2, Overflow);
58 const APInt &In2,
bool IsSigned =
false) {
61 Result = In1.
ssub_ov(In2, Overflow);
63 Result = In1.
usub_ov(In2, Overflow);
71 for (
auto *U :
I.users())
72 if (isa<BranchInst>(U))
82 if (!ICmpInst::isSigned(Pred))
89 if (Pred == ICmpInst::ICMP_SLT) {
90 Pred = ICmpInst::ICMP_SLE;
93 }
else if (
C.isAllOnes()) {
94 if (Pred == ICmpInst::ICMP_SGT) {
95 Pred = ICmpInst::ICMP_SGE;
114 if (
LI->isVolatile() ||
LI->getType() !=
GEP->getResultElementType() ||
120 if (!isa<ConstantArray>(
Init) && !isa<ConstantDataArray>(
Init))
123 uint64_t ArrayElementCount =
Init->getType()->getArrayNumElements();
132 if (
GEP->getNumOperands() < 3 || !isa<ConstantInt>(
GEP->getOperand(1)) ||
133 !cast<ConstantInt>(
GEP->getOperand(1))->isZero() ||
134 isa<Constant>(
GEP->getOperand(2)))
142 Type *EltTy =
Init->getType()->getArrayElementType();
143 for (
unsigned i = 3, e =
GEP->getNumOperands(); i != e; ++i) {
149 if ((
unsigned)IdxVal != IdxVal)
152 if (
StructType *STy = dyn_cast<StructType>(EltTy))
153 EltTy = STy->getElementType(IdxVal);
154 else if (
ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
155 if (IdxVal >= ATy->getNumElements())
157 EltTy = ATy->getElementType();
165 enum { Overdefined = -3, Undefined = -2 };
174 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
178 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
186 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
195 for (
unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
201 if (!LaterIndices.
empty()) {
216 CompareRHS,
DL, &
TLI);
221 if (isa<UndefValue>(
C)) {
224 if (TrueRangeEnd == (
int)i - 1)
226 if (FalseRangeEnd == (
int)i - 1)
233 if (!isa<ConstantInt>(
C))
238 bool IsTrueForElt = !cast<ConstantInt>(
C)->isZero();
243 if (FirstTrueElement == Undefined)
244 FirstTrueElement = TrueRangeEnd = i;
247 if (SecondTrueElement == Undefined)
248 SecondTrueElement = i;
250 SecondTrueElement = Overdefined;
253 if (TrueRangeEnd == (
int)i - 1)
256 TrueRangeEnd = Overdefined;
260 if (FirstFalseElement == Undefined)
261 FirstFalseElement = FalseRangeEnd = i;
264 if (SecondFalseElement == Undefined)
265 SecondFalseElement = i;
267 SecondFalseElement = Overdefined;
270 if (FalseRangeEnd == (
int)i - 1)
273 FalseRangeEnd = Overdefined;
278 if (i < 64 && IsTrueForElt)
279 MagicBitvector |= 1ULL << i;
284 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
285 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
286 FalseRangeEnd == Overdefined)
297 if (!
GEP->isInBounds()) {
300 if (
Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > OffsetSize)
311 unsigned ElementSize =
324 if (SecondTrueElement != Overdefined) {
327 if (FirstTrueElement == Undefined)
330 Value *FirstTrueIdx = ConstantInt::get(
Idx->getType(), FirstTrueElement);
333 if (SecondTrueElement == Undefined)
338 Value *SecondTrueIdx = ConstantInt::get(
Idx->getType(), SecondTrueElement);
340 return BinaryOperator::CreateOr(C1, C2);
345 if (SecondFalseElement != Overdefined) {
348 if (FirstFalseElement == Undefined)
351 Value *FirstFalseIdx = ConstantInt::get(
Idx->getType(), FirstFalseElement);
354 if (SecondFalseElement == Undefined)
359 Value *SecondFalseIdx =
360 ConstantInt::get(
Idx->getType(), SecondFalseElement);
362 return BinaryOperator::CreateAnd(C1, C2);
367 if (TrueRangeEnd != Overdefined) {
368 assert(TrueRangeEnd != FirstTrueElement &&
"Should emit single compare");
372 if (FirstTrueElement) {
373 Value *Offs = ConstantInt::get(
Idx->getType(), -FirstTrueElement);
378 ConstantInt::get(
Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
383 if (FalseRangeEnd != Overdefined) {
384 assert(FalseRangeEnd != FirstFalseElement &&
"Should emit single compare");
387 if (FirstFalseElement) {
388 Value *Offs = ConstantInt::get(
Idx->getType(), -FirstFalseElement);
393 ConstantInt::get(
Idx->getType(), FalseRangeEnd - FirstFalseElement);
406 if (ArrayElementCount <= Idx->
getType()->getIntegerBitWidth())
440 while (!WorkList.
empty()) {
443 while (!WorkList.
empty()) {
444 if (Explored.
size() >= 100)
454 if (!isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
459 if (
auto *
GEP = dyn_cast<GEPOperator>(V)) {
461 auto IsNonConst = [](
Value *V) {
return !isa<ConstantInt>(V); };
462 if (!
GEP->isInBounds() ||
count_if(
GEP->indices(), IsNonConst) > 1)
469 if (WorkList.
back() == V) {
475 if (
auto *PN = dyn_cast<PHINode>(V)) {
477 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
485 for (
auto *PN : PHIs)
486 for (
Value *
Op : PN->incoming_values())
494 for (
Value *Val : Explored) {
497 auto *
PHI = dyn_cast<PHINode>(
Use);
498 auto *Inst = dyn_cast<Instruction>(Val);
500 if (Inst ==
Base || Inst ==
PHI || !Inst || !
PHI ||
504 if (
PHI->getParent() == Inst->getParent())
515 if (
auto *
PHI = dyn_cast<PHINode>(V)) {
520 if (
auto *
I = dyn_cast<Instruction>(V)) {
522 I = &*std::next(
I->getIterator());
526 if (
auto *
A = dyn_cast<Argument>(V)) {
528 BasicBlock &Entry =
A->getParent()->getEntryBlock();
534 assert(isa<Constant>(V) &&
"Setting insertion point for unknown value!");
551 Base->getContext(),
DL.getIndexTypeSizeInBits(Start->getType()));
557 for (
Value *Val : Explored) {
562 if (
auto *
PHI = dyn_cast<PHINode>(Val))
565 PHI->getName() +
".idx",
PHI->getIterator());
570 for (
Value *Val : Explored) {
574 if (
auto *
GEP = dyn_cast<GEPOperator>(Val)) {
578 if (isa<ConstantInt>(
Op) && cast<ConstantInt>(
Op)->
isZero())
579 NewInsts[
GEP] = OffsetV;
582 Op, OffsetV,
GEP->getOperand(0)->getName() +
".add");
585 if (isa<PHINode>(Val))
592 for (
Value *Val : Explored) {
597 if (
auto *
PHI = dyn_cast<PHINode>(Val)) {
599 for (
unsigned I = 0, E =
PHI->getNumIncomingValues();
I < E; ++
I) {
600 Value *NewIncoming =
PHI->getIncomingValue(
I);
603 NewIncoming = NewInsts[NewIncoming];
610 for (
Value *Val : Explored) {
617 Builder.
getInt8Ty(),
Base, NewInsts[Val], Val->getName() +
".ptr");
624 return NewInsts[Start];
687 if (!isa<GetElementPtrInst>(
RHS))
699 isa<Constant>(
RHS) && cast<Constant>(
RHS)->isNullValue() &&
721 auto EC = cast<VectorType>(GEPLHS->
getType())->getElementCount();
726 cast<Constant>(
RHS),
Base->getType()));
730 if (PtrBase != GEPRHS->getOperand(0)) {
731 bool IndicesTheSame =
734 GEPRHS->getPointerOperand()->getType() &&
738 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
739 IndicesTheSame =
false;
752 if (GEPLHS->
isInBounds() && GEPRHS->isInBounds() &&
754 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
758 Value *LOffset = EmitGEPOffset(GEPLHS);
759 Value *ROffset = EmitGEPOffset(GEPRHS);
766 if (LHSIndexTy != RHSIndexTy) {
785 bool GEPsInBounds = GEPLHS->
isInBounds() && GEPRHS->isInBounds();
789 unsigned NumDifferences = 0;
790 unsigned DiffOperand = 0;
791 for (
unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
792 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
794 Type *RHSType = GEPRHS->getOperand(i)->getType();
805 if (NumDifferences++)
break;
809 if (NumDifferences == 0)
813 else if (NumDifferences == 1 && GEPsInBounds) {
815 Value *RHSV = GEPRHS->getOperand(DiffOperand);
823 Value *L = EmitGEPOffset(GEPLHS,
true);
824 Value *R = EmitGEPOffset(GEPRHS,
true);
851 bool Captured =
false;
856 CmpCaptureTracker(
AllocaInst *Alloca) : Alloca(Alloca) {}
858 void tooManyUses()
override { Captured =
true; }
860 bool captured(
const Use *U)
override {
861 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
869 auto Res = ICmps.
insert({ICmp, 0});
870 Res.first->second |= 1u << U->getOperandNo();
879 CmpCaptureTracker Tracker(Alloca);
881 if (Tracker.Captured)
884 bool Changed =
false;
885 for (
auto [ICmp,
Operands] : Tracker.ICmps) {
891 auto *Res = ConstantInt::get(
917 assert(!!
C &&
"C should not be zero!");
923 Constant *R = ConstantInt::get(
X->getType(),
933 ConstantInt::get(
X->getType(), -
C));
945 ConstantInt::get(
X->getType(),
SMax -
C));
956 ConstantInt::get(
X->getType(),
SMax - (
C - 1)));
965 assert(
I.isEquality() &&
"Cannot fold icmp gt/lt");
968 if (
I.getPredicate() ==
I.ICMP_NE)
977 bool IsAShr = isa<AShrOperator>(
I.getOperand(0));
989 return getICmp(
I.ICMP_UGT,
A,
990 ConstantInt::get(
A->getType(), AP2.
logBase2()));
1002 if (IsAShr && AP1 == AP2.
ashr(Shift)) {
1006 return getICmp(
I.ICMP_UGE,
A, ConstantInt::get(
A->getType(), Shift));
1007 return getICmp(
I.ICMP_EQ,
A, ConstantInt::get(
A->getType(), Shift));
1008 }
else if (AP1 == AP2.
lshr(Shift)) {
1009 return getICmp(
I.ICMP_EQ,
A, ConstantInt::get(
A->getType(), Shift));
1015 auto *TorF = ConstantInt::get(
I.getType(),
I.getPredicate() ==
I.ICMP_NE);
1024 assert(
I.isEquality() &&
"Cannot fold icmp gt/lt");
1027 if (
I.getPredicate() ==
I.ICMP_NE)
1038 if (!AP1 && AP2TrailingZeros != 0)
1041 ConstantInt::get(
A->getType(), AP2.
getBitWidth() - AP2TrailingZeros));
1049 if (Shift > 0 && AP2.
shl(Shift) == AP1)
1050 return getICmp(
I.ICMP_EQ,
A, ConstantInt::get(
A->getType(), Shift));
1054 auto *TorF = ConstantInt::get(
I.getType(),
I.getPredicate() ==
I.ICMP_NE);
1075 Instruction *AddWithCst = cast<Instruction>(
I.getOperand(0));
1083 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1107 if (U == AddWithCst)
1125 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1154 if (!
I.isEquality())
1185 APInt(XBitWidth, XBitWidth - 1))))
1187 }
else if (isa<BinaryOperator>(Val) &&
1212 return new ICmpInst(Pred,
B, Cmp.getOperand(1));
1214 return new ICmpInst(Pred,
A, Cmp.getOperand(1));
1231 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
1243 return new ICmpInst(Pred,
Y, Cmp.getOperand(1));
1249 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
1251 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1252 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1260 return new ICmpInst(Pred,
Y, Cmp.getOperand(1));
1265 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
1297 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1310 if (
auto *Phi = dyn_cast<PHINode>(Op0))
1311 if (
all_of(Phi->operands(), [](
Value *V) { return isa<Constant>(V); })) {
1313 for (
Value *V : Phi->incoming_values()) {
1322 for (
auto [V, Pred] :
zip(Ops, Phi->blocks()))
1337 Value *
X = Cmp.getOperand(0), *
Y = Cmp.getOperand(1);
1370 if (Cmp.isEquality() || (IsSignBit &&
hasBranchUse(Cmp)))
1375 if (Cmp.hasOneUse() &&
1389 if (!
match(BI->getCondition(),
1395 if (
auto *V = handleDomCond(DomPred, DomC))
1415 Type *SrcTy =
X->getType();
1421 if (shouldChangeType(Trunc->
getType(), SrcTy)) {
1423 return new ICmpInst(Pred,
X, ConstantInt::get(SrcTy,
C.sext(SrcBits)));
1425 return new ICmpInst(Pred,
X, ConstantInt::get(SrcTy,
C.zext(SrcBits)));
1428 if (
C.isOne() &&
C.getBitWidth() > 1) {
1433 ConstantInt::get(V->getType(), 1));
1443 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1444 return new ICmpInst(NewPred,
Y, ConstantInt::get(SrcTy, DstBits));
1449 return new ICmpInst(Pred,
Y, ConstantInt::get(SrcTy,
C.logBase2()));
1452 if (Cmp.isEquality() && Trunc->
hasOneUse()) {
1455 if (!SrcTy->
isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1459 Constant *WideC = ConstantInt::get(SrcTy,
C.zext(SrcBits));
1468 if ((Known.
Zero | Known.
One).countl_one() >= SrcBits - DstBits) {
1470 APInt NewRHS =
C.zext(SrcBits);
1472 return new ICmpInst(Pred,
X, ConstantInt::get(SrcTy, NewRHS));
1480 const APInt *ShAmtC;
1501 bool YIsSExt =
false;
1504 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1505 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1506 if (Cmp.isSigned()) {
1517 if (
X->getType() !=
Y->getType() &&
1518 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1520 if (!isDesirableIntType(
X->getType()->getScalarSizeInBits()) &&
1521 isDesirableIntType(
Y->getType()->getScalarSizeInBits())) {
1523 Pred = Cmp.getSwappedPredicate(Pred);
1528 else if (!Cmp.isSigned() &&
1538 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1542 Type *TruncTy = Cmp.getOperand(0)->getType();
1547 if (isDesirableIntType(TruncBits) &&
1548 !isDesirableIntType(
X->getType()->getScalarSizeInBits()))
1571 bool TrueIfSigned =
false;
1588 if (
Xor->hasOneUse()) {
1590 if (!Cmp.isEquality() && XorC->
isSignMask()) {
1591 Pred = Cmp.getFlippedSignednessPredicate();
1592 return new ICmpInst(Pred,
X, ConstantInt::get(
X->getType(),
C ^ *XorC));
1597 Pred = Cmp.getFlippedSignednessPredicate();
1598 Pred = Cmp.getSwappedPredicate(Pred);
1599 return new ICmpInst(Pred,
X, ConstantInt::get(
X->getType(),
C ^ *XorC));
1606 if (*XorC == ~
C && (
C + 1).isPowerOf2())
1609 if (*XorC ==
C && (
C + 1).isPowerOf2())
1614 if (*XorC == -
C &&
C.isPowerOf2())
1616 ConstantInt::get(
X->getType(), ~
C));
1618 if (*XorC ==
C && (-
C).isPowerOf2())
1620 ConstantInt::get(
X->getType(), ~
C));
1642 const APInt *ShiftC;
1647 Type *XType =
X->getType();
1653 return new ICmpInst(Pred,
Add, ConstantInt::get(XType, Bound));
1662 if (!Shift || !Shift->
isShift())
1670 unsigned ShiftOpcode = Shift->
getOpcode();
1671 bool IsShl = ShiftOpcode == Instruction::Shl;
1674 APInt NewAndCst, NewCmpCst;
1675 bool AnyCmpCstBitsShiftedOut;
1676 if (ShiftOpcode == Instruction::Shl) {
1684 NewCmpCst = C1.
lshr(*C3);
1685 NewAndCst = C2.
lshr(*C3);
1686 AnyCmpCstBitsShiftedOut = NewCmpCst.
shl(*C3) != C1;
1687 }
else if (ShiftOpcode == Instruction::LShr) {
1692 NewCmpCst = C1.
shl(*C3);
1693 NewAndCst = C2.
shl(*C3);
1694 AnyCmpCstBitsShiftedOut = NewCmpCst.
lshr(*C3) != C1;
1700 assert(ShiftOpcode == Instruction::AShr &&
"Unknown shift opcode");
1701 NewCmpCst = C1.
shl(*C3);
1702 NewAndCst = C2.
shl(*C3);
1703 AnyCmpCstBitsShiftedOut = NewCmpCst.
ashr(*C3) != C1;
1704 if (NewAndCst.
ashr(*C3) != C2)
1708 if (AnyCmpCstBitsShiftedOut) {
1718 Shift->
getOperand(0), ConstantInt::get(
And->getType(), NewAndCst));
1719 return new ICmpInst(Cmp.getPredicate(),
1720 NewAnd, ConstantInt::get(
And->getType(), NewCmpCst));
1752 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.
isZero() &&
1754 return new TruncInst(
And->getOperand(0), Cmp.getType());
1762 if (!
And->hasOneUse())
1765 if (Cmp.isEquality() && C1.
isZero()) {
1783 Constant *NegBOC = ConstantInt::get(
And->getType(), -NewC2);
1785 return new ICmpInst(NewPred,
X, NegBOC);
1803 if (!Cmp.getType()->isVectorTy()) {
1804 Type *WideType = W->getType();
1806 Constant *ZextC1 = ConstantInt::get(WideType, C1.
zext(WideScalarBits));
1807 Constant *ZextC2 = ConstantInt::get(WideType, C2->
zext(WideScalarBits));
1809 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1820 if (!Cmp.isSigned() && C1.
isZero() &&
And->getOperand(0)->hasOneUse() &&
1822 Constant *One = cast<Constant>(
And->getOperand(1));
1827 unsigned UsesRemoved = 0;
1828 if (
And->hasOneUse())
1830 if (
Or->hasOneUse())
1837 if (UsesRemoved >= RequireUsesRemoved) {
1841 One,
Or->getName());
1853 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1854 Attribute::NoImplicitFloat) &&
1857 Type *FPType = V->getType()->getScalarType();
1859 APInt ExponentMask =
1861 if (C1 == ExponentMask) {
1894 Constant *MinSignedC = ConstantInt::get(
1898 return new ICmpInst(NewPred,
X, MinSignedC);
1907 if (
auto *C2 = dyn_cast<ConstantInt>(
Y))
1908 if (
auto *
LI = dyn_cast<LoadInst>(
X))
1909 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(
LI->getOperand(0)))
1910 if (
auto *GV = dyn_cast<GlobalVariable>(
GEP->getOperand(0)))
1915 if (!Cmp.isEquality())
1921 if (Cmp.getOperand(1) ==
Y &&
C.isNegatedPowerOf2()) {
1924 return new ICmpInst(NewPred,
X,
SubOne(cast<Constant>(Cmp.getOperand(1))));
1937 assert(Cmp.isEquality() &&
"Not expecting non-equality predicates");
1939 const APInt *TC, *FC;
1956 X->getType()->isIntOrIntVectorTy(1) && (
C.isZero() ||
C.isOne())) {
1962 return BinaryOperator::CreateAnd(TruncY,
X);
1994 while (!WorkList.
empty()) {
1995 auto MatchOrOperatorArgument = [&](
Value *OrOperatorArgument) {
1998 if (
match(OrOperatorArgument,
2004 if (
match(OrOperatorArgument,
2014 Value *OrOperatorLhs, *OrOperatorRhs;
2016 if (!
match(CurrentValue,
2021 MatchOrOperatorArgument(OrOperatorRhs);
2022 MatchOrOperatorArgument(OrOperatorLhs);
2028 CmpValues.
rbegin()->second);
2030 for (
auto It = CmpValues.
rbegin() + 1; It != CmpValues.
rend(); ++It) {
2032 LhsCmp = Builder.
CreateBinOp(BOpc, LhsCmp, RhsCmp);
2048 ConstantInt::get(V->getType(), 1));
2051 Value *OrOp0 =
Or->getOperand(0), *OrOp1 =
Or->getOperand(1);
2056 cast<PossiblyDisjointInst>(
Or)->isDisjoint()) {
2059 return new ICmpInst(Pred, OrOp0, NewC);
2063 if (
match(OrOp1,
m_APInt(MaskC)) && Cmp.isEquality()) {
2064 if (*MaskC ==
C && (
C + 1).isPowerOf2()) {
2069 return new ICmpInst(Pred, OrOp0, OrOp1);
2076 if (
Or->hasOneUse()) {
2078 Constant *NewC = ConstantInt::get(
Or->getType(),
C ^ (*MaskC));
2090 Constant *NewC = ConstantInt::get(
X->getType(), TrueIfSigned ? 1 : 0);
2118 if (!Cmp.isEquality() || !
C.isZero() || !
Or->hasOneUse())
2150 if (Cmp.isEquality() &&
C.isZero() &&
X ==
Mul->getOperand(1) &&
2151 (
Mul->hasNoUnsignedWrap() ||
Mul->hasNoSignedWrap()))
2173 if (Cmp.isEquality()) {
2175 if (
Mul->hasNoSignedWrap() &&
C.srem(*MulC).isZero()) {
2176 Constant *NewC = ConstantInt::get(MulTy,
C.sdiv(*MulC));
2184 if (
C.urem(*MulC).isZero()) {
2187 if ((*MulC & 1).isOne() ||
Mul->hasNoUnsignedWrap()) {
2188 Constant *NewC = ConstantInt::get(MulTy,
C.udiv(*MulC));
2201 if (
C.isMinSignedValue() && MulC->
isAllOnes())
2207 NewC = ConstantInt::get(
2211 "Unexpected predicate");
2212 NewC = ConstantInt::get(
2217 NewC = ConstantInt::get(
2221 "Unexpected predicate");
2222 NewC = ConstantInt::get(
2227 return NewC ?
new ICmpInst(Pred,
X, NewC) :
nullptr;
2238 unsigned TypeBits =
C.getBitWidth();
2239 bool CIsPowerOf2 =
C.isPowerOf2();
2241 if (Cmp.isUnsigned()) {
2254 unsigned CLog2 =
C.logBase2();
2255 return new ICmpInst(Pred,
Y, ConstantInt::get(ShiftType, CLog2));
2256 }
else if (Cmp.isSigned()) {
2257 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2278 const APInt *ShiftVal;
2308 const APInt *ShiftAmt;
2314 unsigned TypeBits =
C.getBitWidth();
2315 if (ShiftAmt->
uge(TypeBits))
2327 APInt ShiftedC =
C.ashr(*ShiftAmt);
2328 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2331 C.ashr(*ShiftAmt).shl(*ShiftAmt) ==
C) {
2332 APInt ShiftedC =
C.ashr(*ShiftAmt);
2333 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2340 assert(!
C.isMinSignedValue() &&
"Unexpected icmp slt");
2341 APInt ShiftedC = (
C - 1).ashr(*ShiftAmt) + 1;
2342 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2352 APInt ShiftedC =
C.lshr(*ShiftAmt);
2353 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2356 C.lshr(*ShiftAmt).shl(*ShiftAmt) ==
C) {
2357 APInt ShiftedC =
C.lshr(*ShiftAmt);
2358 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2365 assert(
C.ugt(0) &&
"ult 0 should have been eliminated");
2366 APInt ShiftedC = (
C - 1).lshr(*ShiftAmt) + 1;
2367 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2371 if (Cmp.isEquality() && Shl->
hasOneUse()) {
2377 Constant *LShrC = ConstantInt::get(ShType,
C.lshr(*ShiftAmt));
2382 bool TrueIfSigned =
false;
2394 if (Cmp.isUnsigned() && Shl->
hasOneUse()) {
2396 if ((
C + 1).isPowerOf2() &&
2404 if (
C.isPowerOf2() &&
2433 if (
auto FlippedStrictness =
2435 Pred, ConstantInt::get(ShType->
getContext(),
C))) {
2436 CmpPred = FlippedStrictness->first;
2437 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2444 ConstantInt::get(TruncTy, RHSC.
ashr(*ShiftAmt).
trunc(TypeBits - Amt));
2463 if (Cmp.isEquality() && Shr->
isExact() &&
C.isZero())
2464 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
2466 bool IsAShr = Shr->
getOpcode() == Instruction::AShr;
2467 const APInt *ShiftValC;
2469 if (Cmp.isEquality())
2487 assert(ShiftValC->
uge(
C) &&
"Expected simplify of compare");
2488 assert((IsUGT || !
C.isZero()) &&
"Expected X u< 0 to simplify");
2490 unsigned CmpLZ = IsUGT ?
C.countl_zero() : (
C - 1).
countl_zero();
2498 const APInt *ShiftAmtC;
2504 unsigned TypeBits =
C.getBitWidth();
2506 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2509 bool IsExact = Shr->
isExact();
2517 (
C - 1).isPowerOf2() &&
C.countLeadingZeros() > ShAmtVal) {
2523 APInt ShiftedC = (
C - 1).shl(ShAmtVal) + 1;
2524 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2530 APInt ShiftedC =
C.shl(ShAmtVal);
2531 if (ShiftedC.
ashr(ShAmtVal) ==
C)
2532 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2536 APInt ShiftedC = (
C + 1).shl(ShAmtVal) - 1;
2537 if (!
C.isMaxSignedValue() && !(
C + 1).shl(ShAmtVal).isMinSignedValue() &&
2538 (ShiftedC + 1).ashr(ShAmtVal) == (
C + 1))
2539 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2545 APInt ShiftedC = (
C + 1).shl(ShAmtVal) - 1;
2546 if ((ShiftedC + 1).ashr(ShAmtVal) == (
C + 1) ||
2547 (
C + 1).shl(ShAmtVal).isMinSignedValue())
2548 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2555 if (
C.getBitWidth() > 2 &&
C.getNumSignBits() <= ShAmtVal) {
2565 }
else if (!IsAShr) {
2569 APInt ShiftedC =
C.shl(ShAmtVal);
2570 if (ShiftedC.
lshr(ShAmtVal) ==
C)
2571 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2575 APInt ShiftedC = (
C + 1).shl(ShAmtVal) - 1;
2576 if ((ShiftedC + 1).lshr(ShAmtVal) == (
C + 1))
2577 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2581 if (!Cmp.isEquality())
2589 assert(((IsAShr &&
C.shl(ShAmtVal).ashr(ShAmtVal) ==
C) ||
2590 (!IsAShr &&
C.shl(ShAmtVal).lshr(ShAmtVal) ==
C)) &&
2591 "Expected icmp+shr simplify did not occur.");
2596 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy,
C << ShAmtVal));
2602 ConstantInt::get(ShrTy, (
C + 1).shl(ShAmtVal)));
2605 ConstantInt::get(ShrTy, (
C + 1).shl(ShAmtVal) - 1));
2612 Constant *Mask = ConstantInt::get(ShrTy, Val);
2614 return new ICmpInst(Pred,
And, ConstantInt::get(ShrTy,
C << ShAmtVal));
2637 const APInt *DivisorC;
2646 !
C.isStrictlyPositive()))
2652 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2656 return new ICmpInst(Pred,
And, ConstantInt::get(Ty,
C));
2683 assert(*C2 != 0 &&
"udiv 0, X should have been simplified already.");
2688 "icmp ugt X, UINT_MAX should have been simplified already.");
2690 ConstantInt::get(Ty, C2->
udiv(
C + 1)));
2695 assert(
C != 0 &&
"icmp ult X, 0 should have been simplified already.");
2697 ConstantInt::get(Ty, C2->
udiv(
C)));
2711 bool DivIsSigned = Div->
getOpcode() == Instruction::SDiv;
2721 if (Cmp.isEquality() && Div->
hasOneUse() &&
C.isSignBitSet() &&
2722 (!DivIsSigned ||
C.isMinSignedValue())) {
2747 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2766 bool ProdOV = (DivIsSigned ? Prod.
sdiv(*C2) : Prod.
udiv(*C2)) !=
C;
2779 int LoOverflow = 0, HiOverflow = 0;
2780 APInt LoBound, HiBound;
2785 HiOverflow = LoOverflow = ProdOV;
2794 LoBound = -(RangeSize - 1);
2795 HiBound = RangeSize;
2796 }
else if (
C.isStrictlyPositive()) {
2798 HiOverflow = LoOverflow = ProdOV;
2804 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2806 APInt DivNeg = -RangeSize;
2807 LoOverflow =
addWithOverflow(LoBound, HiBound, DivNeg,
true) ? -1 : 0;
2815 LoBound = RangeSize + 1;
2816 HiBound = -RangeSize;
2817 if (HiBound == *C2) {
2821 }
else if (
C.isStrictlyPositive()) {
2824 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2830 LoOverflow = HiOverflow = ProdOV;
2843 if (LoOverflow && HiOverflow)
2847 X, ConstantInt::get(Ty, LoBound));
2850 X, ConstantInt::get(Ty, HiBound));
2854 if (LoOverflow && HiOverflow)
2858 X, ConstantInt::get(Ty, LoBound));
2861 X, ConstantInt::get(Ty, HiBound));
2866 if (LoOverflow == +1)
2868 if (LoOverflow == -1)
2870 return new ICmpInst(Pred,
X, ConstantInt::get(Ty, LoBound));
2873 if (HiOverflow == +1)
2875 if (HiOverflow == -1)
2908 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2910 return new ICmpInst(SwappedPred,
Y, ConstantInt::get(Ty, SubResult));
2918 if (Cmp.isEquality() &&
C.isZero() &&
2954 (*C2 & (
C - 1)) == (
C - 1))
2967 return new ICmpInst(SwappedPred,
Add, ConstantInt::get(Ty, ~
C));
2973 auto FoldConstant = [&](
bool Val) {
2977 cast<VectorType>(Op0->
getType())->getElementCount(), Res);
2981 switch (Table.to_ulong()) {
2983 return FoldConstant(
false);
3013 return FoldConstant(
true);
3036 unsigned BW =
C.getBitWidth();
3037 std::bitset<4> Table;
3038 auto ComputeTable = [&](
bool Op0Val,
bool Op1Val) {
3041 Res += isa<ZExtInst>(Ext0) ? 1 : -1;
3043 Res += isa<ZExtInst>(Ext1) ? 1 : -1;
3047 Table[0] = ComputeTable(
false,
false);
3048 Table[1] = ComputeTable(
false,
true);
3049 Table[2] = ComputeTable(
true,
false);
3050 Table[3] = ComputeTable(
true,
true);
3065 if ((
Add->hasNoSignedWrap() &&
3067 (
Add->hasNoUnsignedWrap() &&
3071 Cmp.isSigned() ?
C.ssub_ov(*C2, Overflow) :
C.usub_ov(*C2, Overflow);
3077 return new ICmpInst(Pred,
X, ConstantInt::get(Ty, NewC));
3083 if (Cmp.isSigned()) {
3084 if (
Lower.isSignMask())
3086 if (
Upper.isSignMask())
3089 if (
Lower.isMinValue())
3091 if (
Upper.isMinValue())
3124 if (!
Add->hasOneUse())
3139 ConstantInt::get(Ty,
C * 2));
3154 ConstantInt::get(Ty, ~
C));
3174 Value *EqualVal = SI->getTrueValue();
3175 Value *UnequalVal = SI->getFalseValue();
3198 auto FlippedStrictness =
3200 PredB, cast<Constant>(RHS2));
3201 if (!FlippedStrictness)
3204 "basic correctness failure");
3205 RHS2 = FlippedStrictness->second;
3217 assert(
C &&
"Cmp RHS should be a constant int!");
3223 Value *OrigLHS, *OrigRHS;
3224 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3225 if (Cmp.hasOneUse() &&
3228 assert(C1LessThan && C2Equal && C3GreaterThan);
3231 C1LessThan->
getValue(),
C->getValue(), Cmp.getPredicate());
3233 Cmp.getPredicate());
3235 C3GreaterThan->
getValue(),
C->getValue(), Cmp.getPredicate());
3246 if (TrueWhenLessThan)
3252 if (TrueWhenGreaterThan)
3262 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3267 Value *Op1 = Cmp.getOperand(1);
3268 Value *BCSrcOp = Bitcast->getOperand(0);
3269 Type *SrcType = Bitcast->getSrcTy();
3270 Type *DstType = Bitcast->getType();
3290 return new ICmpInst(Pred,
X, ConstantInt::get(
X->getType(), 1));
3317 Type *XType =
X->getType();
3322 if (
auto *XVTy = dyn_cast<VectorType>(XType))
3336 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3337 Attribute::NoImplicitFloat) &&
3362 if (Cmp.isEquality() &&
C->isAllOnes() && Bitcast->hasOneUse()) {
3363 if (
Value *NotBCSrcOp =
3374 if (Cmp.isEquality() &&
C->isZero() && Bitcast->hasOneUse() &&
3376 if (
auto *VecTy = dyn_cast<FixedVectorType>(
X->getType())) {
3395 auto *VecTy = cast<VectorType>(SrcType);
3396 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3397 if (
C->isSplat(EltTy->getBitWidth())) {
3405 Value *NewC = ConstantInt::get(EltTy,
C->trunc(EltTy->getBitWidth()));
3406 return new ICmpInst(Pred, Extract, NewC);
3419 if (
auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3423 if (
auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3427 if (
auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3431 if (
auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3435 if (
auto *
II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3442 Value *Cmp0 = Cmp.getOperand(0);
3444 if (
C->isZero() && Cmp.isEquality() && Cmp0->
hasOneUse() &&
3446 m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
3449 m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
3451 return new ICmpInst(Cmp.getPredicate(),
X,
Y);
3466 if (!Cmp.isEquality())
3471 Constant *
RHS = cast<Constant>(Cmp.getOperand(1));
3475 case Instruction::SRem:
3486 case Instruction::Add: {
3490 if (
Constant *C2 = dyn_cast<Constant>(BOp1)) {
3493 }
else if (
C.isZero()) {
3496 if (
Value *NegVal = dyn_castNegVal(BOp1))
3497 return new ICmpInst(Pred, BOp0, NegVal);
3498 if (
Value *NegVal = dyn_castNegVal(BOp0))
3499 return new ICmpInst(Pred, NegVal, BOp1);
3508 return new ICmpInst(Pred, BOp0, Neg);
3513 case Instruction::Xor:
3514 if (
Constant *BOC = dyn_cast<Constant>(BOp1)) {
3518 }
else if (
C.isZero()) {
3520 return new ICmpInst(Pred, BOp0, BOp1);
3523 case Instruction::Or: {
3581 case Instruction::UDiv:
3582 case Instruction::SDiv:
3592 return new ICmpInst(Pred, BOp0, BOp1);
3595 Instruction::Mul, BO->
getOpcode() == Instruction::SDiv, BOp1,
3596 Cmp.getOperand(1), BO);
3600 return new ICmpInst(Pred, YC, BOp0);
3604 if (BO->
getOpcode() == Instruction::UDiv &&
C.isZero()) {
3607 return new ICmpInst(NewPred, BOp1, BOp0);
3621 "Non-ctpop intrin in ctpop fold");
3657 Type *Ty =
II->getType();
3661 switch (
II->getIntrinsicID()) {
3662 case Intrinsic::abs:
3665 if (
C.isZero() ||
C.isMinSignedValue())
3666 return new ICmpInst(Pred,
II->getArgOperand(0), ConstantInt::get(Ty,
C));
3669 case Intrinsic::bswap:
3671 return new ICmpInst(Pred,
II->getArgOperand(0),
3672 ConstantInt::get(Ty,
C.byteSwap()));
3674 case Intrinsic::bitreverse:
3676 return new ICmpInst(Pred,
II->getArgOperand(0),
3677 ConstantInt::get(Ty,
C.reverseBits()));
3679 case Intrinsic::ctlz:
3680 case Intrinsic::cttz: {
3683 return new ICmpInst(Pred,
II->getArgOperand(0),
3689 unsigned Num =
C.getLimitedValue(
BitWidth);
3691 bool IsTrailing =
II->getIntrinsicID() == Intrinsic::cttz;
3694 APInt Mask2 = IsTrailing
3698 ConstantInt::get(Ty, Mask2));
3703 case Intrinsic::ctpop: {
3706 bool IsZero =
C.isZero();
3708 return new ICmpInst(Pred,
II->getArgOperand(0),
3715 case Intrinsic::fshl:
3716 case Intrinsic::fshr:
3717 if (
II->getArgOperand(0) ==
II->getArgOperand(1)) {
3718 const APInt *RotAmtC;
3722 return new ICmpInst(Pred,
II->getArgOperand(0),
3723 II->getIntrinsicID() == Intrinsic::fshl
3724 ? ConstantInt::get(Ty,
C.rotr(*RotAmtC))
3725 : ConstantInt::get(Ty,
C.rotl(*RotAmtC)));
3729 case Intrinsic::umax:
3730 case Intrinsic::uadd_sat: {
3733 if (
C.isZero() &&
II->hasOneUse()) {
3740 case Intrinsic::ssub_sat:
3743 return new ICmpInst(Pred,
II->getArgOperand(0),
II->getArgOperand(1));
3745 case Intrinsic::usub_sat: {
3750 return new ICmpInst(NewPred,
II->getArgOperand(0),
II->getArgOperand(1));
3765 assert(Cmp.isEquality());
3768 Value *Op0 = Cmp.getOperand(0);
3769 Value *Op1 = Cmp.getOperand(1);
3770 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3771 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3772 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3775 switch (IIOp0->getIntrinsicID()) {
3776 case Intrinsic::bswap:
3777 case Intrinsic::bitreverse:
3780 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3781 case Intrinsic::fshl:
3782 case Intrinsic::fshr: {
3785 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3787 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3789 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
3790 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3796 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
3801 Builder.
CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
3803 Op0->
getType(), IIOp0->getIntrinsicID(),
3804 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
3805 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
3822 if (
auto *
II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3823 switch (
II->getIntrinsicID()) {
3826 case Intrinsic::fshl:
3827 case Intrinsic::fshr:
3828 if (Cmp.isEquality() &&
II->getArgOperand(0) ==
II->getArgOperand(1)) {
3830 if (
C.isZero() ||
C.isAllOnes())
3831 return new ICmpInst(Pred,
II->getArgOperand(0), Cmp.getOperand(1));
3845 case Instruction::Xor:
3849 case Instruction::And:
3853 case Instruction::Or:
3857 case Instruction::Mul:
3861 case Instruction::Shl:
3865 case Instruction::LShr:
3866 case Instruction::AShr:
3870 case Instruction::SRem:
3874 case Instruction::UDiv:
3878 case Instruction::SDiv:
3882 case Instruction::Sub:
3886 case Instruction::Add:
3904 if (!
II->hasOneUse())
3920 Value *Op0 =
II->getOperand(0);
3921 Value *Op1 =
II->getOperand(1);
3930 switch (
II->getIntrinsicID()) {
3933 "This function only works with usub_sat and uadd_sat for now!");
3934 case Intrinsic::uadd_sat:
3937 case Intrinsic::usub_sat:
3947 II->getBinaryOp(), *COp1,
II->getNoWrapKind());
3954 if (
II->getBinaryOp() == Instruction::Add)
3960 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
3962 std::optional<ConstantRange> Combination;
3963 if (CombiningOp == Instruction::BinaryOps::Or)
3975 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3980 ConstantInt::get(Op1->
getType(), EquivInt));
3987 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
3992 NewPredicate = Pred;
3996 else if (
C.isAllOnes())
4004 else if (
C.isZero())
4022 if (
I->getIntrinsicID() == Intrinsic::scmp)
4036 switch (
II->getIntrinsicID()) {
4039 case Intrinsic::uadd_sat:
4040 case Intrinsic::usub_sat:
4045 case Intrinsic::ctpop: {
4050 case Intrinsic::scmp:
4051 case Intrinsic::ucmp:
4057 if (Cmp.isEquality())
4060 Type *Ty =
II->getType();
4062 switch (
II->getIntrinsicID()) {
4063 case Intrinsic::ctpop: {
4075 case Intrinsic::ctlz: {
4078 unsigned Num =
C.getLimitedValue();
4081 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4086 unsigned Num =
C.getLimitedValue();
4089 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4093 case Intrinsic::cttz: {
4095 if (!
II->hasOneUse())
4115 case Intrinsic::ssub_sat:
4119 return new ICmpInst(Pred,
II->getArgOperand(0),
II->getArgOperand(1));
4123 II->getArgOperand(1));
4127 II->getArgOperand(1));
4139 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
4140 Constant *RHSC = dyn_cast<Constant>(Op1);
4146 case Instruction::PHI:
4150 case Instruction::IntToPtr:
4159 case Instruction::Load:
4162 dyn_cast<GetElementPtrInst>(LHSI->
getOperand(0)))
4178 auto SimplifyOp = [&](
Value *
Op,
bool SelectCondIsTrue) ->
Value * {
4182 SI->getCondition(), Pred,
Op,
RHS,
DL, SelectCondIsTrue))
4183 return ConstantInt::get(
I.getType(), *Impl);
4188 Value *Op1 = SimplifyOp(SI->getOperand(1),
true);
4190 CI = dyn_cast<ConstantInt>(Op1);
4192 Value *Op2 = SimplifyOp(SI->getOperand(2),
false);
4194 CI = dyn_cast<ConstantInt>(Op2);
4203 bool Transform =
false;
4206 else if (Op1 || Op2) {
4208 if (SI->hasOneUse())
4211 else if (CI && !CI->
isZero())
4230 unsigned Depth = 0) {
4233 if (V->getType()->getScalarSizeInBits() == 1)
4241 switch (
I->getOpcode()) {
4242 case Instruction::ZExt:
4245 case Instruction::SExt:
4249 case Instruction::And:
4250 case Instruction::Or:
4257 case Instruction::Xor:
4267 case Instruction::Select: