32 #define DEBUG_TYPE "instcombine" 35 STATISTIC(NumSel,
"Number of select opts");
41 const APInt &In2,
bool IsSigned =
false) {
44 Result = In1.
sadd_ov(In2, Overflow);
46 Result = In1.
uadd_ov(In2, Overflow);
54 const APInt &In2,
bool IsSigned =
false) {
57 Result = In1.
ssub_ov(In2, Overflow);
59 Result = In1.
usub_ov(In2, Overflow);
67 for (
auto *U : I.
users())
68 if (isa<BranchInst>(U))
135 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
141 Max = Known.
One|UnknownBits;
143 if (UnknownBits.isNegative()) {
157 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
163 Max = Known.
One|UnknownBits;
179 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
184 if (ArrayElementCount > MaxArraySizeForCombine)
205 if (!Idx)
return nullptr;
208 if ((
unsigned)IdxVal != IdxVal)
return nullptr;
210 if (
StructType *STy = dyn_cast<StructType>(EltTy))
211 EltTy = STy->getElementType(IdxVal);
212 else if (
ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
213 if (IdxVal >= ATy->getNumElements())
return nullptr;
214 EltTy = ATy->getElementType();
222 enum { Overdefined = -3, Undefined = -2 };
231 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
235 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
243 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
248 uint64_t MagicBitvector = 0;
252 for (
unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
254 if (!Elt)
return nullptr;
257 if (!LaterIndices.
empty())
265 CompareRHS, DL, &TLI);
267 if (isa<UndefValue>(C)) {
270 if (TrueRangeEnd == (
int)i-1)
272 if (FalseRangeEnd == (
int)i-1)
279 if (!isa<ConstantInt>(C))
return nullptr;
283 bool IsTrueForElt = !cast<ConstantInt>(
C)->
isZero();
288 if (FirstTrueElement == Undefined)
289 FirstTrueElement = TrueRangeEnd = i;
292 if (SecondTrueElement == Undefined)
293 SecondTrueElement = i;
295 SecondTrueElement = Overdefined;
298 if (TrueRangeEnd == (
int)i-1)
301 TrueRangeEnd = Overdefined;
305 if (FirstFalseElement == Undefined)
306 FirstFalseElement = FalseRangeEnd = i;
309 if (SecondFalseElement == Undefined)
310 SecondFalseElement = i;
312 SecondFalseElement = Overdefined;
315 if (FalseRangeEnd == (
int)i-1)
318 FalseRangeEnd = Overdefined;
323 if (i < 64 && IsTrueForElt)
324 MagicBitvector |= 1ULL << i;
329 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
330 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
331 FalseRangeEnd == Overdefined)
346 Idx = Builder.CreateTrunc(Idx, IntPtrTy);
351 if (SecondTrueElement != Overdefined) {
353 if (FirstTrueElement == Undefined)
354 return replaceInstUsesWith(ICI, Builder.getFalse());
359 if (SecondTrueElement == Undefined)
363 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
365 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
366 return BinaryOperator::CreateOr(C1, C2);
371 if (SecondFalseElement != Overdefined) {
373 if (FirstFalseElement == Undefined)
374 return replaceInstUsesWith(ICI, Builder.getTrue());
379 if (SecondFalseElement == Undefined)
383 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
385 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
386 return BinaryOperator::CreateAnd(C1, C2);
391 if (TrueRangeEnd != Overdefined) {
392 assert(TrueRangeEnd != FirstTrueElement &&
"Should emit single compare");
395 if (FirstTrueElement) {
397 Idx = Builder.CreateAdd(Idx, Offs);
401 TrueRangeEnd-FirstTrueElement+1);
406 if (FalseRangeEnd != Overdefined) {
407 assert(FalseRangeEnd != FirstFalseElement &&
"Should emit single compare");
409 if (FirstFalseElement) {
411 Idx = Builder.CreateAdd(Idx, Offs);
415 FalseRangeEnd-FirstFalseElement);
428 if (ArrayElementCount <= Idx->
getType()->getIntegerBitWidth())
431 Ty = DL.getSmallestLegalIntType(Init->
getContext(), ArrayElementCount);
434 Value *V = Builder.CreateIntCast(Idx, Ty,
false);
465 for (i = 1; i != e; ++i, ++GTI) {
468 if (CI->isZero())
continue;
475 Offset += Size*CI->getSExtValue();
485 if (i == e)
return nullptr;
493 for (++i, ++GTI; i != e; ++i, ++GTI) {
495 if (!CI)
return nullptr;
498 if (CI->
isZero())
continue;
526 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
528 Offset &= PtrSizeMask;
529 VariableScale &= PtrSizeMask;
535 int64_t NewOffs = Offset / (int64_t)VariableScale;
536 if (Offset != NewOffs*(int64_t)VariableScale)
540 if (VariableIdx->
getType() != IntPtrTy)
564 while (!WorkList.
empty()) {
567 while (!WorkList.
empty()) {
568 if (Explored.
size() >= 100)
573 if (Explored.
count(V) != 0) {
578 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
579 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
584 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
586 if (!CI->isNoopCast(DL))
589 if (Explored.
count(CI->getOperand(0)) == 0)
593 if (
auto *GEP = dyn_cast<GEPOperator>(V)) {
605 if (WorkList.
back() == V) {
611 if (
auto *PN = dyn_cast<PHINode>(V)) {
613 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
621 for (
auto *PN : PHIs)
622 for (
Value *
Op : PN->incoming_values())
630 for (
Value *Val : Explored) {
636 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
637 Explored.count(PHI) == 0)
640 if (PHI->getParent() == Inst->getParent())
650 bool Before =
true) {
651 if (
auto *PHI = dyn_cast<PHINode>(V)) {
652 Builder.
SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
655 if (
auto *
I = dyn_cast<Instruction>(V)) {
657 I = &*std::next(
I->getIterator());
661 if (
auto *A = dyn_cast<Argument>(V)) {
663 BasicBlock &Entry = A->getParent()->getEntryBlock();
669 assert(isa<Constant>(V) &&
"Setting insertion point for unknown value!");
691 for (
Value *Val : Explored) {
696 if (
auto *PHI = dyn_cast<PHINode>(Val))
697 NewInsts[PHI] =
PHINode::Create(IndexType, PHI->getNumIncomingValues(),
698 PHI->getName() +
".idx", PHI);
703 for (
Value *Val : Explored) {
705 if (NewInsts.
find(Val) != NewInsts.
end())
708 if (
auto *CI = dyn_cast<CastInst>(Val)) {
709 NewInsts[CI] = NewInsts[CI->getOperand(0)];
712 if (
auto *GEP = dyn_cast<GEPOperator>(Val)) {
719 NewInsts[GEP->
getOperand(0)]->getType()->getScalarSizeInBits()) {
720 Index = Builder.CreateSExtOrTrunc(
721 Index, NewInsts[GEP->
getOperand(0)]->getType(),
726 if (isa<ConstantInt>(
Op) && cast<ConstantInt>(
Op)->
isZero())
729 NewInsts[
GEP] = Builder.CreateNSWAdd(
733 if (isa<PHINode>(Val))
740 for (
Value *Val : Explored) {
745 if (
auto *PHI = dyn_cast<PHINode>(Val)) {
747 for (
unsigned I = 0,
E = PHI->getNumIncomingValues();
I <
E; ++
I) {
748 Value *NewIncoming = PHI->getIncomingValue(
I);
750 if (NewInsts.
find(NewIncoming) != NewInsts.
end())
751 NewIncoming = NewInsts[NewIncoming];
753 NewPhi->
addIncoming(NewIncoming, PHI->getIncomingBlock(
I));
758 for (
Value *Val : Explored) {
767 Value *NewBase = Base;
769 NewBase = Builder.CreateBitOrPointerCast(Base, Start->
getType(),
772 Value *GEP = Builder.CreateInBoundsGEP(
776 if (!Val->getType()->isPointerTy()) {
777 Value *Cast = Builder.CreatePointerCast(GEP, Val->
getType(),
778 Val->getName() +
".conv");
784 return NewInsts[Start];
790 static std::pair<Value *, Value *>
812 if (
auto *CI = dyn_cast<IntToPtrInst>(V)) {
813 if (!CI->isNoopCast(DL))
815 V = CI->getOperand(0);
818 if (
auto *CI = dyn_cast<PtrToIntInst>(V)) {
819 if (!CI->isNoopCast(DL))
821 V = CI->getOperand(0);
881 if (!isa<GetElementPtrInst>(RHS))
897 }
else if (
GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
900 if (PtrBase != GEPRHS->getOperand(0)) {
901 bool IndicesTheSame = GEPLHS->
getNumOperands()==GEPRHS->getNumOperands();
903 GEPRHS->getOperand(0)->getType();
906 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
907 IndicesTheSame =
false;
918 if (GEPLHS->
isInBounds() && GEPRHS->isInBounds() &&
920 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
931 if (LHSIndexTy != RHSIndexTy) {
934 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
936 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
941 return replaceInstUsesWith(I, Cmp);
952 return foldGEPICmp(GEPRHS, GEPLHS->
getOperand(0),
956 if (GEPRHS->hasAllZeroIndices())
957 return foldGEPICmp(GEPLHS, GEPRHS->
getOperand(0), Cond,
I);
959 bool GEPsInBounds = GEPLHS->
isInBounds() && GEPRHS->isInBounds();
962 unsigned NumDifferences = 0;
963 unsigned DiffOperand = 0;
964 for (
unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
965 if (GEPLHS->
getOperand(i) != GEPRHS->getOperand(i)) {
967 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
972 if (NumDifferences++)
break;
977 if (NumDifferences == 0)
978 return replaceInstUsesWith(I,
981 else if (NumDifferences == 1 && GEPsInBounds) {
983 Value *RHSV = GEPRHS->getOperand(DiffOperand);
991 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->
hasOneUse()) &&
992 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
1024 unsigned MaxIter = 32;
1027 for (
const Use &U : Alloca->
uses()) {
1028 if (Worklist.
size() >= MaxIter)
1033 unsigned NumCmps = 0;
1034 while (!Worklist.
empty()) {
1037 const Value *V = U->getUser();
1040 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1041 isa<SelectInst>(V)) {
1043 }
else if (isa<LoadInst>(V)) {
1046 }
else if (
const auto *
SI = dyn_cast<StoreInst>(V)) {
1048 if (
SI->getValueOperand() == U->get())
1051 }
else if (isa<ICmpInst>(V)) {
1055 }
else if (
const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1056 switch (Intrin->getIntrinsicID()) {
1060 case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
1061 case Intrinsic::memcpy:
case Intrinsic::memmove:
case Intrinsic::memset:
1069 for (
const Use &U : V->
uses()) {
1070 if (Worklist.
size() >= MaxIter)
1077 return replaceInstUsesWith(
1140 return new ICmpInst(Pred, LHS, RHS);
1147 bool IsAShr = isa<AShrOperator>(I.
getOperand(0));
1172 if (IsAShr && AP1 == AP2.
ashr(Shift)) {
1178 }
else if (AP1 == AP2.
lshr(Shift)) {
1186 return replaceInstUsesWith(I, TorF);
1199 return new ICmpInst(Pred, LHS, RHS);
1208 if (!AP1 && AP2TrailingZeros != 0)
1219 if (Shift > 0 && AP2.
shl(Shift) == AP1)
1225 return replaceInstUsesWith(I, TorF);
1253 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1267 unsigned NeededSignBits = CI1->
getBitWidth() - NewWidth + 1;
1278 if (U == AddWithCst)
1296 Intrinsic::sadd_with_overflow, NewType);
1304 Value *TruncA = Builder.CreateTrunc(A, NewType, A->
getName() +
".trunc");
1305 Value *TruncB = Builder.CreateTrunc(B, NewType, B->
getName() +
".trunc");
1306 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB},
"sadd");
1307 Value *
Add = Builder.CreateExtractValue(Call, 0,
"sadd.result");
1308 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->
getType());
1345 Value *A =
nullptr, *
B =
nullptr;
1363 Cmp, A,
B, CI2, cast<ConstantInt>(Cmp.
getOperand(1)), *
this))
1380 TrueBB, FalseBB)) &&
1381 TrueBB != FalseBB) {
1392 return replaceInstUsesWith(Cmp, Builder.getFalse());
1394 return replaceInstUsesWith(Cmp, Builder.getTrue());
1440 if ((Known.
Zero | Known.
One).countLeadingOnes() >= SrcBits - DstBits) {
1464 bool TrueIfSigned =
false;
1518 if (!Shift || !Shift->
isShift())
1526 unsigned ShiftOpcode = Shift->
getOpcode();
1527 bool IsShl = ShiftOpcode == Instruction::Shl;
1530 bool CanFold =
false;
1531 if (ShiftOpcode == Instruction::Shl) {
1539 bool IsAshr = ShiftOpcode == Instruction::AShr;
1548 if (!IsAshr || (C2.
shl(*C3).
lshr(*C3) == C2)) {
1557 APInt SameAsC1 = IsShl ? NewCst.
shl(*C3) : NewCst.
lshr(*C3);
1559 if (SameAsC1 != C1) {
1572 Worklist.Add(Shift);
1627 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->
getName());
1632 if (
Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1646 unsigned UsesRemoved = 0;
1649 if (Or->hasOneUse())
1655 Value *NewOr =
nullptr;
1656 if (
auto *C = dyn_cast<Constant>(B)) {
1657 if (UsesRemoved >= 1)
1660 if (UsesRemoved >= 3)
1661 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->
getName(),
1666 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->
getName());
1680 if (
Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1688 if (
auto *LI = dyn_cast<LoadInst>(X))
1689 if (
auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1690 if (
auto *GV = dyn_cast<GlobalVariable>(GEP->
getOperand(0)))
1692 !LI->isVolatile() && isa<ConstantInt>(
Y)) {
1694 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2))
1704 if (Cmp.
getOperand(1) == Y && (-
C).isPowerOf2()) {
1716 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) {
1720 Value *Trunc = Builder.CreateTrunc(X, NTy);
1746 (C + 1).isPowerOf2()) {
1768 Value *X1, *X2, *X3, *X4;
1773 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
1774 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
1830 if (CLog2 == TypeBits - 1) {
1858 }
else if (Cmp.
isEquality() && CIsPowerOf2) {
1869 const APInt *ShiftVal;
1871 return foldICmpShlConstConst(Cmp, Shl->
getOperand(1),
C, *ShiftVal);
1873 const APInt *ShiftAmt;
1880 if (ShiftAmt->uge(TypeBits))
1897 C.
ashr(*ShiftAmt).
shl(*ShiftAmt) ==
C) {
1907 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
1927 C.
lshr(*ShiftAmt).
shl(*ShiftAmt) ==
C) {
1936 assert(C.
ugt(0) &&
"ult 0 should have been eliminated");
1937 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
1947 Value *And = Builder.CreateAnd(X, Mask, Shl->
getName() +
".mask");
1949 return new ICmpInst(Pred, And, LShrC);
1953 bool TrueIfSigned =
false;
1959 Value *And = Builder.CreateAnd(X, Mask, Shl->
getName() +
".mask");
1970 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
1972 DL.isLegalInteger(TypeBits - Amt)) {
1978 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
1996 const APInt *ShiftVal;
1998 return foldICmpShrConstConst(Cmp, Shr->
getOperand(1),
C, *ShiftVal);
2000 const APInt *ShiftAmt;
2007 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits);
2008 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2011 bool IsAShr = Shr->
getOpcode() == Instruction::AShr;
2012 bool IsExact = Shr->
isExact();
2023 if (ShiftedC.
ashr(ShAmtVal) ==
C)
2028 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2030 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2038 if (ShiftedC.
lshr(ShAmtVal) ==
C)
2043 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2044 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2058 (!IsAShr && C.
shl(ShAmtVal).
lshr(ShAmtVal) ==
C)) &&
2059 "Expected icmp+shr simplify did not occur.");
2071 Value *And = Builder.CreateAnd(X, Mask, Shr->
getName() +
".mask");
2086 assert(*C2 != 0 &&
"udiv 0, X should have been simplified already.");
2092 "icmp ugt X, UINT_MAX should have been simplified already.");
2099 assert(C != 0 &&
"icmp ult X, 0 should have been simplified already.");
2129 bool DivIsSigned = Div->
getOpcode() == Instruction::SDiv;
2145 APInt Prod = C * *C2;
2150 bool ProdOV = (DivIsSigned ? Prod.
sdiv(*C2) : Prod.
udiv(*C2)) != C;
2165 int LoOverflow = 0, HiOverflow = 0;
2166 APInt LoBound, HiBound;
2171 HiOverflow = LoOverflow = ProdOV;
2177 }
else if (C2->isStrictlyPositive()) {
2180 LoBound = -(RangeSize - 1);
2181 HiBound = RangeSize;
2184 HiOverflow = LoOverflow = ProdOV;
2190 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2192 APInt DivNeg = -RangeSize;
2193 LoOverflow =
addWithOverflow(LoBound, HiBound, DivNeg,
true) ? -1 : 0;
2196 }
else if (C2->isNegative()) {
2201 LoBound = RangeSize + 1;
2202 HiBound = -RangeSize;
2203 if (HiBound == *C2) {
2210 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2212 LoOverflow =
addWithOverflow(LoBound, HiBound, RangeSize,
true) ? -1:0;
2215 LoOverflow = HiOverflow = ProdOV;
2228 if (LoOverflow && HiOverflow)
2229 return replaceInstUsesWith(Cmp, Builder.getFalse());
2238 return replaceInstUsesWith(
2239 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned,
true));
2241 if (LoOverflow && HiOverflow)
2242 return replaceInstUsesWith(Cmp, Builder.getTrue());
2245 ICmpInst::ICMP_ULT, X,
2249 ICmpInst::ICMP_UGE, X,
2251 return replaceInstUsesWith(Cmp,
2252 insertRangeTest(X, LoBound, HiBound,
2253 DivIsSigned,
false));
2256 if (LoOverflow == +1)
2257 return replaceInstUsesWith(Cmp, Builder.getTrue());
2258 if (LoOverflow == -1)
2259 return replaceInstUsesWith(Cmp, Builder.getFalse());
2263 if (HiOverflow == +1)
2264 return replaceInstUsesWith(Cmp, Builder.getFalse());
2265 if (HiOverflow == -1)
2266 return replaceInstUsesWith(Cmp, Builder.getTrue());
2268 return new ICmpInst(ICmpInst::ICMP_UGE, X,
2314 (*C2 & (C - 1)) == (C - 1))
2356 const APInt &Lower = CR.getLower();
2416 assert(C &&
"Cmp RHS should be a constant int!");
2422 Value *OrigLHS, *OrigRHS;
2423 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2425 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
2427 assert(C1LessThan && C2Equal && C3GreaterThan);
2429 bool TrueWhenLessThan =
2432 bool TrueWhenEqual =
2435 bool TrueWhenGreaterThan =
2447 Value *Cond = Builder.getFalse();
2448 if (TrueWhenLessThan)
2449 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(
ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
2451 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(
ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
2452 if (TrueWhenGreaterThan)
2453 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(
ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
2455 return replaceInstUsesWith(Cmp, Cond);
2475 Value *Vec =
nullptr;
2480 if (
auto *Elem = dyn_cast_or_null<ConstantInt>(Mask->
getSplatValue())) {
2481 auto *VecTy = cast<VectorType>(BCIOp->
getType());
2482 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
2484 if (C.
isSplat(EltTy->getBitWidth())) {
2490 Value *Extract = Builder.CreateExtractElement(Vec, Elem);
2492 return new ICmpInst(Pred, Extract, NewC);
2506 if (
auto *BO = dyn_cast<BinaryOperator>(Cmp.
getOperand(0))) {
2507 switch (BO->getOpcode()) {
2508 case Instruction::Xor:
2509 if (
Instruction *I = foldICmpXorConstant(Cmp, BO, *C))
2512 case Instruction::And:
2513 if (
Instruction *I = foldICmpAndConstant(Cmp, BO, *C))
2516 case Instruction::Or:
2517 if (
Instruction *I = foldICmpOrConstant(Cmp, BO, *C))
2520 case Instruction::Mul:
2521 if (
Instruction *I = foldICmpMulConstant(Cmp, BO, *C))
2524 case Instruction::Shl:
2525 if (
Instruction *I = foldICmpShlConstant(Cmp, BO, *C))
2528 case Instruction::LShr:
2529 case Instruction::AShr:
2530 if (
Instruction *I = foldICmpShrConstant(Cmp, BO, *C))
2533 case Instruction::UDiv:
2534 if (
Instruction *I = foldICmpUDivConstant(Cmp, BO, *C))
2537 case Instruction::SDiv:
2538 if (
Instruction *I = foldICmpDivConstant(Cmp, BO, *C))
2541 case Instruction::Sub:
2542 if (
Instruction *I = foldICmpSubConstant(Cmp, BO, *C))
2546 if (
Instruction *I = foldICmpAddConstant(Cmp, BO, *C))
2553 if (
Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, *C))
2559 if (
auto *SI = dyn_cast<SelectInst>(Cmp.
getOperand(0))) {
2564 if (
Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
2568 if (
auto *TI = dyn_cast<TruncInst>(Cmp.
getOperand(0))) {
2569 if (
Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
2573 if (
auto *BCI = dyn_cast<BitCastInst>(Cmp.
getOperand(0))) {
2574 if (
Instruction *I = foldICmpBitCastConstant(Cmp, BCI, *C))
2578 if (
Instruction *I = foldICmpIntrinsicWithConstant(Cmp, *C))
2600 case Instruction::SRem:
2605 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->
getName());
2617 return new ICmpInst(Pred, BOp0, SubC);
2622 if (
Value *NegVal = dyn_castNegVal(BOp1))
2623 return new ICmpInst(Pred, BOp0, NegVal);
2624 if (
Value *NegVal = dyn_castNegVal(BOp0))
2625 return new ICmpInst(Pred, NegVal, BOp1);
2627 Value *Neg = Builder.CreateNeg(BOp1);
2629 return new ICmpInst(Pred, BOp0, Neg);
2634 case Instruction::Xor:
2636 if (
Constant *BOC = dyn_cast<Constant>(BOp1)) {
2642 return new ICmpInst(Pred, BOp0, BOp1);
2646 case Instruction::Sub:
2652 return new ICmpInst(Pred, BOp1, SubC);
2655 return new ICmpInst(Pred, BOp0, BOp1);
2659 case Instruction::Or: {
2666 Value *And = Builder.CreateAnd(BOp0, NotBOC);
2667 return new ICmpInst(Pred, And, NotBOC);
2671 case Instruction::And: {
2687 return new ICmpInst(NewPred, BOp0, Zero);
2691 if (C.
isNullValue() && (~(*BOC) + 1).isPowerOf2()) {
2694 return new ICmpInst(NewPred, BOp0, NegBOC);
2699 case Instruction::Mul:
2710 case Instruction::UDiv:
2714 return new ICmpInst(NewPred, BOp1, BOp0);
2733 case Intrinsic::bswap:
2739 case Intrinsic::ctlz:
2740 case Intrinsic::cttz:
2750 case Intrinsic::ctpop: {
2779 switch (LHSI->getOpcode()) {
2780 case Instruction::GetElementPtr:
2783 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
2788 case Instruction::PHI:
2793 if (
Instruction *
NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
2800 Value *Op1 =
nullptr, *Op2 =
nullptr;
2802 if (
Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2806 if (
Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2818 bool Transform =
false;
2821 else if (Op1 || Op2) {
2823 if (LHSI->hasOneUse())
2826 else if (CI && !CI->
isZero())
2831 replacedSelectWithOperand(cast<SelectInst>(LHSI), &
I, Op1 ? 2 : 1);
2835 Op1 = Builder.CreateICmp(I.
getPredicate(), LHSI->getOperand(1), RHSC,
2838 Op2 = Builder.CreateICmp(I.
getPredicate(), LHSI->getOperand(2), RHSC,
2844 case Instruction::IntToPtr:
2847 DL.getIntPtrType(RHSC->
getType()) == LHSI->getOperand(0)->getType())
2856 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
2860 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
2889 case ICmpInst::Predicate::ICMP_EQ:
2891 DstPred = ICmpInst::Predicate::ICMP_ULE;
2893 case ICmpInst::Predicate::ICMP_NE:
2895 DstPred = ICmpInst::Predicate::ICMP_UGT;
2897 case ICmpInst::Predicate::ICMP_UGT:
2899 assert(X == I.
getOperand(0) &&
"instsimplify took care of commut. variant");
2900 DstPred = ICmpInst::Predicate::ICMP_UGT;
2902 case ICmpInst::Predicate::ICMP_UGE:
2904 assert(X == I.
getOperand(1) &&
"instsimplify took care of commut. variant");
2905 DstPred = ICmpInst::Predicate::ICMP_ULE;
2907 case ICmpInst::Predicate::ICMP_ULT:
2909 assert(X == I.
getOperand(1) &&
"instsimplify took care of commut. variant");
2910 DstPred = ICmpInst::Predicate::ICMP_UGT;
2912 case ICmpInst::Predicate::ICMP_ULE:
2914 assert(X == I.
getOperand(0) &&
"instsimplify took care of commut. variant");
2915 DstPred = ICmpInst::Predicate::ICMP_ULE;
2917 case ICmpInst::Predicate::ICMP_SGT:
2921 DstPred = ICmpInst::Predicate::ICMP_SGT;
2923 case ICmpInst::Predicate::ICMP_SGE:
2927 DstPred = ICmpInst::Predicate::ICMP_SLE;
2929 case ICmpInst::Predicate::ICMP_SLT:
2933 DstPred = ICmpInst::Predicate::ICMP_SGT;
2935 case ICmpInst::Predicate::ICMP_SLE:
2939 DstPred = ICmpInst::Predicate::ICMP_SLE;
2961 const APInt *C0, *C1;
2978 const APInt &MaskedBits = *C0;
2979 assert(MaskedBits != 0 &&
"shift by zero should be folded away already.");
2983 case ICmpInst::Predicate::ICMP_EQ:
2987 DstPred = ICmpInst::Predicate::ICMP_ULT;
2989 case ICmpInst::Predicate::ICMP_NE:
2993 DstPred = ICmpInst::Predicate::ICMP_UGE;
3002 const APInt BitWidth =
APInt(XBitWidth, XBitWidth);
3003 assert(BitWidth.
ugt(MaskedBits) &&
"shifts should leave some bits untouched");
3006 const APInt KeptBits = BitWidth - MaskedBits;
3007 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) &&
"unreachable");
3010 assert(ICmpCst.isPowerOf2());
3013 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
3037 bool NoOp0WrapProblem =
false, NoOp1WrapProblem =
false;
3038 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
3043 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
3051 Value *A =
nullptr, *
B =
nullptr, *C =
nullptr, *
D =
nullptr;
3057 C = BO1->getOperand(0);
3058 D = BO1->getOperand(1);
3062 if ((A == Op1 ||
B == Op1) && NoOp0WrapProblem)
3063 return new ICmpInst(Pred, A == Op1 ?
B : A,
3067 if ((C == Op0 ||
D == Op0) && NoOp1WrapProblem)
3072 if (A && C && (A == C || A ==
D ||
B == C ||
B ==
D) && NoOp0WrapProblem &&
3082 }
else if (A ==
D) {
3086 }
else if (
B == C) {
3167 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
3171 const APInt &AP1 = C1->getValue();
3172 const APInt &AP2 = C2->getValue();
3174 APInt AP1Abs = C1->getValue().
abs();
3175 APInt AP2Abs = C2->getValue().
abs();
3176 if (AP1Abs.
uge(AP2Abs)) {
3178 Value *NewAdd = Builder.CreateNSWAdd(A, C3);
3179 return new ICmpInst(Pred, NewAdd, C);
3182 Value *NewAdd = Builder.CreateNSWAdd(C, C3);
3183 return new ICmpInst(Pred, A, NewAdd);
3194 if (BO0 && BO0->
getOpcode() == Instruction::Sub) {
3198 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
3199 C = BO1->getOperand(0);
3200 D = BO1->getOperand(1);
3204 if (A == Op1 && NoOp0WrapProblem)
3207 if (C == Op0 && NoOp1WrapProblem)
3218 if (
B &&
D &&
B ==
D && NoOp0WrapProblem && NoOp1WrapProblem &&
3223 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem &&
3232 if (
Constant *RHSC = dyn_cast<Constant>(Op1))
3233 if (RHSC->isNotMinSignedValue())
3243 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
3244 Op0 == BO1->getOperand(1))
3268 BO1->hasOneUse() && BO0->
getOperand(1) == BO1->getOperand(1)) {
3273 case Instruction::Sub:
3274 case Instruction::Xor: {
3297 case Instruction::Mul: {
3311 Value *And2 = Builder.CreateAnd(BO1->getOperand(0),
Mask);
3312 return new ICmpInst(Pred, And1, And2);
3321 case Instruction::UDiv:
3322 case Instruction::LShr:
3327 case Instruction::SDiv:
3332 case Instruction::AShr:
3333 if (!BO0->
isExact() || !BO1->isExact())
3337 case Instruction::Shl: {
3361 return replaceInstUsesWith(I, V);
3364 return replaceInstUsesWith(I, V);
3464 if (A == Op1 || B == Op1) {
3465 Value *OtherVal = A == Op1 ?
B : A;
3475 Value *Xor = Builder.CreateXor(C, NC);
3493 Value *OtherVal = A == Op0 ?
B : A;
3500 Value *X =
nullptr, *
Y =
nullptr, *Z =
nullptr;
3506 }
else if (A == D) {
3510 }
else if (B == C) {
3514 }
else if (B == D) {
3521 Op1 = Builder.CreateXor(X,
Y);
3522 Op1 = Builder.CreateAnd(Op1, Z);
3550 if (ShAmt < TypeBits && ShAmt != 0) {
3553 Value *Xor = Builder.CreateXor(A, B, I.
getName() +
".unshifted");
3555 return new ICmpInst(NewPred, Xor, Builder.getInt(CmpVal));
3564 if (ShAmt < TypeBits && ShAmt != 0) {
3565 Value *Xor = Builder.CreateXor(A, B, I.
getName() +
".unshifted");
3567 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
3582 unsigned ASize = cast<IntegerType>(A->
getType())->getPrimitiveSizeInBits();
3584 if (ShAmt < ASize) {
3592 Value *
Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
3593 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
3614 Type *SrcTy = LHSCIOp->getType();
3620 const auto& CompatibleSizes = [&](
Type* SrcTy,
Type* DestTy) ->
bool {
3621 if (isa<VectorType>(SrcTy)) {
3622 SrcTy = cast<VectorType>(SrcTy)->getElementType();
3623 DestTy = cast<VectorType>(DestTy)->getElementType();
3627 if (LHSCI->
getOpcode() == Instruction::PtrToInt &&
3628 CompatibleSizes(SrcTy, DestTy)) {
3629 Value *RHSOp =
nullptr;
3630 if (
auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.
getOperand(1))) {
3631 Value *RHSCIOp = RHSC->getOperand(0);
3633 LHSCIOp->getType()->getPointerAddressSpace()) {
3634 RHSOp = RHSC->getOperand(0);
3636 if (LHSCIOp->getType() != RHSOp->
getType())
3637 RHSOp = Builder.CreateBitCast(RHSOp, LHSCIOp->
getType());
3639 }
else if (
auto *RHSC = dyn_cast<Constant>(ICmp.
getOperand(1))) {
3649 if (LHSCI->
getOpcode() != Instruction::ZExt &&
3650 LHSCI->
getOpcode() != Instruction::SExt)
3653 bool isSignedExt = LHSCI->
getOpcode() == Instruction::SExt;
3654 bool isSignedCmp = ICmp.
isSigned();
3656 if (
auto *CI = dyn_cast<CastInst>(ICmp.
getOperand(1))) {
3659 if (RHSCIOp->
getType() != LHSCIOp->getType())
3664 if (CI->getOpcode() != LHSCI->
getOpcode())
3673 if (isSignedCmp && isSignedExt)
3698 if (isSignedExt && isSignedCmp)
3712 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C))
3725 return replaceInstUsesWith(ICmp, Result);
3734 if (OrigI.
isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
3737 auto SetResult = [&](
Value *OpResult,
Constant *OverflowVal,
bool ReuseName) {
3739 Overflow = OverflowVal;
3749 Builder.SetInsertPoint(&OrigI);
3758 return SetResult(Builder.CreateNUWAdd(LHS, RHS), Builder.getFalse(),
3762 return SetResult(Builder.CreateAdd(LHS, RHS), Builder.getTrue(),
true);
3770 return SetResult(LHS, Builder.getFalse(),
false);
3775 if (willNotOverflowSignedAdd(LHS, RHS, OrigI))
3776 return SetResult(Builder.CreateNSWAdd(LHS, RHS), Builder.getFalse(),
3785 return SetResult(LHS, Builder.getFalse(),
false);
3788 if (willNotOverflowSignedSub(LHS, RHS, OrigI))
3789 return SetResult(Builder.CreateNSWSub(LHS, RHS), Builder.getFalse(),
3792 if (willNotOverflowUnsignedSub(LHS, RHS, OrigI))
3793 return SetResult(Builder.CreateNUWSub(LHS, RHS), Builder.getFalse(),
3802 return SetResult(Builder.CreateNUWMul(LHS, RHS), Builder.getFalse(),
3805 return SetResult(Builder.CreateMul(LHS, RHS), Builder.getTrue(),
true);
3810 if (isa<UndefValue>(RHS))
3815 return SetResult(RHS, Builder.getFalse(),
false);
3819 return SetResult(LHS, Builder.getFalse(),
false);
3822 if (willNotOverflowSignedMul(LHS, RHS, OrigI))
3823 return SetResult(Builder.CreateNSWMul(LHS, RHS), Builder.getFalse(),
3849 if (!isa<IntegerType>(MulVal->
getType()))
3857 assert(MulInstr->getOpcode() == Instruction::Mul);
3859 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
3860 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
3861 assert(LHS->getOpcode() == Instruction::ZExt);
3862 assert(RHS->getOpcode() == Instruction::ZExt);
3863 Value *A = LHS->getOperand(0), *
B = RHS->getOperand(0);
3866 Type *TyA = A->getType(), *TyB =
B->getType();
3868 WidthB = TyB->getPrimitiveSizeInBits();
3871 if (WidthB > WidthA) {
3886 if (
TruncInst *TI = dyn_cast<TruncInst>(U)) {
3889 if (TruncWidth > MulWidth)
3893 if (BO->
getOpcode() != Instruction::And)
3918 if (
ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal))
3919 if (Zext->hasOneUse()) {
3920 Value *ZextArg = Zext->getOperand(0);
3921 if (
TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg))
3932 if (ValToMask != MulVal)
3936 unsigned MaskWidth = CVal.
logBase2();
3937 if (MaskWidth == MulWidth)
3947 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3959 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3970 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3982 if (
ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
3997 Value *MulA = A, *MulB =
B;
3998 if (WidthA < MulWidth)
4000 if (WidthB < MulWidth)
4003 Intrinsic::umul_with_overflow, MulType);
4014 if (U == &I || U == OtherVal)
4016 if (
TruncInst *TI = dyn_cast<TruncInst>(U)) {
4017 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
4025 APInt ShortMask = CI->getValue().
trunc(MulWidth);
4037 if (isa<Instruction>(OtherVal))
4127 return GoodToSwap > 0;
4143 assert(DI && UI &&
"Instruction not defined\n");
4154 auto *Usr = cast<Instruction>(U);
4155 if (Usr != UI && !DT.dominates(DB, Usr->
getParent()))
4166 auto *BI = dyn_cast_or_null<BranchInst>(BB->
getTerminator());
4167 if (!BI || BI->getNumSuccessors() != 2)
4170 if (!IC || (IC->getOperand(0) != SI && IC->
getOperand(1) !=
SI))
4217 const unsigned SIOpd) {
4218 assert((SIOpd == 1 || SIOpd == 2) &&
"Invalid select operand!");
4259 if (SimplifyDemandedBits(&I, 0,
4271 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
4272 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
4284 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
4286 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
4296 if (Op0Max.
ult(Op1Min) || Op0Min.ugt(Op1Max)) {
4305 APInt Op0KnownZeroInverted = ~Op0Known.
Zero;
4308 Value *LHS =
nullptr;
4311 *LHSC != Op0KnownZeroInverted)
4316 APInt ValToCheck = Op0KnownZeroInverted;
4323 return new ICmpInst(NewPred, X, CmpC);
4324 }
else if ((++ValToCheck).isPowerOf2()) {
4330 return new ICmpInst(NewPred, X, CmpC);
4348 if (Op0Max.
ult(Op1Min))
4350 if (Op0Min.uge(Op1Max))
4352 if (Op1Min == Op0Max)
4358 if (*CmpC == Op0Min + 1)
4370 if (Op0Min.ugt(Op1Max))
4372 if (Op0Max.
ule(Op1Min))
4374 if (Op1Max == Op0Min)
4380 if (*CmpC == Op0Max - 1)
4392 if (Op0Max.
slt(Op1Min))
4394 if (Op0Min.sge(Op1Max))
4396 if (Op1Min == Op0Max)
4400 if (*CmpC == Op0Min + 1)
4407 if (Op0Min.sgt(Op1Max))
4409 if (Op0Max.
sle(Op1Min))
4411 if (Op1Max == Op0Min)
4415 if (*CmpC == Op0Max - 1)
4422 assert(!isa<ConstantInt>(Op1) &&
"ICMP_SGE with ConstantInt not folded!");
4423 if (Op0Min.sge(Op1Max))
4425 if (Op0Max.
slt(Op1Min))
4427 if (Op1Min == Op0Max)
4431 assert(!isa<ConstantInt>(Op1) &&
"ICMP_SLE with ConstantInt not folded!");
4432 if (Op0Max.
sle(Op1Min))
4434 if (Op0Min.sgt(Op1Max))
4436 if (Op1Max == Op0Min)
4440 assert(!isa<ConstantInt>(Op1) &&
"ICMP_UGE with ConstantInt not folded!");
4441 if (Op0Min.uge(Op1Max))
4443 if (Op0Max.
ult(Op1Min))
4445 if (Op1Min == Op0Max)
4449 assert(!isa<ConstantInt>(Op1) &&
"ICMP_ULE with ConstantInt not folded!");
4450 if (Op0Max.
ule(Op1Min))
4452 if (Op0Min.ugt(Op1Max))
4454 if (Op1Max == Op0Min)
4500 for (
unsigned i = 0; i != NumElts; ++i) {
4505 if (isa<UndefValue>(Elt))
4565 return BinaryOperator::CreateXor(A,
B);
4573 return BinaryOperator::CreateAnd(Builder.
CreateNot(A),
B);
4581 return BinaryOperator::CreateAnd(Builder.
CreateNot(
B), A);
4589 return BinaryOperator::CreateOr(Builder.
CreateNot(A),
B);
4597 return BinaryOperator::CreateOr(Builder.
CreateNot(
B), A);
4602 bool Changed =
false;
4610 if (Op0Cplxity < Op1Cplxity ||
4618 SQ.getWithInstruction(&I)))
4619 return replaceInstUsesWith(I, V);
4624 Value *Cond, *SelectTrue, *SelectFalse;
4627 if (
Value *V = dyn_castNegVal(SelectTrue)) {
4628 if (V == SelectFalse)
4631 else if (
Value *V = dyn_castNegVal(SelectFalse)) {
4632 if (V == SelectTrue)
4693 if (
Instruction *Res = foldICmpInstWithConstant(I))
4696 if (
Instruction *Res = foldICmpInstWithConstantNotInt(I))
4700 if (
GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
4703 if (
GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
4710 assert(Op1->getType()->isPointerTy() &&
"Comparing pointer with non-pointer?");
4712 if (
Instruction *New = foldAllocaCmp(I, Alloca, Op1))
4715 if (
Instruction *New = foldAllocaCmp(I, Alloca, Op0))
4750 if (
BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4752 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
4759 if (
BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4760 Op1 = CI2->getOperand(0);
4763 if (Op0->
getType() != Op1->getType()) {
4764 if (
Constant *Op1C = dyn_cast<Constant>(Op1)) {
4768 Op1 = Builder.CreateBitCast(Op1, Op0->
getType());
4775 if (isa<CastInst>(Op0)) {
4782 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
4819 isa<IntegerType>(A->
getType())) {
4824 replaceInstUsesWith(*AddI, Result);
4825 return replaceInstUsesWith(I, Overflow);
4853 if (
auto *EVI = dyn_cast<ExtractValueInst>(Op0))
4854 if (
auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
4855 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
4870 return Changed ? &
I :
nullptr;
4876 if (!isa<ConstantFP>(RHSC))
return nullptr;
4877 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4882 if (MantissaWidth == -1)
return nullptr;
4886 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
4890 bool IsExact =
false;
4902 return replaceInstUsesWith(I, Builder.getFalse());
4905 return replaceInstUsesWith(I, Builder.getTrue());
4921 if ((
int)InputSize > MantissaWidth) {
4923 int Exp =
ilogb(RHS);
4926 if (MaxExponent < (
int)InputSize - !LHSUnsigned)
4932 if (MantissaWidth <= Exp && Exp <= (
int)InputSize - !LHSUnsigned)
4941 assert(!RHS.
isNaN() &&
"NaN comparison not already folded!");
4971 return replaceInstUsesWith(I, Builder.getTrue());
4973 return replaceInstUsesWith(I, Builder.getFalse());
4991 return replaceInstUsesWith(I, Builder.getTrue());
4992 return replaceInstUsesWith(I, Builder.getFalse());
5003 return replaceInstUsesWith(I, Builder.getTrue());
5004 return replaceInstUsesWith(I, Builder.getFalse());
5016 return replaceInstUsesWith(I, Builder.getTrue());
5017 return replaceInstUsesWith(I, Builder.getFalse());
5027 return replaceInstUsesWith(I, Builder.getTrue());
5028 return replaceInstUsesWith(I, Builder.getFalse());
5040 bool Equal = LHSUnsigned
5050 return replaceInstUsesWith(I, Builder.getTrue());
5052 return replaceInstUsesWith(I, Builder.getFalse());
5057 return replaceInstUsesWith(I, Builder.getFalse());
5069 return replaceInstUsesWith(I, Builder.getFalse());
5082 return replaceInstUsesWith(I, Builder.getTrue());
5094 return replaceInstUsesWith(I, Builder.getTrue());
5113 bool Changed =
false;
5126 SQ.getWithInstruction(&I)))
5127 return replaceInstUsesWith(I, V);
5182 if (
Constant *RHSC = dyn_cast<Constant>(Op1)) {
5183 if (
Instruction *LHSI = dyn_cast<Instruction>(Op0))
5185 case Instruction::FPExt: {
5187 FPExtInst *LHSExt = cast<FPExtInst>(LHSI);
5225 case Instruction::PHI:
5230 if (
Instruction *
NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
5233 case Instruction::SIToFP:
5234 case Instruction::UIToFP:
5238 case Instruction::FSub: {
5248 dyn_cast<GetElementPtrInst>(LHSI->
getOperand(0))) {
5252 if (
Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I))
5260 CallInst *CI = cast<CallInst>(LHSI);
5262 if (IID != Intrinsic::fabs)
5299 if (
FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0))
5300 if (
FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1))
5301 if (LHSExt->getSrcTy() == RHSExt->getSrcTy())
5302 return new FCmpInst(Pred, LHSExt->getOperand(0), RHSExt->getOperand(0));
5304 return Changed ? &
I :
nullptr;
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
APInt abs() const
Get the absolute value;.
opStatus roundToIntegral(roundingMode RM)
Value * EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
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.
Value * SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
static const fltSemantics & IEEEquad() LLVM_READNONE
BinaryOp_match< cstfp_pred_ty< is_neg_zero_fp >, RHS, Instruction::FSub > m_FNeg(const RHS &X)
Match 'fneg X' as 'fsub -0.0, X'.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
void push_back(const T &Elt)
static bool isEquality(Predicate Pred)
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Return true if the given value is known to have exactly one bit set when defined. ...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
void setSignBit()
Set the sign bit to 1.
This class is the base class for the comparison instructions.
class_match< UndefValue > m_Undef()
Match an arbitrary undef constant.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
iterator_range< use_iterator > uses()
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Type * getSrcTy() const
Return the source type, as a convenience.
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
DiagnosticInfoOptimizationBase::Argument NV
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Value * SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q)
Given operands for an FCmpInst, fold the result or return null.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Compute iterated dominance frontiers using a linear time algorithm.
BinaryOps getOpcode() const
size_type size() const
Determine the number of elements in the SetVector.
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
m_Intrinsic_Ty< Opnd0 >::Ty m_BitReverse(const Opnd0 &Op0)
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
bool dominatesAllUses(const Instruction *DI, const Instruction *UI, const BasicBlock *DB) const
True when DB dominates all uses of DI except UI.
This class represents zero extension of integer types.
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
bool isFP128Ty() const
Return true if this is 'fp128'.
APInt zext(unsigned width) const
Zero extend to a new width.
bool slt(const APInt &RHS) const
Signed less than comparison.
APInt udiv(const APInt &RHS) const
Unsigned division operation.
This class represents a function call, abstracting a target machine's calling convention.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
m_Intrinsic_Ty< Opnd0 >::Ty m_BSwap(const Opnd0 &Op0)
const Value * getTrueValue() const
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
0 1 0 0 True if ordered and less than
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
static Constant * getNUWShl(Constant *C1, Constant *C2)
1 1 1 0 True if unordered or not equal
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate, true > m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
void Add(Instruction *I)
Add - Add the specified instruction to the worklist if it isn't already in it.
bool sgt(const APInt &RHS) const
Signed greather than comparison.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
APInt trunc(unsigned width) const
Truncate to new width.
STATISTIC(NumFunctions, "Total number of functions")
bool isArithmeticShift() const
Return true if this is an arithmetic shift right.
const fltSemantics & getSemantics() const
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
bool isVectorTy() const
True if this is an instance of VectorType.
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp, const unsigned SIOpd)
Try to replace select with select operand SIOpd in SI-ICmp sequence.
bool sle(const APInt &RHS) const
Signed less or equal comparison.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
unsigned getBitWidth() const
Get the bit width of this value.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static 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...
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Intrinsic::ID getIntrinsicForCallSite(ImmutableCallSite ICS, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Value * CreateNot(Value *V, const Twine &Name="")
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
1 0 0 1 True if unordered or equal
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
bool match(Val *V, const Pattern &P)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
This class represents the LLVM 'select' instruction.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
Type * getPointerElementType() const
OverflowCheckFlavor
Specific patterns of overflow check idioms that we match.
This is the base class for all instructions that perform data casts.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
APInt shl(unsigned shiftAmt) const
Left-shift function.
uint64_t getArrayNumElements() const
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
static Instruction * canonicalizeICmpBool(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Integer compare with boolean values can always be turned into bitwise ops.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
static Value * foldICmpWithLowBitMaskedVal(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Some comparisons can be simplified.
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
The core instruction combiner logic.
0 1 0 1 True if ordered and less than or equal
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
unsigned getNumIndices() const
unsigned getActiveBits() const
Compute the number of active bits in the value.
static Instruction * transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, ICmpInst::Predicate Cond, const DataLayout &DL)
Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
static void computeSignedMinMaxValuesFromKnownBits(const KnownBits &Known, APInt &Min, APInt &Max)
Given a signed integer type and a set of known zero and one bits, compute the maximum and minimum val...
Class to represent array types.
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
This instruction compares its operands according to the predicate given to the constructor.
static Instruction * processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, ConstantInt *CI2, ConstantInt *CI1, InstCombiner &IC)
The caller has matched a pattern of the form: I = icmp ugt (add (add A, B), CI2), CI1 If this is of t...
int32_t exactLogBase2() const
This class represents a no-op cast from one type to another.
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
const APInt & getValue() const
Return the constant as an APInt value reference.
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Get a value with upper bits starting at loBit set.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
cstfp_pred_ty< is_pos_zero_fp > m_PosZeroFP()
Match a floating-point positive zero.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
int getFPMantissaWidth() const
Return the width of the mantissa of this type.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
SelectClass_match< Cond, LHS, RHS > m_Select(const Cond &C, const LHS &L, const RHS &R)
static const fltSemantics & IEEEdouble() LLVM_READNONE
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
void takeName(Value *V)
Transfer the name from V to this value.
static bool isChainSelectCmpBranch(const SelectInst *SI)
Return true when the instruction sequence within a block is select-cmp-br.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
This class represents a truncation of integer types.
ShuffleVectorClass_match< V1_t, V2_t, Mask_t > m_ShuffleVector(const V1_t &v1, const V2_t &v2, const Mask_t &m)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
static std::pair< Value *, Value * > getAsConstantIndexedAddress(Value *V, const DataLayout &DL)
Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express the input Value as a constant...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
iterator find(const_arg_type_t< KeyT > Val)
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty, true > m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Value * foldICmpWithTruncSignExtendedVal(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Some comparisons can be simplified.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
OneUse_match< T > m_OneUse(const T &SubPattern)
bool isNegative() const
Determine sign of this APInt.
static Constant * getFNeg(Constant *C)
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
bool isAllOnesValue() const
Determine if all bits are set.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static void setInsertionPoint(IRBuilder<> &Builder, Value *V, bool Before=true)
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Conditional or Unconditional Branch instruction.
static bool canRewriteGEPAsOffset(Value *Start, Value *Base, const DataLayout &DL, SetVector< Value *> &Explored)
Returns true if we can rewrite Start as a GEP with pointer Base and some integer offset.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
CastClass_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
bool isPointerTy() const
True if this is an instance of PointerType.
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.
static Constant * getAnd(Constant *C1, Constant *C2)
static ManagedStatic< OptionRegistry > OR
ConstantFP - Floating Point Values [float, double].
bool isOneValue() const
Determine if this is a value of 1.
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
static Constant * getSExtOrBitCast(Constant *C, Type *Ty)
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
bool isMinSignedValue() const
Determine if this is the smallest signed value.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
bool isMaxValue(bool isSigned) const
This function will return true iff this constant represents the largest value that may be represented...
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
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.
Instruction * visitICmpInst(ICmpInst &I)
0 1 1 1 True if ordered (no nans)
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty, true > m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
Class to represent integer types.
unsigned getIndexTypeSizeInBits(Type *Ty) const
Layout size of the index used in GEP calculation.
static Constant * getNot(Constant *C)
static Value * rewriteGEPAsOffset(Value *Start, Value *Base, const DataLayout &DL, SetVector< Value *> &Explored)
Returns a re-written value of Start as an indexed GEP using Base as a pointer.
void clearSignBit()
Set the sign bit to 0.
const Value * getCondition() const
bool eq(const APInt &RHS) const
Equality comparison.
static Constant * getAllOnesValue(Type *Ty)
bool isZero() const
Returns true if value is all zero.
Signum_match< Val_t > m_Signum(const Val_t &V)
Matches a signum pattern.
bool isSplat(unsigned SplatSizeInBits) const
Check if the APInt consists of a repeated bit pattern.
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 ...
Type * getIndexedType() const
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
void swapOperands()
Exchange the two operands to this instruction in such a way that it does not modify the semantics of ...
unsigned ceilLogBase2() const
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
static wasm::ValType getType(const TargetRegisterClass *RC)
APInt uadd_ov(const APInt &RHS, bool &Overflow) const
bool isExact() const
Determine whether the exact flag is set.
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCompareInstOperands - Attempt to constant fold a compare instruction (icmp/fcmp) with the...
Constant * getSplatValue() const
If this is a splat vector constant, meaning that all of the elements have the same value...
1 1 0 1 True if unordered, less than, or equal
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
deferredval_ty< Value > m_Deferred(Value *const &V)
A commutative-friendly version of m_Specific().
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
bool isKnownNeverNaN(const Value *V)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
static 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...
static bool hasBranchUse(ICmpInst &I)
Given an icmp instruction, return true if any use of this comparison is a branch on sign bit comparis...
InstCombineWorklist & Worklist
A worklist of the instructions that need to be simplified.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty, true > m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
bool isMinValue(bool isSigned) const
This function will return true iff this constant represents the smallest value that may be represente...
bool isEmptySet() const
Return true if this set contains no members.
0 0 1 0 True if ordered and greater than
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
static Constant * getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
static const fltSemantics & IEEEsingle() LLVM_READNONE
StructType * getStructTypeOrNull() const
unsigned getNumOperands() const
static 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...
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
bool isMaxSignedValue() const
Determine if this is the largest signed value.
This is the shared class of boolean and integer constants.
static const fltSemantics & IEEEhalf() LLVM_READNONE
SelectPatternFlavor Flavor
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
1 1 0 0 True if unordered or less than
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
unsigned ComputeNumSignBits(const Value *Op, unsigned Depth=0, const Instruction *CxtI=nullptr) const
This class represents a range of values.
LLVM_NODISCARD T pop_back_val()
bool isMaxValue() const
Determine if this is the largest unsigned value.
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
void negate()
Negate this APInt in place.
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Instruction * foldICmpWithMinMax(ICmpInst &Cmp)
Fold icmp Pred min|max(X, Y), X.
CastClass_match< OpTy, Instruction::UIToFP > m_UIToFP(const OpTy &Op)
Matches UIToFP.
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
static ConstantInt * getTrue(LLVMContext &Context)
bool isCommutative() const
Return true if the instruction is commutative:
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
void setOperand(unsigned i, Value *Val)
unsigned logBase2() const
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
unsigned getVectorNumElements() const
unsigned countTrailingOnes() const
Count the number of trailing one bits.
bool isTrueWhenEqual() const
This is just a convenience.
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...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
static Value * evaluateGEPOffsetExpression(User *GEP, InstCombiner &IC, const DataLayout &DL)
Return a value that can be used to compare the offset implied by a GEP to zero.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
CastClass_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
iterator_range< user_iterator > users()
static Constant * getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
const Value * getFalseValue() const
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...
bool isX86_FP80Ty() const
Return true if this is x86 long double.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Predicate getPredicate() const
Return the predicate for this instruction.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
uint64_t getElementOffset(unsigned Idx) const
unsigned getIntegerBitWidth() const
LLVM_NODISCARD bool empty() const
unsigned greater or equal
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty, true > m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static Constant * getOr(Constant *C1, Constant *C2)
static void computeUnsignedMinMaxValuesFromKnownBits(const KnownBits &Known, APInt &Min, APInt &Max)
Given an unsigned integer type and a set of known zero and one bits, compute the maximum and minimum ...
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
0 1 1 0 True if ordered and operands are unequal
static Instruction * foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl, const APInt &C)
Fold icmp (shl 1, Y), C.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
CastClass_match< OpTy, Instruction::SIToFP > m_SIToFP(const OpTy &Op)
Matches SIToFP.
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
static Instruction * processUMulZExtIdiom(ICmpInst &I, Value *MulVal, Value *OtherVal, InstCombiner &IC)
Recognize and process idiom involving test for multiplication overflow.
1 0 1 0 True if unordered or greater than
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
bool isMinValue() const
Determine if this is the smallest unsigned value.
OverflowResult computeOverflowForUnsignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
void swapOperands()
Exchange the two operands to this instruction in such a way that it does not modify the semantics of ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1)
Check if the order of Op0 and Op1 as operands in an ICmpInst should be swapped.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
0 0 0 1 True if ordered and equal
LLVM Value Representation.
This file provides internal interfaces used to implement the InstCombine.
1 0 1 1 True if unordered, greater than, or equal
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Returns true if the given value is known be positive (i.e.
static Constant * getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced=false)
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Instruction * visitFCmpInst(FCmpInst &I)
bool hasOneUse() const
Return true if there is exactly one user of this value.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
unsigned countLeadingOnes() const
Count the number of leading one bits.
void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
Type * getArrayElementType() const
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
static bool isVolatile(Instruction *Inst)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This class represents an extension of floating point types.
0 0 1 1 True if ordered and greater than or equal
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
BinaryOp_match< ValTy, cst_pred_ty< is_all_ones >, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
int ilogb(const IEEEFloat &Arg)
bool isNullValue() const
Determine if all bits are clear.
cmpResult compare(const APFloat &RHS) const
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.
A wrapper class for inspecting calls to intrinsic functions.
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
static Constant * getXor(Constant *C1, Constant *C2)
gep_type_iterator gep_type_begin(const User *GEP)
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
APInt usub_ov(const APInt &RHS, bool &Overflow) const