42#define DEBUG_TYPE "instcombine"
50 bool IsSigned =
false) {
53 Result = In1.
sadd_ov(In2, Overflow);
55 Result = In1.
uadd_ov(In2, Overflow);
63 bool IsSigned =
false) {
66 Result = In1.
ssub_ov(In2, Overflow);
68 Result = In1.
usub_ov(In2, Overflow);
76 for (
auto *U :
I.users())
98 }
else if (
C.isAllOnes()) {
129 const uint64_t ArrayElementCount = GlobalLoad->getElementCount();
130 if (ArrayElementCount >
CLOpts.maxarray_size)
133 enum { Overdefined = -3, Undefined = -2 };
142 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
146 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
154 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
159 uint64_t MagicBitvector = 0;
162 for (uint64_t i = 0; i < ArrayElementCount; i += 1) {
163 Constant *Elt = GlobalLoad->getElementAt(i);
183 if (TrueRangeEnd == (
int)i - 1)
185 if (FalseRangeEnd == (
int)i - 1)
202 if (FirstTrueElement == Undefined)
203 FirstTrueElement = TrueRangeEnd = i;
206 if (SecondTrueElement == Undefined)
207 SecondTrueElement = i;
209 SecondTrueElement = Overdefined;
212 if (TrueRangeEnd == (
int)i - 1)
215 TrueRangeEnd = Overdefined;
219 if (FirstFalseElement == Undefined)
220 FirstFalseElement = FalseRangeEnd = i;
223 if (SecondFalseElement == Undefined)
224 SecondFalseElement = i;
226 SecondFalseElement = Overdefined;
229 if (FalseRangeEnd == (
int)i - 1)
232 FalseRangeEnd = Overdefined;
237 if (i < 64 && IsTrueForElt)
238 MagicBitvector |= 1ULL << i;
242 if (i >= 64 && SecondTrueElement == Overdefined &&
243 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
244 FalseRangeEnd == Overdefined)
253 if (SecondTrueElement != Overdefined) {
256 if (FirstTrueElement == Undefined)
259 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
262 if (SecondTrueElement == Undefined)
267 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
269 return BinaryOperator::CreateOr(
C1, C2);
274 if (SecondFalseElement != Overdefined) {
277 if (FirstFalseElement == Undefined)
280 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
283 if (SecondFalseElement == Undefined)
288 Value *SecondFalseIdx =
289 ConstantInt::get(Idx->getType(), SecondFalseElement);
291 return BinaryOperator::CreateAnd(
C1, C2);
296 if (TrueRangeEnd != Overdefined) {
297 assert(TrueRangeEnd != FirstTrueElement &&
"Should emit single compare");
301 if (FirstTrueElement) {
303 Idx =
Builder.CreateAdd(Idx, Offs);
307 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
312 if (FalseRangeEnd != Overdefined) {
313 assert(FalseRangeEnd != FirstFalseElement &&
"Should emit single compare");
316 if (FirstFalseElement) {
318 Idx =
Builder.CreateAdd(Idx, Offs);
322 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
333 Type *Ty = GlobalLoad->getIndex()->getType();
334 if (ArrayElementCount > Ty->getIntegerBitWidth())
335 Ty =
DL.getSmallestLegalIntType(RHSC->
getContext(), ArrayElementCount);
340 V =
Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
341 V =
Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
366 while (!WorkList.
empty()) {
369 while (!WorkList.
empty()) {
370 if (Explored.
size() >= 100)
388 if (!
GEP->isInBounds() ||
count_if(
GEP->indices(), IsNonConst) > 1)
396 if (WorkList.
back() ==
V) {
412 for (
auto *PN : PHIs)
413 for (
Value *
Op : PN->incoming_values())
421 for (
Value *Val : Explored) {
427 if (Inst ==
Base || Inst ==
PHI || !Inst || !
PHI ||
431 if (
PHI->getParent() == Inst->getParent())
441 bool Before =
true) {
449 I = &*std::next(
I->getIterator());
450 Builder.SetInsertPoint(
I);
455 BasicBlock &Entry =
A->getParent()->getEntryBlock();
456 Builder.SetInsertPoint(Entry.getFirstInsertionPt());
478 Base->getContext(),
DL.getIndexTypeSizeInBits(Start->getType()));
484 for (
Value *Val : Explored) {
492 PHI->getName() +
".idx",
PHI->getIterator());
497 for (
Value *Val : Explored) {
506 NewInsts[
GEP] = OffsetV;
508 NewInsts[
GEP] = Builder.CreateAdd(
509 Op, OffsetV,
GEP->getOperand(0)->getName() +
".add",
521 for (
Value *Val : Explored) {
528 for (
unsigned I = 0,
E =
PHI->getNumIncomingValues();
I <
E; ++
I) {
529 Value *NewIncoming =
PHI->getIncomingValue(
I);
531 auto It = NewInsts.
find(NewIncoming);
532 if (It != NewInsts.
end())
533 NewIncoming = It->second;
540 for (
Value *Val : Explored) {
546 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(),
Base, NewInsts[Val],
547 Val->getName() +
".ptr", NW);
554 return NewInsts[Start];
640 if (
Base.Ptr == RHS && CanFold(
Base.LHSNW) && !
Base.isExpensive()) {
644 EmitGEPOffsets(
Base.LHSGEPs,
Base.LHSNW, IdxTy,
true);
652 RHS->getType()->getPointerAddressSpace())) {
683 if (GEPLHS->
getOperand(0) != GEPRHS->getOperand(0)) {
684 bool IndicesTheSame =
687 GEPRHS->getPointerOperand()->getType() &&
691 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
692 IndicesTheSame =
false;
698 if (IndicesTheSame &&
706 if (GEPLHS->
isInBounds() && GEPRHS->isInBounds() &&
708 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
712 Value *LOffset = EmitGEPOffset(GEPLHS);
713 Value *ROffset = EmitGEPOffset(GEPRHS);
720 if (LHSIndexTy != RHSIndexTy) {
723 ROffset =
Builder.CreateTrunc(ROffset, LHSIndexTy);
725 LOffset =
Builder.CreateTrunc(LOffset, RHSIndexTy);
734 if (GEPLHS->
getOperand(0) == GEPRHS->getOperand(0) &&
738 unsigned NumDifferences = 0;
739 unsigned DiffOperand = 0;
740 for (
unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
741 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
743 Type *RHSType = GEPRHS->getOperand(i)->getType();
754 if (NumDifferences++)
759 if (NumDifferences == 0)
767 Value *RHSV = GEPRHS->getOperand(DiffOperand);
768 return NewICmp(NW, LHSV, RHSV);
772 if (
Base.Ptr && !
Base.isExpensive()) {
774 bool DoFold = CanFold(
Base.LHSNW &
Base.RHSNW);
776 if (!DoFold &&
Base.Ptr->getType()->isPointerTy()) {
780 unsigned BW =
DL.getIndexTypeSizeInBits(GEPLHS->
getType());
785 DL, LOff,
true) ==
Base.Ptr &&
786 RHS->stripAndAccumulateConstantOffsets(
787 DL, ROff,
true) ==
Base.Ptr)
799 return NewICmp(
Base.LHSNW &
Base.RHSNW, L, R);
826 bool Captured =
false;
831 CmpCaptureTracker(
AllocaInst *Alloca) : Alloca(Alloca) {}
833 void tooManyUses()
override { Captured =
true; }
845 ICmps[ICmp] |= 1u << U->getOperandNo();
854 CmpCaptureTracker Tracker(Alloca);
856 if (Tracker.Captured)
860 for (
auto [ICmp,
Operands] : Tracker.ICmps) {
866 auto *Res = ConstantInt::get(ICmp->getType(),
892 assert(!!
C &&
"C should not be zero!");
908 ConstantInt::get(
X->getType(), -
C));
920 ConstantInt::get(
X->getType(),
SMax -
C));
931 ConstantInt::get(
X->getType(),
SMax - (
C - 1)));
940 assert(
I.isEquality() &&
"Cannot fold icmp gt/lt");
943 if (
I.getPredicate() ==
I.ICMP_NE)
945 return new ICmpInst(Pred, LHS, RHS);
964 return getICmp(
I.ICMP_UGT,
A,
965 ConstantInt::get(
A->getType(), AP2.
logBase2()));
977 if (IsAShr && AP1 == AP2.
ashr(Shift)) {
981 return getICmp(
I.ICMP_UGE,
A, ConstantInt::get(
A->getType(), Shift));
982 return getICmp(
I.ICMP_EQ,
A, ConstantInt::get(
A->getType(), Shift));
983 }
else if (AP1 == AP2.
lshr(Shift)) {
984 return getICmp(
I.ICMP_EQ,
A, ConstantInt::get(
A->getType(), Shift));
990 auto *TorF = ConstantInt::get(
I.getType(),
I.getPredicate() ==
I.ICMP_NE);
999 assert(
I.isEquality() &&
"Cannot fold icmp gt/lt");
1002 if (
I.getPredicate() ==
I.ICMP_NE)
1004 return new ICmpInst(Pred, LHS, RHS);
1013 if (!AP1 && AP2TrailingZeros != 0)
1016 ConstantInt::get(
A->getType(), AP2.
getBitWidth() - AP2TrailingZeros));
1024 if (Shift > 0 && AP2.
shl(Shift) == AP1)
1025 return getICmp(
I.ICMP_EQ,
A, ConstantInt::get(
A->getType(), Shift));
1029 auto *TorF = ConstantInt::get(
I.getType(),
I.getPredicate() ==
I.ICMP_NE);
1058 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1082 if (U == AddWithCst)
1100 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1108 Value *TruncA = Builder.CreateTrunc(
A, NewType,
A->getName() +
".trunc");
1109 Value *TruncB = Builder.CreateTrunc(
B, NewType,
B->getName() +
".trunc");
1110 CallInst *
Call = Builder.CreateCall(
F, {TruncA, TruncB},
"sadd");
1111 Value *
Add = Builder.CreateExtractValue(
Call, 0,
"sadd.result");
1129 if (!
I.isEquality())
1160 APInt(XBitWidth, XBitWidth - 1))))
1187 return new ICmpInst(Pred,
B, Cmp.getOperand(1));
1189 return new ICmpInst(Pred,
A, Cmp.getOperand(1));
1206 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
1218 return new ICmpInst(Pred,
Y, Cmp.getOperand(1));
1224 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
1227 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1235 return new ICmpInst(Pred,
Y, Cmp.getOperand(1));
1240 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
1256 return new ICmpInst(Pred, Stripped,
1269 const APInt *Mask, *Neg;
1285 auto *NewAnd =
Builder.CreateAnd(Num, *Mask);
1309 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1325 for (
Value *V : Phi->incoming_values()) {
1333 PHINode *NewPhi =
Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1334 for (
auto [V, Pred] :
zip(
Ops, Phi->blocks()))
1349 Value *
X = Cmp.getOperand(0), *
Y = Cmp.getOperand(1);
1382 if (Cmp.isEquality() || (IsSignBit &&
hasBranchUse(Cmp)))
1387 if (Cmp.hasOneUse() &&
1401 if (!
match(BI->getCondition(),
1406 if (
DT.dominates(Edge0, Cmp.getParent())) {
1407 if (
auto *V = handleDomCond(DomPred, DomC))
1411 if (
DT.dominates(Edge1, Cmp.getParent()))
1427 Type *SrcTy =
X->getType();
1428 unsigned DstBits =
Trunc->getType()->getScalarSizeInBits(),
1429 SrcBits = SrcTy->getScalarSizeInBits();
1433 if (shouldChangeType(
Trunc->getType(), SrcTy)) {
1434 if (
Trunc->hasNoSignedWrap())
1435 return new ICmpInst(Pred,
X, ConstantInt::get(SrcTy,
C.sext(SrcBits)));
1436 if (!Cmp.isSigned() &&
Trunc->hasNoUnsignedWrap())
1437 return new ICmpInst(Pred,
X, ConstantInt::get(SrcTy,
C.zext(SrcBits)));
1440 if (
C.isOne() &&
C.getBitWidth() > 1) {
1445 ConstantInt::get(V->getType(), 1));
1457 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1459 ConstantInt::get(SrcTy, DstBits - Pow2->
logBase2()));
1465 Pred,
Y, ConstantInt::get(SrcTy,
C.logBase2() - Pow2->
logBase2()));
1468 if (Cmp.isEquality() && (
Trunc->hasOneUse() ||
Trunc->hasNoUnsignedWrap())) {
1471 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1475 Constant *WideC = ConstantInt::get(SrcTy,
C.zext(SrcBits));
1484 if ((
Known.Zero |
Known.One).countl_one() >= SrcBits - DstBits) {
1486 APInt NewRHS =
C.zext(SrcBits);
1488 return new ICmpInst(Pred,
X, ConstantInt::get(SrcTy, NewRHS));
1500 DstBits == SrcBits - ShAmt) {
1517 bool YIsSExt =
false;
1520 unsigned NoWrapFlags =
cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1522 if (Cmp.isSigned()) {
1533 if (
X->getType() !=
Y->getType() &&
1534 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1536 if (!isDesirableIntType(
X->getType()->getScalarSizeInBits()) &&
1537 isDesirableIntType(
Y->getType()->getScalarSizeInBits())) {
1539 Pred = Cmp.getSwappedPredicate(Pred);
1544 else if (!Cmp.isSigned() &&
1558 Type *TruncTy = Cmp.getOperand(0)->getType();
1563 if (isDesirableIntType(TruncBits) &&
1564 !isDesirableIntType(
X->getType()->getScalarSizeInBits()))
1587 bool TrueIfSigned =
false;
1604 if (
Xor->hasOneUse()) {
1606 if (!Cmp.isEquality() && XorC->
isSignMask()) {
1607 Pred = Cmp.getFlippedSignednessPredicate();
1608 return new ICmpInst(Pred,
X, ConstantInt::get(
X->getType(),
C ^ *XorC));
1613 Pred = Cmp.getFlippedSignednessPredicate();
1614 Pred = Cmp.getSwappedPredicate(Pred);
1615 return new ICmpInst(Pred,
X, ConstantInt::get(
X->getType(),
C ^ *XorC));
1622 if (*XorC == ~
C && (
C + 1).isPowerOf2())
1625 if (*XorC ==
C && (
C + 1).isPowerOf2())
1630 if (*XorC == -
C &&
C.isPowerOf2())
1632 ConstantInt::get(
X->getType(), ~
C));
1634 if (*XorC ==
C && (-
C).isPowerOf2())
1636 ConstantInt::get(
X->getType(), ~
C));
1658 const APInt *ShiftC;
1663 Type *XType =
X->getType();
1669 return new ICmpInst(Pred,
Add, ConstantInt::get(XType, Bound));
1678 if (!Shift || !Shift->
isShift())
1686 unsigned ShiftOpcode = Shift->
getOpcode();
1687 bool IsShl = ShiftOpcode == Instruction::Shl;
1690 APInt NewAndCst, NewCmpCst;
1691 bool AnyCmpCstBitsShiftedOut;
1692 if (ShiftOpcode == Instruction::Shl) {
1697 if (Cmp.isSigned() && (C2.
isNegative() ||
C1.isNegative()))
1700 NewCmpCst =
C1.lshr(*C3);
1701 NewAndCst = C2.
lshr(*C3);
1702 AnyCmpCstBitsShiftedOut = NewCmpCst.
shl(*C3) !=
C1;
1703 }
else if (ShiftOpcode == Instruction::LShr) {
1708 NewCmpCst =
C1.shl(*C3);
1709 NewAndCst = C2.
shl(*C3);
1710 AnyCmpCstBitsShiftedOut = NewCmpCst.
lshr(*C3) !=
C1;
1716 assert(ShiftOpcode == Instruction::AShr &&
"Unknown shift opcode");
1717 NewCmpCst =
C1.shl(*C3);
1718 NewAndCst = C2.
shl(*C3);
1719 AnyCmpCstBitsShiftedOut = NewCmpCst.
ashr(*C3) !=
C1;
1720 if (NewAndCst.
ashr(*C3) != C2)
1724 if (AnyCmpCstBitsShiftedOut) {
1734 Shift->
getOperand(0), ConstantInt::get(
And->getType(), NewAndCst));
1735 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1736 ConstantInt::get(
And->getType(), NewCmpCst));
1743 if (Shift->
hasOneUse() &&
C1.isZero() && Cmp.isEquality() &&
1753 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1767 return new TruncInst(
And->getOperand(0), Cmp.getType());
1778 ConstantInt::get(
X->getType(), ~*C2));
1783 ConstantInt::get(
X->getType(), -*C2));
1786 if (!
And->hasOneUse())
1789 if (Cmp.isEquality() &&
C1.isZero()) {
1807 Constant *NegBOC = ConstantInt::get(
And->getType(), -NewC2);
1809 return new ICmpInst(NewPred,
X, NegBOC);
1823 (Cmp.isEquality() || (!
C1.isNegative() && !C2->
isNegative()))) {
1827 if (!Cmp.getType()->isVectorTy()) {
1828 Type *WideType = W->getType();
1830 Constant *ZextC1 = ConstantInt::get(WideType,
C1.zext(WideScalarBits));
1831 Constant *ZextC2 = ConstantInt::get(WideType, C2->
zext(WideScalarBits));
1833 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1844 if (!Cmp.isSigned() &&
C1.isZero() &&
And->getOperand(0)->hasOneUse() &&
1851 unsigned UsesRemoved = 0;
1852 if (
And->hasOneUse())
1854 if (
Or->hasOneUse())
1861 if (UsesRemoved >= RequireUsesRemoved) {
1865 One,
Or->getName());
1867 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1881 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1882 Attribute::NoImplicitFloat) &&
1885 Type *FPType = V->getType()->getScalarType();
1886 if (FPType->isIEEELikeFPTy() && (
C1.isZero() ||
C1 == *C2)) {
1887 APInt ExponentMask =
1889 if (*C2 == ExponentMask) {
1890 unsigned Mask =
C1.isZero()
1924 Constant *MinSignedC = ConstantInt::get(
1928 return new ICmpInst(NewPred,
X, MinSignedC);
1944 if (!Cmp.isEquality())
1954 if (
C.getBitWidth() > 1 && (
C.isZero() ||
C.isOne()) &&
1958 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(1));
1962 return new TruncInst(MatchedX, Cmp.getType());
1966 if (
And->hasOneUse()) {
1975 if (Cmp.getOperand(1) ==
Y &&
C.isNegatedPowerOf2()) {
1986 X->getType()->isIntOrIntVectorTy(1) && (
C.isZero() ||
C.isOne())) {
1992 return BinaryOperator::CreateAnd(TruncY,
X);
2010 const APInt *Addend, *Msk;
2014 APInt NewComperand = (
C - *Addend) & *Msk;
2015 Value *MaskA =
Builder.CreateAnd(
A, ConstantInt::get(
A->getType(), *Msk));
2017 ConstantInt::get(MaskA->
getType(), NewComperand));
2039 while (!WorkList.
empty()) {
2040 auto MatchOrOperatorArgument = [&](
Value *OrOperatorArgument) {
2043 if (
match(OrOperatorArgument,
2049 if (
match(OrOperatorArgument,
2059 Value *OrOperatorLhs, *OrOperatorRhs;
2061 if (!
match(CurrentValue,
2066 MatchOrOperatorArgument(OrOperatorRhs);
2067 MatchOrOperatorArgument(OrOperatorLhs);
2073 CmpValues.
rbegin()->second);
2075 for (
auto It = CmpValues.
rbegin() + 1; It != CmpValues.
rend(); ++It) {
2076 Value *RhsCmp = Builder.CreateICmp(
Pred, It->first, It->second);
2077 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2093 ConstantInt::get(V->getType(), 1));
2096 Value *OrOp0 =
Or->getOperand(0), *OrOp1 =
Or->getOperand(1);
2103 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(),
C));
2104 return new ICmpInst(Pred, OrOp0, NewC);
2116 if (
match(OrOp1,
m_APInt(MaskC)) && Cmp.isEquality()) {
2117 if (*MaskC ==
C && (
C + 1).isPowerOf2()) {
2122 return new ICmpInst(Pred, OrOp0, OrOp1);
2129 if (
Or->hasOneUse()) {
2131 Constant *NewC = ConstantInt::get(
Or->getType(),
C ^ (*MaskC));
2143 Constant *NewC = ConstantInt::get(
X->getType(), TrueIfSigned ? 1 : 0);
2171 if (!Cmp.isEquality() || !
C.isZero() || !
Or->hasOneUse())
2202 if (
X ==
Mul->getOperand(1) && !Cmp.isSigned()) {
2204 bool IsSqr =
C == R * R;
2207 if (Cmp.isEquality() &&
2208 (
Mul->hasNoUnsignedWrap() || (
Mul->hasNoSignedWrap() &&
C.isZero()))) {
2216 return new ICmpInst(Pred,
X, ConstantInt::get(MulTy, R));
2221 if (
Mul->hasNoUnsignedWrap()) {
2224 return new ICmpInst(Pred,
X, ConstantInt::get(MulTy, R));
2238 return new ICmpInst(Cmp.getStrictPredicate(),
X,
2239 ConstantInt::get(MulTy, R));
2262 if (Cmp.isEquality()) {
2264 if (
Mul->hasNoSignedWrap() &&
C.srem(*MulC).isZero()) {
2265 Constant *NewC = ConstantInt::get(MulTy,
C.sdiv(*MulC));
2273 if (
C.urem(*MulC).isZero()) {
2276 if ((*MulC & 1).isOne() ||
Mul->hasNoUnsignedWrap()) {
2277 Constant *NewC = ConstantInt::get(MulTy,
C.udiv(*MulC));
2290 if (
C.isMinSignedValue() && MulC->
isAllOnes())
2296 NewC = ConstantInt::get(
2300 "Unexpected predicate");
2301 NewC = ConstantInt::get(
2306 NewC = ConstantInt::get(
2310 "Unexpected predicate");
2311 NewC = ConstantInt::get(
2316 return NewC ?
new ICmpInst(Pred,
X, NewC) :
nullptr;
2328 unsigned TypeBits =
C.getBitWidth();
2330 if (Cmp.isUnsigned()) {
2335 bool CIsPowerOf2 = Rem.
isZero() &&
Div.isPowerOf2();
2349 unsigned CLog2 =
Div.logBase2();
2350 return new ICmpInst(
Pred,
Y, ConstantInt::get(ShiftType, CLog2));
2351 }
else if (Cmp.isSigned() && C2->
isOne()) {
2352 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2373 const APInt *ShiftVal;
2403 const APInt *ShiftAmt;
2409 unsigned TypeBits =
C.getBitWidth();
2410 if (ShiftAmt->
uge(TypeBits))
2422 APInt ShiftedC =
C.ashr(*ShiftAmt);
2423 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2426 C.ashr(*ShiftAmt).shl(*ShiftAmt) ==
C) {
2427 APInt ShiftedC =
C.ashr(*ShiftAmt);
2428 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2435 assert(!
C.isMinSignedValue() &&
"Unexpected icmp slt");
2436 APInt ShiftedC = (
C - 1).ashr(*ShiftAmt) + 1;
2437 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2447 APInt ShiftedC =
C.lshr(*ShiftAmt);
2448 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2451 C.lshr(*ShiftAmt).shl(*ShiftAmt) ==
C) {
2452 APInt ShiftedC =
C.lshr(*ShiftAmt);
2453 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2460 assert(
C.ugt(0) &&
"ult 0 should have been eliminated");
2461 APInt ShiftedC = (
C - 1).lshr(*ShiftAmt) + 1;
2462 return new ICmpInst(Pred,
X, ConstantInt::get(ShType, ShiftedC));
2466 if (Cmp.isEquality() && Shl->
hasOneUse()) {
2472 Constant *LShrC = ConstantInt::get(ShType,
C.lshr(*ShiftAmt));
2477 bool TrueIfSigned =
false;
2489 if (Cmp.isUnsigned() && Shl->
hasOneUse()) {
2491 if ((
C + 1).isPowerOf2() &&
2499 if (
C.isPowerOf2() &&
2529 Pred, ConstantInt::get(ShType->
getContext(),
C))) {
2530 CmpPred = FlippedStrictness->first;
2538 ConstantInt::get(TruncTy, RHSC.
ashr(*ShiftAmt).
trunc(TypeBits - Amt));
2540 Builder.CreateTrunc(
X, TruncTy,
"",
false,
2557 if (Cmp.isEquality() && Shr->
isExact() &&
C.isZero())
2558 return new ICmpInst(Pred,
X, Cmp.getOperand(1));
2560 bool IsAShr = Shr->
getOpcode() == Instruction::AShr;
2561 const APInt *ShiftValC;
2563 if (Cmp.isEquality())
2581 assert(ShiftValC->
uge(
C) &&
"Expected simplify of compare");
2582 assert((IsUGT || !
C.isZero()) &&
"Expected X u< 0 to simplify");
2584 unsigned CmpLZ = IsUGT ?
C.countl_zero() : (
C - 1).
countl_zero();
2592 const APInt *ShiftAmtC;
2598 unsigned TypeBits =
C.getBitWidth();
2600 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2603 bool IsExact = Shr->
isExact();
2611 (
C - 1).isPowerOf2() &&
C.countLeadingZeros() > ShAmtVal) {
2617 APInt ShiftedC = (
C - 1).shl(ShAmtVal) + 1;
2618 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2624 APInt ShiftedC =
C.shl(ShAmtVal);
2625 if (ShiftedC.
ashr(ShAmtVal) ==
C)
2626 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2630 APInt ShiftedC = (
C + 1).shl(ShAmtVal) - 1;
2631 if (!
C.isMaxSignedValue() && !(
C + 1).shl(ShAmtVal).isMinSignedValue() &&
2632 (ShiftedC + 1).ashr(ShAmtVal) == (
C + 1))
2633 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2639 APInt ShiftedC = (
C + 1).shl(ShAmtVal) - 1;
2640 if ((ShiftedC + 1).ashr(ShAmtVal) == (
C + 1) ||
2641 (
C + 1).shl(ShAmtVal).isMinSignedValue())
2642 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2649 if (
C.getBitWidth() > 2 &&
C.getNumSignBits() <= ShAmtVal) {
2659 }
else if (!IsAShr) {
2663 APInt ShiftedC =
C.shl(ShAmtVal);
2664 if (ShiftedC.
lshr(ShAmtVal) ==
C)
2665 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2669 APInt ShiftedC = (
C + 1).shl(ShAmtVal) - 1;
2670 if ((ShiftedC + 1).lshr(ShAmtVal) == (
C + 1))
2671 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy, ShiftedC));
2675 if (!Cmp.isEquality())
2683 assert(((IsAShr &&
C.shl(ShAmtVal).ashr(ShAmtVal) ==
C) ||
2684 (!IsAShr &&
C.shl(ShAmtVal).lshr(ShAmtVal) ==
C)) &&
2685 "Expected icmp+shr simplify did not occur.");
2690 return new ICmpInst(Pred,
X, ConstantInt::get(ShrTy,
C << ShAmtVal));
2696 Constant *Mask = ConstantInt::get(ShrTy, Val);
2698 return new ICmpInst(Pred,
And, ConstantInt::get(ShrTy,
C << ShAmtVal));
2715 const APInt *DivisorC;
2724 "ult X, 0 should have been simplified already.");
2729 if (!NormalizedC.
uge(DivisorC->
abs() - 1))
2752 const APInt *DivisorC;
2761 !
C.isStrictlyPositive()))
2767 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2771 return new ICmpInst(Pred,
And, ConstantInt::get(Ty,
C));
2798 assert(*C2 != 0 &&
"udiv 0, X should have been simplified already.");
2803 "icmp ugt X, UINT_MAX should have been simplified already.");
2805 ConstantInt::get(Ty, C2->
udiv(
C + 1)));
2810 assert(
C != 0 &&
"icmp ult X, 0 should have been simplified already.");
2812 ConstantInt::get(Ty, C2->
udiv(
C)));
2826 bool DivIsSigned =
Div->getOpcode() == Instruction::SDiv;
2836 if (Cmp.isEquality() &&
Div->hasOneUse() &&
C.isSignBitSet() &&
2837 (!DivIsSigned ||
C.isMinSignedValue())) {
2838 Value *XBig =
Builder.CreateICmp(Pred,
X, ConstantInt::get(Ty,
C));
2839 Value *YOne =
Builder.CreateICmp(Pred,
Y, ConstantInt::get(Ty, 1));
2865 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2869 DivIsSigned =
false;
2888 bool ProdOV = (DivIsSigned ? Prod.
sdiv(*C2) : Prod.
udiv(*C2)) !=
C;
2901 int LoOverflow = 0, HiOverflow = 0;
2902 APInt LoBound, HiBound;
2907 HiOverflow = LoOverflow = ProdOV;
2916 LoBound = -(RangeSize - 1);
2917 HiBound = RangeSize;
2918 }
else if (
C.isStrictlyPositive()) {
2920 HiOverflow = LoOverflow = ProdOV;
2926 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2928 APInt DivNeg = -RangeSize;
2929 LoOverflow =
addWithOverflow(LoBound, HiBound, DivNeg,
true) ? -1 : 0;
2937 LoBound = RangeSize + 1;
2938 HiBound = -RangeSize;
2939 if (HiBound == *C2) {
2943 }
else if (
C.isStrictlyPositive()) {
2946 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2952 LoOverflow = HiOverflow = ProdOV;
2965 if (LoOverflow && HiOverflow)
2969 X, ConstantInt::get(Ty, LoBound));
2972 X, ConstantInt::get(Ty, HiBound));
2976 if (LoOverflow && HiOverflow)
2980 X, ConstantInt::get(Ty, LoBound));
2983 X, ConstantInt::get(Ty, HiBound));
2988 if (LoOverflow == +1)
2990 if (LoOverflow == -1)
2992 return new ICmpInst(Pred,
X, ConstantInt::get(Ty, LoBound));
2995 if (HiOverflow == +1)
2997 if (HiOverflow == -1)
3039 bool HasNSW =
Sub->hasNoSignedWrap();
3040 bool HasNUW =
Sub->hasNoUnsignedWrap();
3042 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3044 return new ICmpInst(SwappedPred,
Y, ConstantInt::get(Ty, SubResult));
3052 if (Cmp.isEquality() &&
C.isZero() &&
3053 none_of((
Sub->users()), [](
const User *U) { return isa<PHINode>(U); }))
3061 if (!
Sub->hasOneUse())
3064 if (
Sub->hasNoSignedWrap()) {
3088 (*C2 & (
C - 1)) == (
C - 1))
3101 return new ICmpInst(SwappedPred,
Add, ConstantInt::get(Ty, ~
C));
3107 auto FoldConstant = [&](
bool Val) {
3108 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3115 switch (
Table.to_ulong()) {
3117 return FoldConstant(
false);
3119 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) :
nullptr;
3121 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) :
nullptr;
3123 return Builder.CreateNot(Op0);
3125 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) :
nullptr;
3127 return Builder.CreateNot(Op1);
3129 return Builder.CreateXor(Op0, Op1);
3131 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) :
nullptr;
3133 return Builder.CreateAnd(Op0, Op1);
3135 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) :
nullptr;
3139 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) :
nullptr;
3143 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) :
nullptr;
3145 return Builder.CreateOr(Op0, Op1);
3147 return FoldConstant(
true);
3162 Cmp.getType() !=
A->getType() || Cmp.getType() !=
B->getType())
3165 std::bitset<4>
Table;
3166 auto ComputeTable = [&](
bool First,
bool Second) -> std::optional<bool> {
3170 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3174 return std::nullopt;
3177 for (
unsigned I = 0;
I < 4; ++
I) {
3178 bool First = (
I >> 1) & 1;
3179 bool Second =
I & 1;
3180 if (
auto Res = ComputeTable(
First, Second))
3196 bool HasNUW,
bool HasNSW,
3199 Type *Ty =
X->getType();
3206 APInt NewC =
C.usub_ov(C2, Overflow);
3210 return new ICmpInst(Pred,
X, ConstantInt::get(Ty, NewC));
3218 APInt NewC =
C.ssub_ov(C2, Overflow);
3222 return new ICmpInst(ChosenPred,
X, ConstantInt::get(Ty, NewC));
3226 (
C - C2).isNonNegative() &&
3229 .isAllNonNegative())
3231 ConstantInt::get(Ty,
C - C2));
3246 const APInt *ShAmtC;
3254 return new ICmpInst(Pred,
A, ConstantInt::get(
A->getType(),
C));
3264 Cmp,
X, *C2,
Add->hasNoUnsignedWrap(),
Add->hasNoSignedWrap(),
C))
3270 if (Cmp.isSigned()) {
3271 if (
Lower.isSignMask())
3273 if (
Upper.isSignMask())
3276 if (
Lower.isMinValue())
3278 if (
Upper.isMinValue())
3311 if (!
Add->hasOneUse())
3326 ConstantInt::get(Ty,
C * 2));
3340 Builder.CreateAdd(
X, ConstantInt::get(Ty, *C2 -
C - 1)),
3341 ConstantInt::get(Ty, ~
C));
3346 Type *NewCmpTy = V->getType();
3348 if (shouldChangeType(Ty, NewCmpTy)) {
3359 :
Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3360 ConstantInt::get(NewCmpTy, EquivInt));
3382 Value *EqualVal =
SI->getTrueValue();
3383 Value *UnequalVal =
SI->getFalseValue();
3406 auto FlippedStrictness =
3408 if (!FlippedStrictness)
3411 "basic correctness failure");
3412 RHS2 = FlippedStrictness->second;
3424 assert(
C &&
"Cmp RHS should be a constant int!");
3430 Value *OrigLHS, *OrigRHS;
3431 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3432 if (Cmp.hasOneUse() &&
3435 assert(C1LessThan && C2Equal && C3GreaterThan);
3438 C1LessThan->
getValue(),
C->getValue(), Cmp.getPredicate());
3440 Cmp.getPredicate());
3442 C3GreaterThan->
getValue(),
C->getValue(), Cmp.getPredicate());
3453 if (TrueWhenLessThan)
3459 if (TrueWhenGreaterThan)
3474 Value *Op1 = Cmp.getOperand(1);
3475 Value *BCSrcOp = Bitcast->getOperand(0);
3476 Type *SrcType = Bitcast->getSrcTy();
3477 Type *DstType = Bitcast->getType();
3481 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3482 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3497 return new ICmpInst(Pred,
X, ConstantInt::get(
X->getType(), 1));
3524 Type *XType =
X->getType();
3527 if (!(XType->
isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3542 Type *FPType = SrcType->getScalarType();
3543 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3544 Attribute::NoImplicitFloat) &&
3545 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3551 Builder.createIsFPClass(BCSrcOp, Mask));
3574 if (!
match(Cmp.getOperand(1),
m_APInt(
C)) || !DstType->isIntegerTy() ||
3575 !SrcType->isIntOrIntVectorTy())
3585 if (Cmp.isEquality() &&
C->isAllOnes() && Bitcast->hasOneUse()) {
3586 if (
Value *NotBCSrcOp =
3588 Value *Cast =
Builder.CreateBitCast(NotBCSrcOp, DstType);
3597 if (Cmp.isEquality() &&
C->isZero() && Bitcast->hasOneUse() &&
3600 Type *NewType =
Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3620 if (
C->isSplat(EltTy->getBitWidth())) {
3626 Value *Extract =
Builder.CreateExtractElement(Vec, Mask[0]);
3627 Value *NewC = ConstantInt::get(EltTy,
C->trunc(EltTy->getBitWidth()));
3628 return new ICmpInst(Pred, Extract, NewC);
3666 if (
match(Cmp.getOperand(0),
3672 bool ValidPred =
true;
3690 X->getType()->getScalarType()->getFltSemantics();
3693 if (!Exp.isNegative() && Exp.sle(MaxExp + 1) &&
3695 int ExpVal =
static_cast<int>(Exp.getSExtValue());
3700 ConstantFP::get(
X->getType(), CmpConst));
3709 Value *Cmp0 = Cmp.getOperand(0);
3711 if (
C->isZero() && Cmp.isEquality() && Cmp0->
hasOneUse() &&
3718 return new ICmpInst(Cmp.getPredicate(),
X,
Y);
3733 if (!Cmp.isEquality())
3742 case Instruction::SRem:
3753 case Instruction::Add: {
3760 }
else if (
C.isZero()) {
3763 if (
Value *NegVal = dyn_castNegVal(BOp1))
3764 return new ICmpInst(Pred, BOp0, NegVal);
3765 if (
Value *NegVal = dyn_castNegVal(BOp0))
3766 return new ICmpInst(Pred, NegVal, BOp1);
3775 return new ICmpInst(Pred, BOp0, Neg);
3780 case Instruction::Xor:
3785 }
else if (
C.isZero()) {
3787 return new ICmpInst(Pred, BOp0, BOp1);
3790 case Instruction::Or: {
3811 Cond->getType() == Cmp.getType()) {
3849 case Instruction::UDiv:
3850 case Instruction::SDiv:
3860 return new ICmpInst(Pred, BOp0, BOp1);
3863 Instruction::Mul, BO->
getOpcode() == Instruction::SDiv, BOp1,
3864 Cmp.getOperand(1), BO);
3868 return new ICmpInst(Pred, YC, BOp0);
3872 if (BO->
getOpcode() == Instruction::UDiv &&
C.isZero()) {
3875 return new ICmpInst(NewPred, BOp1, BOp0);
3889 "Non-ctpop intrin in ctpop fold");
3924 Type *Ty =
II->getType();
3928 switch (
II->getIntrinsicID()) {
3929 case Intrinsic::abs:
3932 if (
C.isZero() ||
C.isMinSignedValue())
3933 return new ICmpInst(Pred,
II->getArgOperand(0), ConstantInt::get(Ty,
C));
3936 case Intrinsic::bswap:
3938 return new ICmpInst(Pred,
II->getArgOperand(0),
3939 ConstantInt::get(Ty,
C.byteSwap()));
3941 case Intrinsic::bitreverse:
3943 return new ICmpInst(Pred,
II->getArgOperand(0),
3944 ConstantInt::get(Ty,
C.reverseBits()));
3946 case Intrinsic::ctlz:
3947 case Intrinsic::cttz: {
3950 return new ICmpInst(Pred,
II->getArgOperand(0),
3956 unsigned Num =
C.getLimitedValue(
BitWidth);
3958 bool IsTrailing =
II->getIntrinsicID() == Intrinsic::cttz;
3961 APInt Mask2 = IsTrailing
3965 ConstantInt::get(Ty, Mask2));
3970 case Intrinsic::ctpop: {
3973 bool IsZero =
C.isZero();
3975 return new ICmpInst(Pred,
II->getArgOperand(0),
3982 case Intrinsic::fshl:
3983 case Intrinsic::fshr:
3984 if (
II->getArgOperand(0) ==
II->getArgOperand(1)) {
3985 const APInt *RotAmtC;
3989 return new ICmpInst(Pred,
II->getArgOperand(0),
3990 II->getIntrinsicID() == Intrinsic::fshl
3991 ? ConstantInt::get(Ty,
C.rotr(*RotAmtC))
3992 : ConstantInt::get(Ty,
C.rotl(*RotAmtC)));
3996 case Intrinsic::umax:
3997 case Intrinsic::uadd_sat: {
4000 if (
C.isZero() &&
II->hasOneUse()) {
4007 case Intrinsic::ssub_sat:
4012 if (
C.isZero() &&
II->getType()->getScalarSizeInBits() > 1)
4013 return new ICmpInst(Pred,
II->getArgOperand(0),
II->getArgOperand(1));
4015 case Intrinsic::usub_sat: {
4020 return new ICmpInst(NewPred,
II->getArgOperand(0),
II->getArgOperand(1));
4035 assert(Cmp.isEquality());
4038 Value *Op0 = Cmp.getOperand(0);
4039 Value *Op1 = Cmp.getOperand(1);
4042 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4045 switch (IIOp0->getIntrinsicID()) {
4046 case Intrinsic::bswap:
4047 case Intrinsic::bitreverse:
4050 return new ICmpInst(
Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4051 case Intrinsic::fshl:
4052 case Intrinsic::fshr: {
4055 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
4057 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
4059 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
4060 return new ICmpInst(
Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4066 const unsigned BW = IIOp0->getType()->getScalarSizeInBits();
4067 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4076 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
4077 Value *CombinedRotate = Builder.CreateIntrinsic(
4078 Op0->
getType(), IIOp0->getIntrinsicID(),
4079 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
4080 return new ICmpInst(
Pred, IIOp1->getOperand(0), CombinedRotate);
4099 switch (
II->getIntrinsicID()) {
4102 case Intrinsic::fshl:
4103 case Intrinsic::fshr:
4104 if (Cmp.isEquality() &&
II->getArgOperand(0) ==
II->getArgOperand(1)) {
4106 if (
C.isZero() ||
C.isAllOnes())
4107 return new ICmpInst(Pred,
II->getArgOperand(0), Cmp.getOperand(1));
4121 case Instruction::Xor:
4125 case Instruction::And:
4129 case Instruction::Or:
4133 case Instruction::Mul:
4137 case Instruction::Shl:
4141 case Instruction::LShr:
4142 case Instruction::AShr:
4146 case Instruction::SRem:
4150 case Instruction::UDiv:
4154 case Instruction::SDiv:
4158 case Instruction::Sub:
4162 case Instruction::Add:
4186 if (!
II->hasOneUse())
4202 Value *Op0 =
II->getOperand(0);
4203 Value *Op1 =
II->getOperand(1);
4212 switch (
II->getIntrinsicID()) {
4215 "This function only works with usub_sat and uadd_sat for now!");
4216 case Intrinsic::uadd_sat:
4219 case Intrinsic::usub_sat:
4229 II->getBinaryOp(), *COp1,
II->getNoWrapKind());
4236 if (
II->getBinaryOp() == Instruction::Add)
4242 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4244 std::optional<ConstantRange> Combination;
4245 if (CombiningOp == Instruction::BinaryOps::Or)
4246 Combination =
C1.exactUnionWith(C2);
4248 Combination =
C1.exactIntersectWith(C2);
4257 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4261 Builder.CreateAdd(Op0, ConstantInt::get(Op1->
getType(), EquivOffset)),
4262 ConstantInt::get(Op1->
getType(), EquivInt));
4269 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4274 NewPredicate =
Pred;
4278 else if (
C.isAllOnes())
4286 else if (
C.isZero())
4303 if (!
C.isZero() && !
C.isAllOnes())
4314 if (
I->getIntrinsicID() == Intrinsic::scmp)
4328 switch (
II->getIntrinsicID()) {
4331 case Intrinsic::uadd_sat:
4332 case Intrinsic::usub_sat:
4337 case Intrinsic::ctpop: {
4342 case Intrinsic::scmp:
4343 case Intrinsic::ucmp:
4349 if (Cmp.isEquality())
4352 Type *Ty =
II->getType();
4354 switch (
II->getIntrinsicID()) {
4355 case Intrinsic::ctpop: {
4367 case Intrinsic::ctlz: {
4370 unsigned Num =
C.getLimitedValue();
4373 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4378 unsigned Num =
C.getLimitedValue();
4381 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4385 case Intrinsic::cttz: {
4387 if (!
II->hasOneUse())
4394 Builder.CreateAnd(
II->getArgOperand(0), Mask),
4402 Builder.CreateAnd(
II->getArgOperand(0), Mask),
4407 case Intrinsic::ssub_sat:
4414 return new ICmpInst(Pred,
II->getArgOperand(0),
II->getArgOperand(1));
4418 II->getArgOperand(1));
4422 II->getArgOperand(1));
4425 case Intrinsic::abs: {
4426 if (!
II->hasOneUse())
4435 Builder.CreateAdd(
X, ConstantInt::get(Ty,
C)),
4436 ConstantInt::get(Ty, 2 *
C));
4443 Builder.CreateAdd(
X, ConstantInt::get(Ty,
C - 1)),
4444 ConstantInt::get(Ty, 2 * (
C - 1)));
4457 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
4466 case Instruction::Select: {
4473 Instruction::PtrToAddr, RHSC,
DL.getIndexType(RHSC->
getType()),
DL);
4474 if (!RHSIndexBits || !RHSIndexBits->
isNullValue())
4479 if (!
SI->hasOneUse() || !
SI->getCondition()->hasOneUse())
4486 if (!
match(
SI->getCondition(),
4499 case Instruction::IntToPtr:
4504 APInt NullPtrValue =
4512 case Instruction::Load:
4527 auto SimplifyOp = [&](
Value *
Op,
bool SelectCondIsTrue) ->
Value * {
4531 SI->getCondition(), Pred,
Op, RHS,
DL, SelectCondIsTrue))
4532 return ConstantInt::get(
I.getType(), *Impl);
4537 Value *Op1 = SimplifyOp(
SI->getOperand(1),
true);
4541 Value *Op2 = SimplifyOp(
SI->getOperand(2),
false);
4545 auto Simplifies = [&](
Value *
Op,
unsigned Idx) {
4560 bool Transform =
false;
4563 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4565 if (
SI->hasOneUse())
4568 else if (CI && !CI->
isZero())
4576 Op1 =
Builder.CreateICmp(Pred,
SI->getOperand(1), RHS,
I.getName());
4578 Op2 =
Builder.CreateICmp(Pred,
SI->getOperand(2), RHS,
I.getName());
4596 if (C1SatisfiesCond && !C2SatisfiesCond) {
4600 Value *Cmp2 =
Builder.CreateICmp(Pred, RHS,
SI->getFalseValue());
4602 return BinaryOperator::CreateOr(Cmp1, Cmp2);
4603 return BinaryOperator::CreateAnd(Cmp1, Cmp2);
4613 unsigned Depth = 0) {
4616 if (
V->getType()->getScalarSizeInBits() == 1)
4624 switch (
I->getOpcode()) {
4625 case Instruction::ZExt:
4628 case Instruction::SExt:
4632 case Instruction::And:
4633 case Instruction::Or:
4640 case Instruction::Xor:
4650 case Instruction::Select:
4654 case Instruction::Shl:
4657 case Instruction::LShr:
4660 case Instruction::AShr:
4664 case Instruction::Add:
4670 case Instruction::Sub:
4676 case Instruction::Call: {
4678 switch (
II->getIntrinsicID()) {
4681 case Intrinsic::umax:
4682 case Intrinsic::smax:
4683 case Intrinsic::umin:
4684 case Intrinsic::smin:
4689 case Intrinsic::bitreverse:
4779 auto IsLowBitMask = [&]() {
4797 auto Check = [&]() {
4815 auto Check = [&]() {
4834 if (!IsLowBitMask())
4870 const APInt &MaskedBits = *
C0;
4871 assert(MaskedBits != 0 &&
"shift by zero should be folded away already.");
4892 auto *XType =
X->getType();
4893 const unsigned XBitWidth = XType->getScalarSizeInBits();
4895 assert(
BitWidth.ugt(MaskedBits) &&
"shifts should leave some bits untouched");
4908 Value *T0 = Builder.CreateAdd(
X, ConstantInt::get(XType, AddCst));
4910 Value *
T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4926 !
I.getOperand(0)->hasOneUse())
4951 assert(NarrowestTy ==
I.getOperand(0)->getType() &&
4952 "We did not look past any shifts while matching XShift though.");
4953 bool HadTrunc = WidestTy !=
I.getOperand(0)->getType();
4960 auto XShiftOpcode = XShift->
getOpcode();
4961 if (XShiftOpcode == YShift->
getOpcode())
4964 Value *
X, *XShAmt, *
Y, *YShAmt;
4973 if (!
match(
I.getOperand(0),
4999 unsigned MaximalPossibleTotalShiftAmount =
5002 APInt MaximalRepresentableShiftAmount =
5004 if (MaximalRepresentableShiftAmount.
ult(MaximalPossibleTotalShiftAmount))
5013 if (NewShAmt->getType() != WidestTy) {
5023 if (!
match(NewShAmt,
5025 APInt(WidestBitWidth, WidestBitWidth))))
5030 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
5036 ? NewShAmt->getSplatValue()
5039 if (NewShAmtSplat &&
5047 unsigned MinLeadZero =
Known.countMinLeadingZeros();
5049 unsigned MaxActiveBits =
Known.getBitWidth() - MinLeadZero;
5050 if (MaxActiveBits <= 1)
5058 unsigned MinLeadZero =
Known.countMinLeadingZeros();
5060 unsigned MaxActiveBits =
Known.getBitWidth() - MinLeadZero;
5061 if (MaxActiveBits <= 1)
5064 if (NewShAmtSplat) {
5067 if (AdjNewShAmt.
ule(MinLeadZero))
5078 X = Builder.CreateZExt(
X, WidestTy);
5079 Y = Builder.CreateZExt(
Y, WidestTy);
5081 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5082 ? Builder.CreateLShr(
X, NewShAmt)
5083 : Builder.CreateShl(
X, NewShAmt);
5084 Value *
T1 = Builder.CreateAnd(T0,
Y);
5085 return Builder.CreateICmp(
I.getPredicate(),
T1,
5103 if (!
I.isEquality() &&
5113 NeedNegation =
false;
5116 NeedNegation =
true;
5122 if (
I.isEquality() &&
5137 bool MulHadOtherUses =
Mul && !
Mul->hasOneUse();
5138 if (MulHadOtherUses)
5142 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5143 : Intrinsic::smul_with_overflow,
5144 X->getType(), {X, Y},
nullptr,
"mul");
5149 if (MulHadOtherUses)
5154 Res =
Builder.CreateNot(Res,
"mul.not.ov");
5158 if (MulHadOtherUses)
5184 Type *Ty =
X->getType();
5188 Value *
And = Builder.CreateAnd(
X, MaxSignedVal);
5198 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1), *
A;
5260 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1), *
A;
5295 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1), *
A;
5311 return new ICmpInst(PredOut, Op0, Op1);
5331 return new ICmpInst(NewPred, Op0, Const);
5343 if (!
C.isPowerOf2())
5350 bool &HasNSW,
bool &HasNUW) {
5358 if (BO.
getOpcode() == Instruction::Or) {
5380 bool Op0HasNSW =
false, Op0HasNUW =
false;
5381 bool Op1HasNSW =
false, Op1HasNUW =
false;
5382 bool NoOp0WrapProblem =
hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5383 bool NoOp1WrapProblem =
hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5390 if (!NoOp0WrapProblem || !NoOp1WrapProblem)
5420 if (BO0->getOpcode() != BO1->getOpcode())
5423 A = BO0->getOperand(0);
5424 B = BO0->getOperand(1);
5425 C = BO1->getOperand(0);
5426 D = BO1->getOperand(1);
5428 switch (BO0->getOpcode()) {
5431 case Instruction::Sub:
5432 if (!NoOp0WrapProblem || !NoOp1WrapProblem)
5449 case Instruction::Mul: {
5452 if (IsEquality || !NoOp0WrapProblem || !NoOp1WrapProblem)
5462 }
else if (
A ==
D) {
5467 }
else if (
B ==
C) {
5472 }
else if (
B ==
D) {
5499 if (!BO0->hasOneUse() && !BO1->hasOneUse())
5507 switch (BO0->getOpcode()) {
5510 case Instruction::Shl: {
5511 bool NUW = Op0HasNUW && Op1HasNUW;
5512 bool NSW = Op0HasNSW && Op1HasNSW;
5515 if (!NSW && IsSigned)
5520 case Instruction::LShr:
5521 return !IsSigned && BO0->isExact() && BO1->isExact();
5522 case Instruction::AShr:
5523 return BO0->isExact() && BO1->isExact();
5524 case Instruction::UDiv:
5525 return !IsSigned && BO0->isExact() && BO1->isExact();
5526 case Instruction::SDiv:
5527 if (!BO0->isExact() || !BO1->isExact())
5542 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
5557 Value *Dividend, *Divisor;
5558 if (
I.isEquality() &&
5563 return new ICmpInst(NewPred, Dividend, Divisor);
5635 bool NoOp0WrapProblem =
false, NoOp1WrapProblem =
false;
5636 bool Op0HasNUW =
false, Op1HasNUW =
false;
5637 bool Op0HasNSW =
false, Op1HasNSW =
false;
5640 Value *
A =
nullptr, *
B =
nullptr, *
C =
nullptr, *
D =
nullptr;
5653 if ((
A == Op1 ||
B == Op1) && NoOp0WrapProblem)
5659 if ((
C == Op0 ||
D == Op0) && NoOp1WrapProblem)
5667 return new ICmpInst(Pred, LHS, RHS);
5673 bool IsNegative) ->
bool {
5674 const APInt *OffsetC;
5686 if (!
C.isStrictlyPositive())
5713 if (
A && NoOp0WrapProblem && IsAddOrSignedPred &&
5714 ShareCommonDivisor(
A, Op1,
B, IsNegative))
5724 if (
C && NoOp1WrapProblem &&
5725 ShareCommonDivisor(Op0,
C,
D,
5738 if (
A &&
C && NoOp0WrapProblem && NoOp1WrapProblem &&
5740 const APInt *AP1, *AP2;
5748 if (AP1Abs.
uge(AP2Abs)) {
5749 APInt Diff = *AP1 - *AP2;
5752 A, C3,
"", Op0HasNUW && Diff.
ule(*AP1), Op0HasNSW);
5755 APInt Diff = *AP2 - *AP1;
5758 C, C3,
"", Op1HasNUW && Diff.
ule(*AP2), Op1HasNSW);
5777 if (BO0 && BO0->
getOpcode() == Instruction::Sub) {
5781 if (BO1 && BO1->
getOpcode() == Instruction::Sub) {
5787 if (
A == Op1 && NoOp0WrapProblem)
5790 if (
C == Op0 && NoOp1WrapProblem)
5814 if (RHSC->isNotMinSignedValue())
5815 return new ICmpInst(
I.getSwappedPredicate(),
X,
5833 if (Op0HasNSW && Op1HasNSW) {
5835 SQ.getWithInstruction(&
I));
5840 SQ.getWithInstruction(&
I));
5841 if (GreaterThan &&
match(GreaterThan,
m_One()))
5847 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5859 if (NonZero && Op0HasNSW && Op1HasNSW)
5864 if (NonZero && Op0HasNUW && Op1HasNUW)
5875 else if (BO1 && BO1->
getOpcode() == Instruction::SRem &&
5905 case Instruction::Add:
5906 case Instruction::Sub:
5907 case Instruction::Xor: {
5914 if (
C->isSignMask()) {
5920 if (BO0->
getOpcode() == Instruction::Xor &&
C->isMaxSignedValue()) {
5922 NewPred =
I.getSwappedPredicate(NewPred);
5928 case Instruction::Mul: {
5929 if (!
I.isEquality())
5937 if (
unsigned TZs =
C->countr_zero()) {
5943 return new ICmpInst(Pred, And1, And2);
6008 auto IsCondKnownTrue = [](
Value *Val) -> std::optional<bool> {
6010 return std::nullopt;
6015 return std::nullopt;
6021 Pred = Pred.dropSameSign();
6024 if (!CmpXZ.has_value() && !CmpYZ.has_value())
6026 if (!CmpXZ.has_value()) {
6032 if (CmpYZ.has_value())
6056 if (!MinMaxCmpXZ.has_value()) {
6064 if (!MinMaxCmpXZ.has_value())
6080 return FoldIntoCmpYZ();
6107 return FoldIntoCmpYZ();
6116 return FoldIntoCmpYZ();
6148 const APInt *
Lo =
nullptr, *
Hi =
nullptr;
6171 I,
Builder.CreateICmp(Pred,
X, ConstantInt::get(
X->getType(),
C)));
6177 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
6181 if (
I.isEquality()) {
6216 Type *Ty =
A->getType();
6217 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop,
A);
6219 ConstantInt::get(Ty, 2))
6221 ConstantInt::get(Ty, 1));
6228using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6230 bool AllowRecursion) {
6236 case Instruction::Add:
6237 Offsets.emplace_back(Instruction::Sub, Inst->
getOperand(1));
6238 Offsets.emplace_back(Instruction::Sub, Inst->
getOperand(0));
6240 case Instruction::Sub:
6241 Offsets.emplace_back(Instruction::Add, Inst->
getOperand(1));
6243 case Instruction::Xor:
6244 Offsets.emplace_back(Instruction::Xor, Inst->
getOperand(1));
6245 Offsets.emplace_back(Instruction::Xor, Inst->
getOperand(0));
6247 case Instruction::Shl:
6249 Offsets.emplace_back(Instruction::AShr, Inst->
getOperand(1));
6251 Offsets.emplace_back(Instruction::LShr, Inst->
getOperand(1));
6253 case Instruction::Select:
6254 if (AllowRecursion) {
6301 assert(
I.isEquality() &&
"Expected an equality icmp");
6302 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
6313 case Instruction::AShr: {
6314 const APInt *CV, *CRHS;
6316 CV->
ashr(*CRHS).
shl(*CRHS) == *CV) &&
6322 case Instruction::LShr: {
6323 const APInt *CV, *CRHS;
6325 CV->
lshr(*CRHS).
shl(*CRHS) == *CV) &&
6344 auto ApplyOffset = [&](
Value *
V,
unsigned BinOpc,
6347 if (!Sel->hasOneUse())
6349 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc,
RHS);
6352 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc,
RHS);
6357 if (
Value *Simplified = ApplyOffsetImpl(
V, BinOpc,
RHS))
6362 for (
auto [BinOp,
RHS] : OffsetOps) {
6363 auto BinOpc =
static_cast<unsigned>(BinOp);
6365 auto Op0Result = ApplyOffset(Op0, BinOpc,
RHS);
6366 if (!Op0Result.isValid())
6368 auto Op1Result = ApplyOffset(Op1, BinOpc,
RHS);
6369 if (!Op1Result.isValid())
6372 Value *NewLHS = Op0Result.materialize(Builder);
6373 Value *NewRHS = Op1Result.materialize(Builder);
6374 return new ICmpInst(
I.getPredicate(), NewLHS, NewRHS);
6381 if (!
I.isEquality())
6384 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
6388 if (
A == Op1 ||
B == Op1) {
6389 Value *OtherVal =
A == Op1 ?
B :
A;
6417 Value *OtherVal =
A == Op0 ?
B :
A;
6424 Value *
X =
nullptr, *
Y =
nullptr, *Z =
nullptr;
6430 }
else if (
A ==
D) {
6434 }
else if (
B ==
C) {
6438 }
else if (
B ==
D) {
6450 (*
C0 ^ *
C1).isNegatedPowerOf2();
6456 int(Op0->
hasOneUse()) + int(Op1->hasOneUse()) +
6458 if (XorIsNegP2 || UseCnt >= 2) {
6461 Op1 =
Builder.CreateAnd(Op1, Z);
6481 (Op0->
hasOneUse() || Op1->hasOneUse())) {
6486 MaskC->
countr_one() ==
A->getType()->getScalarSizeInBits())
6492 const APInt *AP1, *AP2;
6501 if (ShAmt < TypeBits && ShAmt != 0) {
6506 return new ICmpInst(NewPred,
Xor, ConstantInt::get(
A->getType(), CmpVal));
6516 if (ShAmt < TypeBits && ShAmt != 0) {
6536 if (ShAmt < ASize) {
6559 A->getType()->getScalarSizeInBits() ==
BitWidth * 2 &&
6560 (
I.getOperand(0)->hasOneUse() ||
I.getOperand(1)->hasOneUse())) {
6565 Add, ConstantInt::get(
A->getType(),
C.shl(1)));
6592 Builder.CreateIntrinsic(Op0->
getType(), Intrinsic::fshl, {A, A, B}));
6607 std::optional<bool> IsZero = std::nullopt;
6649 Constant *
C = ConstantInt::get(Res->X->getType(), Res->C);
6653 unsigned SrcBits =
X->getType()->getScalarSizeInBits();
6655 if (
II->getIntrinsicID() == Intrinsic::cttz ||
6656 II->getIntrinsicID() == Intrinsic::ctlz) {
6657 unsigned MaxRet = SrcBits;
6683 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6684 bool IsSignedCmp = ICmp.
isSigned();
6692 if (IsZext0 != IsZext1) {
6697 if (ICmp.
isEquality() &&
X->getType()->isIntOrIntVectorTy(1) &&
6698 Y->getType()->isIntOrIntVectorTy(1))
6708 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6709 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6711 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6718 Type *XTy =
X->getType(), *YTy =
Y->getType();
6725 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6727 X =
Builder.CreateCast(CastOpcode,
X, YTy);
6729 Y =
Builder.CreateCast(CastOpcode,
Y, XTy);
6741 if (IsSignedCmp && IsSignedExt)
6754 Type *SrcTy = CastOp0->getSrcTy();
6762 if (IsSignedExt && IsSignedCmp)
6793 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.
getOperand(0));
6794 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.
getOperand(1));
6795 if (SimplifiedOp0 || SimplifiedOp1)
6797 SimplifiedOp0 ? SimplifiedOp0 : ICmp.
getOperand(0),
6798 SimplifiedOp1 ? SimplifiedOp1 : ICmp.
getOperand(1));
6807 Value *Op0Src = CastOp0->getOperand(0);
6808 Type *SrcTy = CastOp0->getSrcTy();
6809 Type *DestTy = CastOp0->getDestTy();
6813 auto CompatibleSizes = [&](
Type *PtrTy,
Type *IntTy) {
6814 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6815 unsigned IndexWidth =
DL.getAddressSizeInBits(PtrTy);
6816 unsigned PtrWidth =
DL.getPointerTypeSizeInBits(PtrTy);
6819 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6823 Value *NewOp1 =
nullptr;
6825 NewOp1 = PtrToIntOp1->getOperand(0);
6828 NewOp1 = PtrToAddrOp1->getOperand(0);
6835 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6841 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6842 CompatibleSizes(DestTy, SrcTy)) {
6843 Value *NewOp1 =
nullptr;
6845 Value *IntSrc = IntToPtrOp1->getOperand(0);
6847 NewOp1 = IntToPtrOp1->getOperand(0);
6867 case Instruction::Add:
6868 case Instruction::Sub:
6870 case Instruction::Mul:
6871 return !(
RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6883 case Instruction::Add:
6888 case Instruction::Sub:
6893 case Instruction::Mul:
6902 bool IsSigned,
Value *LHS,
6913 Builder.SetInsertPoint(&OrigI);
6930 Result = Builder.CreateBinOp(BinaryOp,
LHS,
RHS);
6931 Result->takeName(&OrigI);
6935 Result = Builder.CreateBinOp(BinaryOp,
LHS,
RHS);
6936 Result->takeName(&OrigI);
6940 Inst->setHasNoSignedWrap();
6942 Inst->setHasNoUnsignedWrap();
6967 const APInt *OtherVal,
6975 unsigned Opcode = Instr->getOpcode();
6976 assert(Opcode == Instruction::Add || Opcode == Instruction::Mul);
6983 Type *TyA =
A->getType(), *TyB =
B->getType();
6985 WidthB = TyB->getPrimitiveSizeInBits();
6986 unsigned ResultWidth;
6988 if (WidthB > WidthA) {
6989 ResultWidth = WidthB;
6992 ResultWidth = WidthA;
7005 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
7006 if (TruncWidth > ResultWidth)
7010 if (BO->getOpcode() != Instruction::And)
7013 const APInt &CVal = CI->getValue();
7029 switch (
I.getPredicate()) {
7036 if (MaxVal.
eq(*OtherVal))
7046 if (MaxVal.
eq(*OtherVal))
7059 Value *ResultA =
A, *ResultB =
B;
7060 if (WidthA < ResultWidth)
7061 ResultA = Builder.CreateZExt(
A, ResultType);
7062 if (WidthB < ResultWidth)
7063 ResultB = Builder.CreateZExt(
B, ResultType);
7066 Value *OverflowCheck;
7068 if (Opcode == Instruction::Add) {
7070 ArithResult = Builder.CreateAdd(ResultA, ResultB,
"add");
7074 Builder.CreateICmpUGE(ArithResult, ResultA,
"not.add.overflow");
7077 Builder.CreateICmpULT(ArithResult, ResultA,
"add.overflow");
7080 Value *
Call = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow,
7081 ResultType, {ResultA, ResultB},
7083 ArithResult = Builder.CreateExtractValue(
Call, 0,
"umul.value");
7084 OverflowCheck = Builder.CreateExtractValue(
Call, 1,
"umul.overflow");
7086 OverflowCheck = Builder.CreateNot(OverflowCheck);
7097 if (TI->getType()->getPrimitiveSizeInBits() == ResultWidth)
7102 assert(BO->getOpcode() == Instruction::And);
7106 Value *ShortAnd = Builder.CreateAnd(ArithResult, ShortMask);
7107 Value *Zext = Builder.CreateZExt(ShortAnd, BO->
getType());
7133 switch (
I.getPredicate()) {
7164 assert(DI && UI &&
"Instruction not defined\n");
7175 if (Usr != UI && !
DT.dominates(DB, Usr->getParent()))
7190 if (!IC || (IC->getOperand(0) !=
SI && IC->getOperand(1) !=
SI))
7237 const unsigned SIOpd) {
7238 assert((SIOpd == 1 || SIOpd == 2) &&
"Invalid select operand!");
7240 BasicBlock *Succ =
SI->getParent()->getTerminator()->getSuccessor(1);
7254 SI->replaceUsesOutsideBlock(
SI->getOperand(SIOpd),
SI->getParent());
7264 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
7269 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7270 ? Ty->getScalarSizeInBits()
7271 :
DL.getPointerTypeSizeInBits(Ty->getScalarType());
7295 if (
I.hasSameSign() &&
I.isUnsigned()) {
7297 if (To.isNegative() || To.isNonNegative())
7302 To.makeNonNegative();
7304 PropagateSignBit(Op0Known, Op1Known);
7305 PropagateSignBit(Op1Known, Op0Known);
7340 if (!Cmp.hasOneUse())
7349 if (!isMinMaxCmp(
I)) {
7354 if (Op1Min == Op0Max)
7359 if (*CmpC == Op0Min + 1)
7361 ConstantInt::get(Op1->getType(), *CmpC - 1));
7371 if (Op1Max == Op0Min)
7376 if (*CmpC == Op0Max - 1)
7378 ConstantInt::get(Op1->getType(), *CmpC + 1));
7388 if (Op1Min == Op0Max)
7392 if (*CmpC == Op0Min + 1)
7394 ConstantInt::get(Op1->getType(), *CmpC - 1));
7399 if (Op1Max == Op0Min)
7403 if (*CmpC == Op0Max - 1)
7405 ConstantInt::get(Op1->getType(), *CmpC + 1));
7422 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7425 Value *LHS =
nullptr;
7428 *LHSC != Op0KnownZeroInverted)
7434 Type *XTy =
X->getType();
7435 unsigned Log2C1 =
C1->countr_zero();
7436 APInt C2 = Op0KnownZeroInverted;
7443 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7453 (Op0Known & Op1Known) == Op0Known)
7459 if (Op1Min == Op0Max)
7463 if (Op1Max == Op0Min)
7467 if (Op1Min == Op0Max)
7471 if (Op1Max == Op0Min)
7479 if ((
I.isSigned() || (
I.isUnsigned() && !
I.hasSameSign())) &&
7482 I.setPredicate(
I.getUnsignedPredicate());
7500 return BinaryOperator::CreateAnd(
Builder.CreateIsNull(
X),
Y);
7506 return BinaryOperator::CreateOr(
Builder.CreateIsNull(
X),
Y);
7517 bool IsSExt = ExtI->
getOpcode() == Instruction::SExt;
7519 auto CreateRangeCheck = [&] {
7534 }
else if (!IsSExt || HasOneUse) {
7539 return CreateRangeCheck();
7541 }
else if (IsSExt ?
C->isAllOnes() :
C->isOne()) {
7549 }
else if (!IsSExt || HasOneUse) {
7554 return CreateRangeCheck();
7568 Instruction::ICmp, Pred1,
X,
7587 Value *Op0 =
I.getOperand(0);
7588 Value *Op1 =
I.getOperand(1);
7594 if (!FlippedStrictness)
7598 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7599 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7618 I.setName(
I.getName() +
".not");
7629 Value *
A =
I.getOperand(0), *
B =
I.getOperand(1);
7630 assert(
A->getType()->isIntOrIntVectorTy(1) &&
"Bools only");
7636 switch (
I.getPredicate()) {
7645 switch (
I.getPredicate()) {
7655 switch (
I.getPredicate()) {
7664 return BinaryOperator::CreateXor(
A,
B);
7672 return BinaryOperator::CreateAnd(Builder.CreateNot(
A),
B);
7680 return BinaryOperator::CreateAnd(Builder.CreateNot(
B),
A);
7688 return BinaryOperator::CreateOr(Builder.CreateNot(
A),
B);
7696 return BinaryOperator::CreateOr(Builder.CreateNot(
B),
A);
7744 Value *NewX = Builder.CreateLShr(
X,
Y,
X->getName() +
".highbits");
7752 Value *
LHS = Cmp.getOperand(0), *
RHS = Cmp.getOperand(1);
7756 Value *
V = Builder.CreateCmp(
Pred,
X,
Y, Cmp.getName());
7758 I->copyIRFlags(&Cmp);
7759 Module *M = Cmp.getModule();
7761 M, Intrinsic::vector_reverse,
V->getType());
7768 (
LHS->hasOneUse() ||
RHS->hasOneUse()))
7769 return createCmpReverse(
Pred,
V1, V2);
7777 return createCmpReverse(
Pred,
LHS, V2);
7786 Type *V1Ty =
V1->getType();
7788 V1Ty == V2->
getType() && (
LHS->hasOneUse() ||
RHS->hasOneUse())) {
7802 Constant *ScalarC =
C->getSplatValue(
true);
7821 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
7827 if (
match(Op0, UAddOvResultPat) &&
7838 (Op0 ==
A || Op0 ==
B))
7848 if (!
I.getOperand(0)->getType()->isPointerTy() ||
7850 I.getParent()->getParent(),
7851 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7855 if (
match(
I.getOperand(0),
7871 Value *Const =
I.getOperand(1);
7889 Type *VecEltTy = VecTy->getElementType();
7891 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7892 if (!
DL.fitsInLegalInteger(ScalarBW))
7896 ? ConstantInt::get(ScalarTy, 0)
7899 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7911 if (
I.getType()->isVectorTy())
7934 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7937 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7939 if (!
DL.isLegalInteger(NumBits))
7943 auto *ScalarTy = Builder.getIntNTy(NumBits);
7944 LHS = Builder.CreateBitCast(
LHS, ScalarTy,
LHS->getName() +
".scalar");
7945 RHS = Builder.CreateBitCast(
RHS, ScalarTy,
RHS->getName() +
".scalar");
7963 case Instruction::GetElementPtr:
7967 case Instruction::Select:
7970 case Instruction::Call: {
7997 bool IsIntMinPosion =
C->isAllOnesValue();
8009 CtxI, IsIntMinPosion
8010 ?
Builder.CreateICmpSGT(
X, AllOnesValue)
8012 X, ConstantInt::get(
X->getType(),
SMin + 1)));
8018 CtxI, IsIntMinPosion
8019 ?
Builder.CreateICmpSLT(
X, NullValue)
8021 X, ConstantInt::get(
X->getType(),
SMin)));
8042 case Instruction::Add: {
8051 case Instruction::And:
8052 case Instruction::Or: {
8059 case Instruction::UDiv:
8060 case Instruction::SDiv: {
8062 auto CheckUGT1 = [](
const APInt &Divisor) {
return Divisor.ugt(1); };
8076 case Instruction::LShr:
8077 case Instruction::AShr: {
8079 auto CheckNE0 = [](
const APInt &Shift) {
return !Shift.isZero(); };
8093 case Instruction::Shl: {
8101 if (ShAmt >=
X->getType()->getScalarSizeInBits())
8103 if (canEvaluateShifted(Op1, ShAmt,
false,
8105 Value *NewOp1 = getShiftedValue(Op1, ShAmt,
false,
8113 if (ShAmt >=
X->getType()->getScalarSizeInBits())
8115 if (canEvaluateShifted(Op1, ShAmt,
false,
8117 Value *NewOp1 = getShiftedValue(Op1, ShAmt,
false,
8130 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
8137 if (Op0Cplxity < Op1Cplxity) {
8200 if (
C->isNonNegative())
8204 ConstantInt::get(
X->getType(), ~*
C));
8210 if (
C->isNonNegative())
8214 ConstantInt::get(
X->getType(), ~*
C));
8270 if (
I.isCommutative()) {
8271 if (
auto Pair = matchSymmetricPair(
I.getOperand(0),
I.getOperand(1))) {
8300 (Op0->
hasOneUse() || Op1->hasOneUse())) {
8328 bool I0NUW = I0->hasNoUnsignedWrap();
8329 bool I1NUW = I1->hasNoUnsignedWrap();
8330 bool I0NSW = I0->hasNoSignedWrap();
8331 bool I1NSW = I1->hasNoSignedWrap();
8335 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8337 ConstantInt::get(Op0->
getType(), 0));
8344 assert(Op1->getType()->isPointerTy() &&
8345 "Comparing pointer with non-pointer?");
8369 Type *SmallType =
X->getType();
8371 if (Mask->isMask(SmallWidth) &&
8372 shouldChangeType(
I.getOperand(0)->getType(), SmallType)) {
8374 return new ICmpInst(
I.getUnsignedPredicate(), NewTrunc,
X);
8392 bool ConsumesOp0, ConsumesOp1;
8395 (ConsumesOp0 || ConsumesOp1)) {
8398 assert(InvOp0 && InvOp1 &&
8399 "Mismatch between isFreeToInvert and getFreelyInverted");
8400 return new ICmpInst(
I.getSwappedPredicate(), InvOp0, InvOp1);
8412 if (AddI->
getOpcode() == Instruction::Add &&
8413 OptimizeOverflowCheck(Instruction::Add,
false,
X,
Y, *AddI,
8414 Result, Overflow)) {
8434 if ((
I.isUnsigned() ||
I.isEquality()) &&
8437 Y->getType()->getScalarSizeInBits() == 1 &&
8438 (Op0->
hasOneUse() || Op1->hasOneUse())) {
8445 unsigned ShiftOpc = ShiftI->
getOpcode();
8446 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8447 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8481 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8488 if (
I.getType()->isVectorTy())
8507 Type *InputTy =
A->getType();
8511 APInt TruncC1 =
C1->trunc(InputBitWidth);
8514 TruncC1.
setBit(InputBitWidth - 1);
8518 ConstantInt::get(InputTy, C2->
trunc(InputBitWidth)));
8538 if (MantissaWidth == -1)
8545 if (
I.isEquality()) {
8547 bool IsExact =
false;
8548 APSInt RHSCvt(IntWidth, LHSUnsigned);
8557 if (*RHS != RHSRoundInt) {
8577 if ((
int)IntWidth > MantissaWidth) {
8579 int Exp =
ilogb(*RHS);
8582 if (MaxExponent < (
int)IntWidth - !LHSUnsigned)
8588 if (MantissaWidth <= Exp && Exp <= (
int)IntWidth - !LHSUnsigned)
8597 assert(!RHS->isNaN() &&
"NaN comparison not already folded!");
8600 switch (
I.getPredicate()) {
8691 APSInt RHSInt(IntWidth, LHSUnsigned);
8694 if (!RHS->isZero()) {
8709 if (RHS->isNegative())
8715 if (RHS->isNegative())
8721 if (RHS->isNegative())
8728 if (!RHS->isNegative())
8734 if (RHS->isNegative())
8740 if (RHS->isNegative())
8746 if (RHS->isNegative())
8753 if (!RHS->isNegative())
8772 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
8780 if (
I.getType() !=
C1->getType() ||
I.getType() != C2->
getType())
8783 unsigned Pred =
I.getPredicate();
8791 if (!Res00 || !Res01 || !Res10 || !Res11)
8800 std::bitset<4>
Table;
8858 if (
C->isNegative())
8859 Pred =
I.getSwappedPredicate();
8886 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8892 bool RoundDown =
false;
8913 auto NextValue = [](
const APFloat &
Value,
bool RoundDown) {
8915 NextValue.
next(RoundDown);
8919 APFloat NextCValue = NextValue(*CValue, RoundDown);
8924 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8925 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8932 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8933 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8935 ExtNextCValue = ExtCValue + Bias;
8942 C.getType()->getScalarType()->getFltSemantics();
8945 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8946 if (MidValue != *CValue)
8947 ExtMidValue.
next(!RoundDown);
8955 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8959 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8960 if (ConvertFltSema(NextExtMidValue, SrcFltSema).
isFinite())
8965 ConstantFP::get(DestType, ExtMidValue),
"", &
I);
8978 if (!
C->isPosZero()) {
8979 if (!
C->isSmallestNormalized())
8992 switch (
I.getPredicate()) {
9018 switch (
I.getPredicate()) {
9043 assert(!
I.hasNoNaNs() &&
"fcmp should have simplified");
9048 assert(!
I.hasNoNaNs() &&
"fcmp should have simplified");
9062 return replacePredAndOp0(&
I,
I.getPredicate(),
X);
9085 I.setHasNoInfs(
false);
9087 switch (
I.getPredicate()) {
9132 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
9139 Pred =
I.getSwappedPredicate();
9185 I.getFunction()->getDenormalMode(
9192 I.setHasNoNaNs(
true);
9217 if (MantissaWidth != -1 &&
ilogb(*
C) < MantissaWidth) {
9219 I.setPredicate(
I.getSwappedPredicate());
9256 if (!IsStrictLt && !IsStrictGt && !IsGe)
9278 }
else if (
match(FAbsArg,
9286 if (
A->getType() !=
B->getType())
9301 Type *OpType =
LHS->getType();
9307 if (!FloorX && !CeilX) {
9311 Pred =
I.getSwappedPredicate();
9387 if (!
I || !(
I->getOpcode() == Instruction::SIToFP ||
9388 I->getOpcode() == Instruction::UIToFP))
9391 bool IsUnsigned =
I->getOpcode() == Instruction::UIToFP;
9392 unsigned BitWidth =
I->getOperand(0)->getType()->getScalarSizeInBits();
9415 Value *Op0 =
I.getOperand(0), *Op1 =
I.getOperand(1);
9417 SQ.getWithInstruction(&
I)))
9422 assert(OpType == Op1->getType() &&
"fcmp with different-typed operands?");
9447 if (
I.isCommutative()) {
9448 if (
auto Pair = matchSymmetricPair(
I.getOperand(0),
I.getOperand(1))) {
9472 return new FCmpInst(
I.getSwappedPredicate(),
X,
Y,
"", &
I);
9488 bool IsRedundantMinMaxClamp =
9550 X->getType()->isIntOrIntVectorTy() &&
9551 !
F.getDenormalMode(Op1->getType()->getScalarType()->getFltSemantics())
9552 .inputsMayBeZero()) {
9560 Type *IntTy =
X->getType();
9561 const APInt &SignMask =
~APInt::getSignMask(IntTy->getScalarSizeInBits());
9562 Value *MaskX =
Builder.CreateAnd(
X, ConstantInt::get(IntTy, SignMask));
9572 case Instruction::Select:
9582 case Instruction::FSub:
9587 case Instruction::PHI:
9591 case Instruction::SIToFP:
9592 case Instruction::UIToFP:
9596 case Instruction::FDiv:
9600 case Instruction::Load:
9605 case Instruction::FPTrunc:
9633 return new FCmpInst(
I.getSwappedPredicate(),
X, NegC,
"", &
I);
9647 X->getType() ==
Y->getType())
9658 X->getType()->getScalarType()->getFltSemantics();
9694 Constant *NewC = ConstantFP::get(
X->getType(), TruncC);
9707 Type *IntType =
Builder.getIntNTy(
X->getType()->getScalarSizeInBits());
9720 Value *CanonLHS =
nullptr;
9723 if (CanonLHS == Op1)
9724 return new FCmpInst(Pred, Op1, Op1,
"", &
I);
9726 Value *CanonRHS =
nullptr;
9729 if (CanonRHS == Op0)
9730 return new FCmpInst(Pred, Op0, Op0,
"", &
I);
9733 if (CanonLHS && CanonRHS)
9734 return new FCmpInst(Pred, CanonLHS, CanonRHS,
"", &
I);
9737 if (
I.getType()->isVectorTy())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
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")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Instruction * foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI, Constant *RHSC)
Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
static Instruction * foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC)
Optimize fabs(X) compared with zero.
static void collectOffsetOp(Value *V, SmallVectorImpl< OffsetOp > &Offsets, bool AllowRecursion)
static Value * rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW, const DataLayout &DL, SetVector< Value * > &Explored, InstCombiner &IC)
Returns a re-written value of Start as an indexed GEP using Base as a pointer.
static bool isMinMaxCmpSelectEliminable(SelectPatternFlavor Flavor, Value *A, Value *B)
Returns true if a select that implements a min/max is redundant and select result can be replaced wit...
static Instruction * foldICmpEqualityWithOffset(ICmpInst &I, InstCombiner::BuilderTy &Builder, const SimplifyQuery &SQ)
Offset both sides of an equality icmp to see if we can save some instructions: icmp eq/ne X,...
static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1+In2, returning true if the result overflowed for this type.
static Instruction * foldICmpOfVectorReduce(ICmpInst &I, const DataLayout &DL, IRBuilderBase &Builder)
static Instruction * foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
static Instruction * foldVectorCmp(CmpInst &Cmp, InstCombiner::BuilderTy &Builder)
static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q, unsigned Depth=0)
static Value * createLogicFromTable(const std::bitset< 4 > &Table, Value *Op0, Value *Op1, IRBuilderBase &Builder, bool HasOneUse)
static Instruction * foldICmpOfUAddOv(ICmpInst &I)
static bool isChainSelectCmpBranch(const SelectInst *SI)
Return true when the instruction sequence within a block is select-cmp-br.
static Instruction * foldICmpInvariantGroup(ICmpInst &I)
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
static Instruction * foldReductionIdiom(ICmpInst &I, InstCombiner::BuilderTy &Builder, const DataLayout &DL)
This function folds patterns produced by lowering of reduce idioms, such as llvm.vector....
static Instruction * canonicalizeICmpBool(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Integer compare with boolean values can always be turned into bitwise ops.
static Instruction * foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI, Constant *RHSC, InstCombinerImpl &CI)
static Value * foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or, InstCombiner::BuilderTy &Builder)
Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
static bool hasBranchUse(ICmpInst &I)
Given an icmp instruction, return true if any use of this comparison is a branch on sign bit comparis...
static Value * foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0, Value *Op1, const SimplifyQuery &Q, InstCombiner &IC)
Some comparisons can be simplified.
static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth)
When performing a comparison against a constant, it is possible that not all the bits in the LHS are ...
static Instruction * foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl, const APInt &C)
Fold icmp (shl nuw C2, Y), C.
static Instruction * foldFCmpWithFloorAndCeil(FCmpInst &I, InstCombinerImpl &IC)
static Instruction * foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
static Instruction * processUZExtIdiom(ICmpInst &I, Value *Val, const APInt *OtherVal, InstCombinerImpl &IC)
Recognize and process idiom involving test for unsigned overflow.
static Instruction * foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC)
Optimize sqrt(X) compared with zero.
static Instruction * foldFCmpFNegCommonOp(FCmpInst &I)
static bool hasNoWrapProblem(const BinaryOperator &BO, CmpInst::Predicate Pred, bool &HasNSW, bool &HasNUW)
static Instruction * foldICmpWithHighBitMask(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
static ICmpInst * canonicalizeCmpWithConstant(ICmpInst &I)
If we have an icmp le or icmp ge instruction with a constant operand, turn it into the appropriate ic...
static Instruction * foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
Fold an icmp with LLVM intrinsics.
static Instruction * foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * foldICmpPow2Test(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1-In2, returning true if the result overflowed for this type.
static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW, const DataLayout &DL, SetVector< Value * > &Explored)
Returns true if we can rewrite Start as a GEP with pointer Base and some integer offset.
static Instruction * foldFCmpFpTrunc(FCmpInst &I, const Instruction &FPTrunc, const Constant &C)
static Instruction * foldICmpXNegX(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static Instruction * processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, ConstantInt *CI2, ConstantInt *CI1, InstCombinerImpl &IC)
The caller has matched a pattern of the form: I = icmp ugt (add (add A, B), CI2), CI1 If this is of t...
static Value * foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ, InstCombiner::BuilderTy &Builder)
static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C)
Returns true if the exploded icmp can be expressed as a signed comparison to zero and updates the pre...
static Instruction * transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond, const DataLayout &DL, InstCombiner &IC)
Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
static Instruction * foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs, const APInt &CRhs, InstCombiner::BuilderTy &Builder, const SimplifyQuery &Q)
static Instruction * foldFCmpFAbsFSubIntToFP(FCmpInst &I, InstCombinerImpl &IC)
Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b where 'pred' is olt, ult, ogt,...
static void setInsertionPoint(IRBuilder<> &Builder, Value *V, bool Before=true)
static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned)
static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q)
Return true if X is a multiple of C.
static Value * foldICmpWithTruncSignExtendedVal(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Some comparisons can be simplified.
static Instruction * foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
uint64_t IntrinsicInst * II
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file implements a set that has insertion order iteration characteristics.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
static constexpr roundingMode rmTowardZero
static constexpr roundingMode rmNearestTiesToEven
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
opStatus
IEEE-754R 7: Default exception handling.
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
APInt bitcastToAPInt() const
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
opStatus next(bool nextDown)
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
opStatus roundToIntegral(roundingMode RM)
Class for arbitrary precision integers.
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
uint64_t getZExtValue() const
Get zero extended value.
unsigned getActiveBits() const
Compute the number of active bits in the value.
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
APInt abs() const
Get the absolute value.
unsigned ceilLogBase2() const
bool sgt(const APInt &RHS) const
Signed greater than comparison.
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
LLVM_ABI APInt usub_ov(const APInt &RHS, bool &Overflow) const
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
unsigned getBitWidth() const
Return the number of bits in the APInt.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
bool isNegative() const
Determine sign of this APInt.
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
bool eq(const APInt &RHS) const
Equality comparison.
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
void negate()
Negate this APInt in place.
unsigned countr_zero() const
Count the number of trailing zero bits.
unsigned countl_zero() const
The APInt version of std::countl_zero.
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
void flipAllBits()
Toggle every bit to its opposite value.
unsigned countl_one() const
Count the number of leading one bits.
unsigned logBase2() const
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
bool isMaxSignedValue() const
Determine if this is the largest signed value.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
APInt shl(unsigned shiftAmt) const
Left-shift function.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
bool isOne() const
Determine if this is a value of 1.
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
unsigned countr_one() const
Count the number of trailing one bits.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
An arbitrary precision integer that knows its signedness.
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the minimum integer value with the given bit width and signedness.
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the maximum integer value with the given bit width and signedness.
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
LLVM Basic Block Representation.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BinaryOps getOpcode() const
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
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.
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This class is the base class for the comparison instructions.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
bool isEquality() const
Determine if this is an equals/not equals predicate.
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
bool isTrueWhenEqual() const
This is just a convenience.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
static LLVM_ABI bool isStrictPredicate(Predicate predicate)
This is a static version that you can use without an instruction available.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Predicate getPredicate() const
Return the predicate for this instruction.
static bool isIntPredicate(Predicate P)
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI CmpPredicate getSwapped(CmpPredicate P)
Get the swapped predicate of a CmpPredicate.
Conditional Branch instruction.
static LLVM_ABI std::optional< ConstGlobalLoad > fromLoadInst(LoadInst *LI)
Analyze a load instruction to a linear expression that loads from a constant global.
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getXor(Constant *C1, Constant *C2)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
const APInt & getValue() const
Return the constant as an APInt value reference.
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
LLVM_ABI const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers,...
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.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
iterator find(const_arg_type_t< KeyT > Val)
This instruction compares its operands according to the predicate given to the constructor.
static bool isCommutative(Predicate Pred)
static bool isEquality(Predicate Pred)
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
static GEPNoWrapFlags none()
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
LLVM_ABI Type * getSourceElementType() const
Value * getPointerOperand()
GEPNoWrapFlags getNoWrapFlags() const
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
This instruction compares its operands according to the predicate given to the constructor.
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
Common base class shared among various IRBuilders.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", bool HasSameSign=false)
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Instruction * foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr, const APInt &C)
Fold icmp ({al}shr X, Y), C.
Instruction * foldICmpWithZextOrSext(ICmpInst &ICmp)
Instruction * foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select, ConstantInt *C)
Instruction * foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv, const APInt &C)
Instruction * foldICmpBinOpWithConstant(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
Instruction * foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or, const APInt &C)
Fold icmp (or X, Y), C.
Instruction * foldICmpTruncWithTruncOrExt(ICmpInst &Cmp, const SimplifyQuery &Q)
Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
Instruction * foldSignBitTest(ICmpInst &I)
Fold equality-comparison between zero and any (maybe truncated) right-shift by one-less-than-bitwidth...
Instruction * foldCmpLoadFromIndexedGlobal(LoadInst *LI, CmpPredicate Pred, Constant *RHSC, Instruction &CtxI, ConstantInt *AndCst=nullptr)
Try to fold cmp pred (load (gep GV, ...)), cmpcst where GV is a global variable with a constant initi...
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi, bool isSigned, bool Inside)
Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise (V < Lo || V >= Hi).
Instruction * foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ)
Try to fold icmp (binop), X or icmp X, (binop).
Instruction * foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub, const APInt &C)
Fold icmp (sub X, Y), C.
Instruction * foldICmpWithClamp(ICmpInst &Cmp, Value *X, MinMaxIntrinsic *Min)
Match and fold patterns like: icmp eq/ne X, min(max(X, Lo), Hi) which represents a range check and ca...
Instruction * foldICmpInstWithConstantNotInt(ICmpInst &Cmp)
Handle icmp with constant (but not simple integer constant) RHS.
bool matchCommonBinOpOperands(Value *Op0, Value *Op1, CmpInst::Predicate Pred, Value *&LHS, Value *&RHS, const SimplifyQuery &Q)
Match Op0 Pred Op1 on binops with a removable common operand.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
Instruction * foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1, const APInt &C2)
Handle "(icmp eq/ne (shl AP2, A), AP1)" -> (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
Value * reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0, const SimplifyQuery &SQ, bool AnalyzeForSignBitExtraction=false)
Instruction * foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II, const APInt &C)
Fold an equality icmp with LLVM intrinsic and constant operand.
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Value * foldMultiplicationOverflowCheck(ICmpInst &Cmp)
Fold (-1 u/ x) u< y ((x * y) ?
Instruction * foldICmpAddLikeConstant(ICmpInst &Cmp, Value *X, const APInt &C2, bool HasNUW, bool HasNSW, const APInt &C)
Fold icmp pred (add X, C2), C using the no-wrap flags of the add.
Instruction * foldICmpWithConstant(ICmpInst &Cmp)
Fold icmp Pred X, C.
OverflowResult computeOverflow(Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS, Instruction *CtxI) const
CmpInst * canonicalizeICmpPredicate(CmpInst &I)
If we have a comparison with a non-canonical predicate, if we can update all the users,...
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * foldICmpWithZero(ICmpInst &Cmp)
Instruction * foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Fold an icmp equality instruction with binary operator LHS and constant RHS: icmp eq/ne BO,...
Instruction * foldICmpUsingBoolRange(ICmpInst &I)
If one operand of an icmp is effectively a bool (value range of {0,1}), then try to reduce patterns b...
Instruction * foldICmpWithTrunc(ICmpInst &Cmp)
Instruction * foldCmpSelectOfConstants(CmpInst &I)
Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2) where all true/false values are cons...
Instruction * foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II, const APInt &C)
Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS, ConstantInt *&Less, ConstantInt *&Equal, ConstantInt *&Greater)
Match a select chain which produces one of three values based on whether the LHS is less than,...
const InstCombineCLOptions & CLOpts
Instruction * visitFCmpInst(FCmpInst &I)
Instruction * foldICmpUsingKnownBits(ICmpInst &Cmp)
Try to fold the comparison based on range information we can get by checking whether bits are known t...
Instruction * foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div, const APInt &C)
Fold icmp ({su}div X, Y), C.
Instruction * foldIRemByPowerOfTwoToBitTest(ICmpInst &I)
If we have: icmp eq/ne (urem/srem x, y), 0 iff y is a power-of-two, we can replace this with a bit te...
Instruction * foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI, Constant *RHSC)
Fold fcmp ([us]itofp x, cst) if possible.
Instruction * foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv, const APInt &C)
Fold icmp (udiv X, Y), C.
Instruction * foldICmpAddOpConst(Value *X, const APInt &C, CmpPredicate Pred)
Fold "icmp pred (X+C), X".
Instruction * foldICmpWithCastOp(ICmpInst &ICmp)
Handle icmp (cast x), (cast or constant).
Instruction * foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc, const APInt &C)
Fold icmp (trunc X), C.
Instruction * foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add, const APInt &C)
Fold icmp (add X, Y), C.
Instruction * foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul, const APInt &C)
Fold icmp (mul X, Y), C.
Instruction * foldICmpCommutative(CmpPredicate Pred, Value *Op0, Value *Op1, ICmpInst &CtxI)
Instruction * tryFoldInstWithCtpopWithNot(Instruction *I)
Instruction * foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor, const APInt &C)
Fold icmp (xor X, Y), C.
Instruction * foldSelectICmp(CmpPredicate Pred, SelectInst *SI, Value *RHS, const ICmpInst &I)
Instruction * foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp, const APInt &C)
Try to fold integer comparisons with a constant operand: icmp Pred X, C where X is some kind of instr...
Instruction * foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp)
Fold icmp eq (num + mask) & ~mask, num to icmp eq (and num, mask), 0 Where mask is a low bit mask.
Instruction * foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And, const APInt &C1, const APInt &C2)
Fold icmp (and (sh X, Y), C2), C1.
Instruction * foldICmpBinOpWithConstantViaTruthTable(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Instruction * foldICmpInstWithConstant(ICmpInst &Cmp)
Try to fold integer comparisons with a constant operand: icmp Pred X, C where X is some kind of instr...
Instruction * foldICmpXorShiftConst(ICmpInst &Cmp, BinaryOperator *Xor, const APInt &C)
For power-of-2 C: ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1) ((X s>> ShiftC) ^ X) u> (C - 1) -...
Instruction * foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl, const APInt &C)
Fold icmp (shl X, Y), C.
Instruction * foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And, const APInt &C)
Fold icmp (and X, Y), C.
Instruction * foldICmpEquality(ICmpInst &Cmp)
Instruction * foldICmpWithMinMax(Instruction &I, MinMaxIntrinsic *MinMax, Value *Z, CmpPredicate Pred)
Fold icmp Pred min|max(X, Y), Z.
bool dominatesAllUses(const Instruction *DI, const Instruction *UI, const BasicBlock *DB) const
True when DB dominates all uses of DI except UI.
bool foldAllocaCmp(AllocaInst *Alloca)
Instruction * visitICmpInst(ICmpInst &I)
Instruction * foldICmpWithDominatingICmp(ICmpInst &Cmp)
Canonicalize icmp instructions based on dominating conditions.
bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp, const unsigned SIOpd)
Try to replace select with select operand SIOpd in SI-ICmp sequence.
Instruction * foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1, const APInt &C2)
Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" -> (icmp eq/ne A, Log2(AP2/AP1)) -> (icmp eq/ne A,...
void freelyInvertAllUsersOf(Value *V, Value *IgnoredUser=nullptr)
Freely adapt every user of V as-if V was changed to !V.
Instruction * foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And, const APInt &C1)
Fold icmp (and X, C2), C1.
Instruction * foldICmpBitCast(ICmpInst &Cmp)
Instruction * foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond, Instruction &I)
Fold comparisons between a GEP instruction and something else.
The core instruction combiner logic.
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const Instruction *CtxI) const
Module & getModule() const
LLVM_ABI bool canBeCastedExactlyIntToFP(Value *V, Type *FPTy, bool IsSigned, const Instruction *CtxI=nullptr) const
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
unsigned ComputeMaxSignificantBits(const Value *Op, const Instruction *CtxI=nullptr, unsigned Depth=0) const
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CtxI=nullptr, unsigned Depth=0)
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const Instruction *CtxI) const
static bool isCanonicalPredicate(CmpPredicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
bool canFreelyInvertAllUsersOf(Instruction *V, Value *IgnoredUser)
Given i1 V, can every user of V be freely adapted if V is changed to !V ?
OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CtxI) const
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const Instruction *CtxI, bool IsNSW=false) const
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const Instruction *CtxI) const
OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CtxI) const
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
const SimplifyQuery & getSimplifyQuery() const
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
bool isArithmeticShift() const
Return true if this is an arithmetic shift right.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
This class represents min/max intrinsics.
static bool isMin(Intrinsic::ID ID)
Whether the intrinsic is a smin or umin.
static bool isSigned(Intrinsic::ID ID)
Whether the intrinsic is signed or unsigned.
A Module instance is used to store all the information related to an LLVM module.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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...
Represents a saturating add/sub intrinsic.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
A vector that has set insertion semantics.
size_type size() const
Determine the number of elements in the SetVector.
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
bool insert(const value_type &X)
Insert a new element into the SetVector.
This instruction constructs a fixed permutation of two input vectors.
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)
reverse_iterator rbegin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
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.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
LLVM_ABI const fltSemantics & getFltSemantics() const
A Use represents the edge between a Value definition and its users.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< user_iterator > users()
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
const ParentTy * getParent() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
LLVM_ABI APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A sign-divided by B, rounded by the given rounding mode.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
auto m_PosZeroFP()
Matches a floating-point positive zero.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
auto m_Sqrt(const Opnd0 &Op0)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWNeg(const ValTy &V)
Matches a 'Neg' as 'sub nsw 0, V'.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
cst_pred_ty< is_non_zero_int > m_NonZeroInt()
Match a non-zero integer or a vector with all non-zero elements.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
cst_pred_ty< is_negated_power2_or_zero > m_NegatedPower2OrZero()
Match a integer or vector negated power-of-2.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
cst_pred_ty< custom_checkfn< APInt > > m_CheckedInt(function_ref< bool(const APInt &)> CheckFn)
Match an integer or vector where CheckFn(ele) for each element is true.
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
cst_pred_ty< is_lowbit_mask_or_zero > m_LowBitMaskOrZero()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastInst_match< OpTy, UIToFPInst > m_UIToFP(const OpTy &Op)
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
cstfp_pred_ty< is_finitenonzero > m_FiniteNonZero()
Match a finite non-zero FP constant.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
auto m_FAbs(const Opnd0 &Op0)
Signum_match< Val_t > m_Signum(const Val_t &V)
Matches a signum pattern.
CastInst_match< OpTy, SIToFPInst > m_SIToFP(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_MaxOrMin(const Opnd0 &Op0, const Opnd1 &Op1)
CastInst_match< OpTy, FPTruncInst > m_FPTrunc(const OpTy &Op)
auto m_Undef()
Match an arbitrary undef constant.
auto m_VecReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
@ BinaryOp
One of the operands is a binary op.
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI Value * simplifyFCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q)
Given operands for an FCmpInst, fold the result or return null.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
LLVM_ABI bool isKnownNegative(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM_ABI bool isKnownPositive(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Value * simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
constexpr unsigned BitWidth
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< DecomposedBitTest > decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate Pred, bool LookThroughTrunc=true, bool AllowNonZeroC=false, bool DecomposeAnd=false)
Decompose an icmp into the form ((X & Mask) pred C) if possible.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Value * materialize(InstCombiner::BuilderTy &Builder) const
static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV, Instruction *MDFrom)
static OffsetResult value(Value *V)
static OffsetResult invalid()
This callback is used in conjunction with PointerMayBeCaptured.
static CommonPointerBase compute(Value *LHS, Value *RHS)
Represent subnormal handling kind for floating point instruction inputs and outputs.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
static constexpr DenormalMode getIEEE()
bool isNonNegative() const
Returns true if this value is known to be non-negative.
bool isZero() const
Returns true if value is all zero.
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
APInt getSignedMaxValue() const
Return the maximal signed value possible given these KnownBits.
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
bool isConstant() const
Returns true if we know the value of all bits.
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
bool isNegative() const
Returns true if this value is known to be negative.
unsigned countMinPopulation() const
Returns the number of bits known to be one.
APInt getSignedMinValue() const
Return the minimal signed value possible given these KnownBits.
const APInt & getConstant() const
Returns the value when all bits have a known value.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
SimplifyQuery getWithInstruction(const Instruction *I) const
A MapVector that performs no allocations if smaller than a certain size.
Capture information for a specific Use.