49#include "llvm/IR/IntrinsicsAArch64.h"
50#include "llvm/IR/IntrinsicsAMDGPU.h"
51#include "llvm/IR/IntrinsicsARM.h"
52#include "llvm/IR/IntrinsicsHexagon.h"
83#define DEBUG_TYPE "instcombine"
89STATISTIC(NumSimplified,
"Number of library calls simplified");
95 if (ITy->getBitWidth() < 32)
105 auto *Src =
MI->getRawSource();
107 if (!Src->hasOneUse())
117 if (!CopyDstAlign || *CopyDstAlign < DstAlign) {
118 MI->setDestAlignment(DstAlign);
124 if (!CopySrcAlign || *CopySrcAlign < SrcAlign) {
125 MI->setSourceAlignment(SrcAlign);
134 MI->setLength((uint64_t)0);
142 MI->setLength((uint64_t)0);
149 if (!MemOpLength)
return nullptr;
156 assert(
Size &&
"0-sized memory transferring should be removed already.");
166 if (*CopyDstAlign <
Size || *CopySrcAlign <
Size)
176 Value *Src =
MI->getArgOperand(1);
177 Value *Dest =
MI->getArgOperand(0);
180 L->setAlignment(*CopySrcAlign);
181 L->setAAMetadata(AACopyMD);
182 MDNode *LoopMemParallelMD =
183 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
184 if (LoopMemParallelMD)
185 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
186 MDNode *AccessGroupMD =
MI->getMetadata(LLVMContext::MD_access_group);
188 L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
194 if (LoopMemParallelMD)
195 S->
setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
197 S->
setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
202 L->setVolatile(MT->isVolatile());
205 if (
MI->isAtomic()) {
212 MI->setLength((uint64_t)0);
217 const Align KnownAlignment =
220 if (!MemSetAlign || *MemSetAlign < KnownAlignment) {
221 MI->setDestAlignment(KnownAlignment);
230 MI->setLength((uint64_t)0);
239 MI->setLength((uint64_t)0);
249 assert(Len &&
"0-sized memory setting should be removed already.");
250 const Align Alignment =
MI->getDestAlign().valueOrOne();
256 if (
MI->isAtomic() && Alignment < Len)
267 FillVal = ConstantInt::get(
MI->getContext(),
278 DbgAssign->replaceVariableLocationOp(Fill, FillVal);
286 MI->setLength((uint64_t)0);
296 Value *LoadPtr =
II.getArgOperand(0);
297 const Align Alignment =
II.getParamAlign(0).valueOrOne();
298 Value *Mask =
II.getArgOperand(1);
303 LoadInst *L = Builder.CreateAlignedLoad(
II.getType(), LoadPtr, Alignment,
313 LoadInst *LI = Builder.CreateAlignedLoad(
II.getType(), LoadPtr, Alignment,
316 return Builder.CreateSelect(
II.getArgOperand(1), LI,
II.getArgOperand(2));
326 Value *StorePtr =
II.getArgOperand(1);
340 new StoreInst(
II.getArgOperand(0), StorePtr,
false, Alignment);
372 if (ConstMask->isAllOnesValue())
376 LoadInst *
L =
Builder.CreateAlignedLoad(VecTy->getElementType(), SplatPtr,
377 Alignment,
"load.scalar");
379 Builder.CreateVectorSplat(VecTy->getElementCount(), L,
"broadcast");
406 StoreInst *S =
new StoreInst(SplatValue, SplatPtr,
false,
414 if (ConstMask->isAllOnesValue()) {
417 ElementCount VF = WideLoadTy->getElementCount();
421 Builder.CreateExtractElement(
II.getArgOperand(0), LastLane);
423 new StoreInst(Extract, SplatPtr,
false, Alignment);
450 auto *Arg =
II.getArgOperand(0);
451 auto *StrippedArg = Arg->stripPointerCasts();
452 auto *StrippedInvariantGroupsArg = StrippedArg;
454 if (Intr->getIntrinsicID() != Intrinsic::launder_invariant_group)
456 StrippedInvariantGroupsArg = Intr->getArgOperand(0)->stripPointerCasts();
458 if (StrippedArg == StrippedInvariantGroupsArg)
463 if (Result->getType()->getPointerAddressSpace() !=
464 II.getType()->getPointerAddressSpace())
471 assert((
II.getIntrinsicID() == Intrinsic::cttz ||
472 II.getIntrinsicID() == Intrinsic::ctlz) &&
473 "Expected cttz or ctlz intrinsic");
474 bool IsTZ =
II.getIntrinsicID() == Intrinsic::cttz;
475 Value *Op0 =
II.getArgOperand(0);
476 Value *Op1 =
II.getArgOperand(1);
487 if (
II.getType()->isIntOrIntVectorTy(1)) {
501 {Op0, IC.Builder.getTrue()});
551 return BinaryOperator::CreateAdd(ConstCttz,
X);
559 return BinaryOperator::CreateSub(ConstCttz,
X);
565 ConstantInt::get(
II.getType(),
II.getType()->getScalarSizeInBits());
566 return BinaryOperator::CreateSub(Width,
X);
574 return BinaryOperator::CreateAdd(ConstCtlz,
X);
582 return BinaryOperator::CreateSub(ConstCtlz,
X);
590 unsigned BitWidth = Ty->getScalarSizeInBits();
604 ConstantInt::get(R->getType(), R->getType()->getScalarSizeInBits() - 1),
614 unsigned PossibleZeros = IsTZ ?
Known.countMaxTrailingZeros()
615 :
Known.countMaxLeadingZeros();
616 unsigned DefiniteZeros = IsTZ ?
Known.countMinTrailingZeros()
617 :
Known.countMinLeadingZeros();
623 if (PossibleZeros == DefiniteZeros) {
624 auto *
C = ConstantInt::get(Op0->
getType(), DefiniteZeros);
631 if (!
Known.One.isZero() ||
635 {Op0, IC.Builder.getTrue()});
640 if (
BitWidth != 1 && !
II.hasRetAttr(Attribute::Range) &&
641 !
II.getMetadata(LLVMContext::MD_range)) {
652 assert(
II.getIntrinsicID() == Intrinsic::ctpop &&
653 "Expected ctpop intrinsic");
655 unsigned BitWidth = Ty->getScalarSizeInBits();
656 Value *Op0 =
II.getArgOperand(0);
702 if ((~
Known.Zero).isPowerOf2())
703 return BinaryOperator::CreateLShr(
704 Op0, ConstantInt::get(Ty, (~
Known.Zero).exactLogBase2()));
718 II.getRange().value_or(ConstantRange::getFull(
BitWidth));
721 unsigned Upper =
Known.countMaxPopulation() + 1;
730 if (
Range != OldRange) {
749 unsigned NumIndexes = RetTy->getNumElements();
752 if (!RetTy->getElementType()->isIntegerTy(8) ||
753 (NumIndexes != 8 && NumIndexes != 16))
758 unsigned int StartIndex = (
unsigned)IsExtension;
764 unsigned NumElementsPerSource = SourceTy->getNumElements();
770 if (NumIndexes > NumElementsPerSource)
775 unsigned int NumSourceOperands =
II.arg_size() - 1 - (
unsigned)IsExtension;
785 for (
unsigned I = 0;
I < NumIndexes; ++
I) {
799 unsigned SourceOperandIndex = Index / NumElementsPerSource;
801 unsigned SourceOperandElementIndex = Index % NumElementsPerSource;
803 Value *SourceOperand;
804 if (SourceOperandIndex >= NumSourceOperands) {
807 SourceOperandIndex = NumSourceOperands;
811 SourceOperand =
II.getArgOperand(0);
812 SourceOperandElementIndex =
I;
817 SourceOperandElementIndex = 0;
820 SourceOperand =
II.getArgOperand(SourceOperandIndex + StartIndex);
828 NumElementsPerSource)
833 unsigned NumSlots = ValueToShuffleSlot.
size();
836 if (NumSlots == 2 && !ValueToShuffleSlot.
contains(SourceOperand))
839 auto [It, Inserted] =
840 ValueToShuffleSlot.
try_emplace(SourceOperand, NumSlots);
842 ShuffleOperands[It->getSecond()] = SourceOperand;
844 unsigned RemappedIndex =
845 (It->getSecond() * NumElementsPerSource) + SourceOperandElementIndex;
846 Indexes[
I] = RemappedIndex;
850 ShuffleOperands[0], ShuffleOperands[1],
ArrayRef(Indexes, NumIndexes));
857 unsigned NumOperands) {
858 assert(
I.arg_size() >= NumOperands &&
"Not enough operands");
859 assert(
E.arg_size() >= NumOperands &&
"Not enough operands");
860 for (
unsigned i = 0; i < NumOperands; i++)
861 if (
I.getArgOperand(i) !=
E.getArgOperand(i))
882 for (; BI != BE; ++BI) {
884 if (
I->isDebugOrPseudoInst() ||
907 return II.getIntrinsicID() == Intrinsic::vastart ||
908 (
II.getIntrinsicID() == Intrinsic::vacopy &&
909 I.getArgOperand(0) !=
II.getArgOperand(1));
915 assert(
Call.arg_size() > 1 &&
"Need at least 2 args to swap");
916 Value *Arg0 =
Call.getArgOperand(0), *Arg1 =
Call.getArgOperand(1);
918 Call.setArgOperand(0, Arg1);
919 Call.setArgOperand(1, Arg0);
924 Call.setAttributes(CallAttr
925 .setAttributesAtIndex(
926 Ctx, AttributeList::FirstArgIndex + 0, RHSAttr)
927 .setAttributesAtIndex(
928 Ctx, AttributeList::FirstArgIndex + 1, LHSAttr));
947 Value *OperationResult =
nullptr;
954 for (User *U : WO->
users()) {
958 for (
auto &AssumeVH :
AC.assumptionsFor(U)) {
972 Inst->setHasNoSignedWrap();
974 Inst->setHasNoUnsignedWrap();
985 Ty = Ty->getScalarType();
990 Ty = Ty->getScalarType();
991 return F.getDenormalMode(Ty->getFltSemantics()).inputsAreZero();
998 return Mode.inputsMayBePositiveZero() ||
Mode.outputsMayBePositiveZero();
1006 switch (
static_cast<unsigned>(Mask)) {
1063 Value *Src0 =
II.getArgOperand(0);
1064 Value *Src1 =
II.getArgOperand(1);
1070 const FPClassTest OrderedInvertedMask = ~OrderedMask & ~fcNan;
1072 const bool IsStrict =
1073 II.getFunction()->getAttributes().hasFnAttr(Attribute::StrictFP);
1079 II.getCalledFunction(),
1080 {FNegSrc, ConstantInt::get(Src1->getType(), fneg(Mask))});
1085 II.getCalledFunction(),
1086 {FAbsSrc, ConstantInt::get(Src1->getType(), inverse_fabs(Mask))});
1088 if ((OrderedMask ==
fcInf || OrderedInvertedMask ==
fcInf) &&
1089 (IsOrdered || IsUnordered) && !IsStrict) {
1097 if (OrderedInvertedMask ==
fcInf)
1107 (IsOrdered || IsUnordered) && !IsStrict) {
1114 Value *EqInf = IsUnordered ?
Builder.CreateFCmpUEQ(Src0, Inf)
1115 :
Builder.CreateFCmpOEQ(Src0, Inf);
1121 if ((OrderedInvertedMask ==
fcPosInf || OrderedInvertedMask ==
fcNegInf) &&
1122 (IsOrdered || IsUnordered) && !IsStrict) {
1129 Value *NeInf = IsUnordered ?
Builder.CreateFCmpUNE(Src0, Inf)
1130 :
Builder.CreateFCmpONE(Src0, Inf);
1135 if (Mask ==
fcNan && !IsStrict) {
1167 if (!IsStrict && (IsOrdered || IsUnordered) &&
1181 KnownFPClass
Known =
1187 if (
Known.isKnownAlways(Mask))
1193 if ((Mask &
Known.getKnownFPClasses()) != Mask) {
1195 1, ConstantInt::get(Src1->
getType(), Mask &
Known.getKnownFPClasses()));
1204 if (
Known.isNonNegative())
1206 if (
Known.isNegative())
1213 return std::nullopt;
1225 return std::nullopt;
1237 return *Known0 == *Known1;
1252 int SignedMax =
static_cast<int>(
maxIntN(ExpBits));
1253 int SignedMin =
static_cast<int>(
minIntN(ExpBits));
1266 assert((MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin ||
1267 MinMaxID == Intrinsic::umax || MinMaxID == Intrinsic::umin) &&
1268 "Expected a min or max intrinsic");
1271 Value *Op0 =
II->getArgOperand(0), *Op1 =
II->getArgOperand(1);
1273 const APInt *C0, *C1;
1279 bool IsSigned = MinMaxID == Intrinsic::smax || MinMaxID == Intrinsic::smin;
1281 if ((IsSigned && !
Add->hasNoSignedWrap()) ||
1282 (!IsSigned && !
Add->hasNoUnsignedWrap()))
1289 IsSigned ? C1->
ssub_ov(*C0, Overflow) : C1->
usub_ov(*C0, Overflow);
1290 assert(!Overflow &&
"Expected simplify of min/max");
1294 Constant *NewMinMaxC = ConstantInt::get(
II->getType(), CDiff);
1295 Value *NewMinMax = Builder.CreateBinaryIntrinsic(MinMaxID,
X, NewMinMaxC);
1296 return IsSigned ? BinaryOperator::CreateNSWAdd(NewMinMax,
Add->getOperand(1))
1297 : BinaryOperator::CreateNUWAdd(NewMinMax,
Add->getOperand(1));
1308 const APInt *MinValue, *MaxValue;
1312 }
else if (
match(&MinMax1,
1321 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
1324 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
1338 if (
AddSub->getOpcode() == Instruction::Add)
1339 IntrinsicID = Intrinsic::sadd_sat;
1340 else if (
AddSub->getOpcode() == Instruction::Sub)
1341 IntrinsicID = Intrinsic::ssub_sat;
1354 Value *Sat =
Builder.CreateIntrinsic(IntrinsicID, NewTy, {AT,
BT});
1364 Value *I0 =
II->getArgOperand(0), *I1 =
II->getArgOperand(1);
1366 const APInt *C0, *C1;
1371 switch (
II->getIntrinsicID()) {
1372 case Intrinsic::smax:
1376 case Intrinsic::smin:
1380 case Intrinsic::umax:
1384 case Intrinsic::umin:
1396 Value *Cmp = Builder.CreateICmp(Pred,
X, I1);
1420 if (InnerMinMaxID != MinMaxID &&
1421 !(((MinMaxID == Intrinsic::umax && InnerMinMaxID == Intrinsic::smax) ||
1422 (MinMaxID == Intrinsic::smin && InnerMinMaxID == Intrinsic::umin)) &&
1427 Value *CondC = Builder.CreateICmp(Pred, C0, C1);
1428 Value *NewC = Builder.CreateSelect(CondC, C0, C1);
1429 return Builder.CreateIntrinsic(InnerMinMaxID,
II->getType(),
1430 {LHS->getArgOperand(0), NewC});
1451 if (!InnerMM || InnerMM->getIntrinsicID() != MinMaxID ||
1457 MinMaxID,
II->getType());
1458 Value *NewInner = Builder.CreateBinaryIntrinsic(MinMaxID,
X,
Y);
1469 if (!
LHS || !
RHS ||
LHS->getIntrinsicID() != MinMaxID ||
1470 RHS->getIntrinsicID() != MinMaxID ||
1471 (!
LHS->hasOneUse() && !
RHS->hasOneUse()))
1480 Value *MinMaxOp =
nullptr;
1481 Value *ThirdOp =
nullptr;
1482 if (
LHS->hasOneUse()) {
1485 if (
D ==
A ||
C ==
A) {
1490 }
else if (
D ==
B ||
C ==
B) {
1497 assert(
RHS->hasOneUse() &&
"Expected one-use operand");
1499 if (
D ==
A ||
D ==
B) {
1504 }
else if (
C ==
A ||
C ==
B) {
1512 if (!MinMaxOp || !ThirdOp)
1525 if (!
II->getType()->isVectorTy() ||
1527 !
II->getCalledFunction()->isSpeculatable())
1534 return isa<Constant>(Arg.get()) ||
1535 isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(),
1536 Arg.getOperandNo(), nullptr);
1549 Type *SrcTy =
X->getType();
1550 for (
Use &Arg :
II->args()) {
1554 else if (
match(&Arg,
1556 X->getType() == SrcTy)
1575 Value *NewIntrinsic =
1576 Builder.CreateIntrinsic(ResTy,
II->getIntrinsicID(), NewArgs, FPI);
1583 if (!
II->getType()->isVectorTy() ||
1590 return match(V, m_OneUse(m_VecReverse(m_Value())));
1597 for (
Use &Arg :
II->args()) {
1599 Arg.getOperandNo(),
nullptr))
1614 II->getType(),
II->getIntrinsicID(), NewArgs, FPI);
1615 return Builder.CreateVectorReverse(NewIntrinsic);
1621template <Intrinsic::ID IntrID>
1624 static_assert(IntrID == Intrinsic::bswap || IntrID == Intrinsic::bitreverse,
1625 "This helper only supports BSWAP and BITREVERSE intrinsics");
1632 Value *OldReorderX, *OldReorderY;
1645 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID,
Y);
1650 Value *NewReorder = Builder.CreateUnaryIntrinsic(IntrID,
X);
1661 case Intrinsic::smax:
1662 case Intrinsic::smin:
1663 case Intrinsic::umax:
1664 case Intrinsic::umin:
1665 case Intrinsic::maximum:
1666 case Intrinsic::minimum:
1667 case Intrinsic::maximumnum:
1668 case Intrinsic::minimumnum:
1669 case Intrinsic::maxnum:
1670 case Intrinsic::minnum:
1689 auto IID =
II->getIntrinsicID();
1695 auto *InvariantBinaryInst =
1699 return InvariantBinaryInst;
1703 if (!CanReorderLanes)
1716 int Sz = Mask.size();
1718 for (
int Idx : Mask) {
1721 UsedIndices.
set(Idx);
1726 return UsedIndices.
all() ? V :
nullptr;
1735template <Intrinsic::ID IntrID>
1740 static_assert(IntrID == Intrinsic::cttz || IntrID == Intrinsic::ctlz,
1741 "This helper only supports cttz and ctlz intrinsics");
1743 Value *CtOp1, *CtOp2;
1744 Value *ZeroUndef1, *ZeroUndef2;
1751 return Builder.CreateBinaryIntrinsic(
1752 IntrID, Builder.CreateOr(CtOp1, CtOp2),
1753 Builder.CreateOr(ZeroUndef1, ZeroUndef2));
1755 unsigned BitWidth = I1->getType()->getScalarSizeInBits();
1762 Type *Ty = I1->getType();
1764 IntrID == Intrinsic::cttz ? Instruction::Shl : Instruction::LShr,
1765 IntrID == Intrinsic::cttz
1766 ? ConstantInt::get(Ty, 1)
1769 return Builder.CreateBinaryIntrinsic(
1770 IntrID, Builder.CreateOr(CtOp1, NewConst),
1779 case Intrinsic::umax:
1780 case Intrinsic::umin:
1781 if (HasNUW && LOp == Instruction::Add)
1783 if (HasNUW && LOp == Instruction::Shl)
1786 case Intrinsic::smax:
1787 case Intrinsic::smin:
1788 return HasNSW && LOp == Instruction::Add;
1801 case Intrinsic::umax:
1802 case Intrinsic::umin:
1803 return HasNUW && LOp == Instruction::Sub;
1804 case Intrinsic::smax:
1805 case Intrinsic::smin:
1806 return HasNSW && LOp == Instruction::Sub;
1846 if (
A ==
D ||
B ==
C)
1854 Value *NewIntrinsic = Builder.CreateBinaryIntrinsic(TopLevelOpcode,
B,
D);
1855 return Builder.CreateNoWrapBinOp(InnerOpcode,
A, NewIntrinsic, HasNUW,
1860 Value *NewIntrinsic = Builder.CreateBinaryIntrinsic(TopLevelOpcode,
A,
C);
1861 return Builder.CreateNoWrapBinOp(InnerOpcode, NewIntrinsic,
B, HasNUW,
1868 Value *Arg0 =
II->getArgOperand(0);
1874 bool AllPositive =
true;
1875 bool AllNegative =
true;
1879 const APInt &V = CI->getValue();
1880 if (V.isNonNegative()) {
1881 AllNegative =
false;
1882 return AllPositive && V.ult(ElemBits);
1884 AllPositive =
false;
1885 return AllNegative && V.sgt(-ElemBits);
1891 for (
unsigned I = 0,
E = VTy->getNumElements();
I <
E; ++
I) {
1892 if (!
Check(ShiftConst->getAggregateElement(
I)))
1896 }
else if (!
Check(ShiftConst))
1903 Value *NegAmt =
B.CreateNeg(ShiftConst);
1905 const bool IsSigned =
1906 IID == Intrinsic::arm_neon_vshifts || IID == Intrinsic::aarch64_neon_sshl;
1908 IsSigned ?
B.CreateAShr(Arg0, NegAmt) :
B.CreateLShr(Arg0, NegAmt);
1919 bool IsSin = IID == Intrinsic::sin;
1920 Intrinsic::ID MatchID = IsSin ? Intrinsic::cos : Intrinsic::sin;
1922 Value *Arg =
II->getArgOperand(0);
1932 if (Cand !=
II && !Cand->use_empty() &&
1933 Cand->getIntrinsicID() == MatchID) {
1946 std::optional<BasicBlock::iterator> InsertPt =
1947 ArgInst->getInsertionPointAfterDef();
1950 B.SetInsertPoint(*InsertPt);
1952 BasicBlock &EntryBB =
II->getFunction()->getEntryBlock();
1953 B.SetInsertPoint(&EntryBB, EntryBB.
begin());
1957 II->getModule(), Intrinsic::sincos, Arg->
getType());
1958 CallInst *SinCos =
B.CreateCall(SinCosFunc, Arg,
"sincos");
1963 II->getMetadata(LLVMContext::MD_fpmath),
1966 Value *Sin =
B.CreateExtractValue(SinCos, 0,
"sin");
1967 Value *Cos =
B.CreateExtractValue(SinCos, 1,
"cos");
1972 return IsSin ? Sin : Cos;
1987 unsigned ExtIdx = 0;
1997 Type *NarrowTy =
X->getType();
2001 Value *OtherOp =
II->getArgOperand(1 - ExtIdx);
2006 Y->getType() != NarrowTy)
2021 II->getIntrinsicID() == Intrinsic::scmp && CastOpc == Instruction::SExt
2026 return Builder.CreateIntrinsic(
II->getType(), NewIID, {X, Y});
2038 SQ.getWithInstruction(&CI)))
2054 return visitCallBase(CI);
2059 if (
auto NumBytes =
MI->getLengthInBytes()) {
2061 if (NumBytes->isZero())
2066 if (
MI->isAtomic() &&
2067 (NumBytes->isNegative() ||
2068 (NumBytes->getZExtValue() %
MI->getElementSizeInBytes() != 0))) {
2070 assert(
MI->getType()->isVoidTy() &&
2071 "non void atomic unordered mem intrinsic");
2077 if (
MI->isVolatile())
2082 if (MTI->getSource() == MTI->getDest())
2086 auto IsPointerUndefined = [
MI](
Value *Ptr) {
2092 bool SrcIsUndefined =
false;
2098 SrcIsUndefined = IsPointerUndefined(MTI->getRawSource());
2105 if (SrcIsUndefined || IsPointerUndefined(
MI->getRawDest())) {
2115 if (GVSrc->isConstant()) {
2119 ? Intrinsic::memcpy_element_unordered_atomic
2120 : Intrinsic::memcpy;
2134 auto VWidth = IIFVTy->getNumElements();
2135 APInt PoisonElts(VWidth, 0);
2144 if (
II->isCommutative()) {
2145 if (
auto Pair = matchSymmetricPair(
II->getOperand(0),
II->getOperand(1))) {
2148 II->dropPoisonGeneratingAnnotations();
2149 II->dropUBImplyingAttrsAndMetadata();
2168 case Intrinsic::objectsize: {
2171 &InsertedInstructions)) {
2172 for (
Instruction *Inserted : InsertedInstructions)
2178 case Intrinsic::abs: {
2179 Value *IIOperand =
II->getArgOperand(0);
2186 II->getCalledFunction(),
2188 Builder.getInt1(IntMinIsPoison ||
2189 cast<Instruction>(IIOperand)->hasNoSignedWrap())});
2193 {X, II->getArgOperand(1)});
2197 if (
match(IIOperand,
2204 {XY, II->getArgOperand(1)});
2207 if (std::optional<bool>
Known =
2233 return BinaryOperator::CreateAnd(
X, ConstantInt::get(
II->getType(), 1));
2237 case Intrinsic::umin: {
2238 Value *I0 =
II->getArgOperand(0), *I1 =
II->getArgOperand(1);
2241 assert(
II->getType()->getScalarSizeInBits() != 1 &&
2242 "Expected simplify of umin with max constant");
2248 if (
Value *FoldedCttz =
2253 if (
Value *FoldedCtlz =
2259 case Intrinsic::umax: {
2260 Value *I0 =
II->getArgOperand(0), *I1 =
II->getArgOperand(1);
2263 (I0->
hasOneUse() || I1->hasOneUse()) &&
X->getType() ==
Y->getType()) {
2271 Value *NarrowMaxMin =
Builder.CreateBinaryIntrinsic(IID,
X, NarrowC);
2290 Value *Cmp =
Builder.CreateICmpEQ(
X, ConstantInt::get(
X->getType(), 0));
2291 Value *NewSelect =
nullptr;
2292 NewSelect =
Builder.CreateSelectWithUnknownProfile(
2293 Cmp, ConstantInt::get(
X->getType(), 1),
A,
DEBUG_TYPE);
2297 if (IID == Intrinsic::umax) {
2308 case Intrinsic::smax:
2309 case Intrinsic::smin: {
2310 Value *I0 =
II->getArgOperand(0), *I1 =
II->getArgOperand(1);
2313 (I0->
hasOneUse() || I1->hasOneUse()) &&
X->getType() ==
Y->getType()) {
2322 Value *NarrowMaxMin =
Builder.CreateBinaryIntrinsic(IID,
X, NarrowC);
2329 const APInt *MinC, *MaxC;
2330 auto CreateCanonicalClampForm = [&](
bool IsSigned) {
2331 auto MaxIID = IsSigned ? Intrinsic::smax : Intrinsic::umax;
2332 auto MinIID = IsSigned ? Intrinsic::smin : Intrinsic::umin;
2334 MaxIID,
X, ConstantInt::get(
X->getType(), *MaxC));
2337 MinIID, NewMax, ConstantInt::get(
X->getType(), *MinC)));
2339 if (IID == Intrinsic::smax &&
2343 return CreateCanonicalClampForm(
true);
2344 if (IID == Intrinsic::umax &&
2348 return CreateCanonicalClampForm(
false);
2352 if ((IID == Intrinsic::umin || IID == Intrinsic::smax) &&
2353 II->getType()->isIntOrIntVectorTy(1)) {
2354 return BinaryOperator::CreateAnd(I0, I1);
2359 if ((IID == Intrinsic::umax || IID == Intrinsic::smin) &&
2360 II->getType()->isIntOrIntVectorTy(1)) {
2361 return BinaryOperator::CreateOr(I0, I1);
2369 if (IID == Intrinsic::smin) {
2372 Value *Zero = ConstantInt::get(
X->getType(), 0);
2375 Builder.CreateIntrinsic(
II->getType(), Intrinsic::scmp, {X, Zero}));
2379 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
2406 bool UseOr = IID == Intrinsic::smax || IID == Intrinsic::umax;
2407 bool UseAndN = IID == Intrinsic::smin || IID == Intrinsic::umin;
2409 if (IID == Intrinsic::smax || IID == Intrinsic::smin) {
2411 if (KnownSign == std::nullopt) {
2414 }
else if (*KnownSign ) {
2426 return BinaryOperator::CreateOr(I0,
X);
2428 return BinaryOperator::CreateAnd(I0,
Builder.CreateNot(
X));
2444 Value *InvMaxMin =
Builder.CreateBinaryIntrinsic(InvID,
A, NotY);
2463 return BinaryOperator::CreateAnd(
Builder.CreateBinaryIntrinsic(IID,
X,
Y),
2464 ConstantInt::get(
II->getType(), *RHSC));
2474 if (I0->
hasOneUse() && !I1->hasOneUse())
2486 if (IID == Intrinsic::smin || IID == Intrinsic::umax)
2487 Abs =
Builder.CreateNeg(Abs,
"nabs", IntMinIsPoison);
2512 I0, IsSigned,
SQ.getWithInstruction(
II));
2514 if (LHS_CR.
icmp(Pred, *RHSC))
2518 ConstantInt::get(
II->getType(), *RHSC));
2527 case Intrinsic::scmp:
2528 case Intrinsic::ucmp: {
2532 if (IID == Intrinsic::ucmp)
2535 Value *I0 =
II->getArgOperand(0), *I1 =
II->getArgOperand(1);
2540 SQ.getWithInstruction(
II));
2541 if (
Range.getSignedMin().sge(-1) &&
Range.getSignedMax().sle(1))
2543 CI,
Builder.CreateSExtOrTrunc(I0,
II->getType()));
2549 Builder.CreateIntrinsic(
II->getType(), Intrinsic::scmp, {LHS, RHS}));
2552 case Intrinsic::bitreverse: {
2553 Value *IIOperand =
II->getArgOperand(0);
2557 X->getType()->isIntOrIntVectorTy(1)) {
2558 Type *Ty =
II->getType();
2571 return crossLogicOpFold;
2575 case Intrinsic::bswap: {
2576 Value *IIOperand =
II->getArgOperand(0);
2586 Value *NewSwap =
Builder.CreateUnaryIntrinsic(Intrinsic::bswap,
X);
2598 unsigned BW =
Known.getBitWidth();
2601 if (BW - LZ - TZ == 8) {
2602 assert(LZ != TZ &&
"active byte cannot be in the middle");
2604 return BinaryOperator::CreateNUWShl(
2605 IIOperand, ConstantInt::get(IIOperand->
getType(), LZ - TZ));
2607 return BinaryOperator::CreateExactLShr(
2608 IIOperand, ConstantInt::get(IIOperand->
getType(), TZ - LZ));
2613 unsigned C =
X->getType()->getScalarSizeInBits() - BW;
2614 Value *CV = ConstantInt::get(
X->getType(),
C);
2621 return crossLogicOpFold;
2630 case Intrinsic::masked_load:
2631 if (
Value *SimplifiedMaskedOp = simplifyMaskedLoad(*
II))
2634 case Intrinsic::masked_store:
2635 return simplifyMaskedStore(*
II);
2636 case Intrinsic::masked_gather:
2637 return simplifyMaskedGather(*
II);
2638 case Intrinsic::masked_scatter:
2639 return simplifyMaskedScatter(*
II);
2640 case Intrinsic::launder_invariant_group:
2644 case Intrinsic::powi: {
2648 if (Power->isMinusOne())
2650 II->getArgOperand(0),
II);
2652 if (Power->equalsInt(2))
2654 II->getArgOperand(0),
II);
2656 if (!Power->getValue()[0]) {
2670 Value *Exp =
II->getArgOperand(1);
2673 if (
II->hasApproxFunc() &&
Base->isExactlyValue(2.0)) {
2676 Exp =
Builder.CreateVectorSplat(VTy->getElementCount(), Exp);
2684 case Intrinsic::cttz:
2685 case Intrinsic::ctlz:
2690 case Intrinsic::ctpop:
2695 case Intrinsic::fshl:
2696 case Intrinsic::fshr: {
2697 Value *Op0 =
II->getArgOperand(0), *Op1 =
II->getArgOperand(1);
2698 Type *Ty =
II->getType();
2699 unsigned BitWidth = Ty->getScalarSizeInBits();
2708 if (ModuloC != ShAmtC)
2714 "Shift amount expected to be modulo bitwidth");
2719 if (IID == Intrinsic::fshr) {
2730 assert(IID == Intrinsic::fshl &&
2731 "All funnel shifts by simple constants should go left");
2736 return BinaryOperator::CreateShl(Op0, ShAmtC);
2743 return BinaryOperator::CreateLShr(Op1,
2761 const APInt *ShAmtInnerC, *ShAmtOuterC;
2765 APInt Sum = *ShAmtOuterC + *ShAmtInnerC;
2769 Constant *ModuloC = ConstantInt::get(Ty, Modulo);
2771 {InnerOp, InnerOp, ModuloC});
2783 Mod, IID == Intrinsic::fshl ? Intrinsic::fshr : Intrinsic::fshl, Ty);
2791 Value *Op2 =
II->getArgOperand(2);
2793 return BinaryOperator::CreateShl(Op0,
And);
2811 case Intrinsic::pdep: {
2814 unsigned MaskIdx, MaskLen;
2820 Value *ShiftAmt = ConstantInt::get(
II->getType(), MaskIdx);
2828 case Intrinsic::pext: {
2831 unsigned MaskIdx, MaskLen;
2838 Value *ShiftAmt = ConstantInt::get(
II->getType(), MaskIdx);
2845 case Intrinsic::ptrmask: {
2846 unsigned BitWidth =
DL.getPointerTypeSizeInBits(
II->getType());
2851 Value *InnerPtr, *InnerMask;
2856 if (
match(
II->getArgOperand(0),
2860 "Mask types must match");
2863 Value *NewMask =
Builder.CreateAnd(
II->getArgOperand(1), InnerMask);
2871 (
Known.isNonZero() ||
2877 unsigned NewAlignmentLog =
2892 case Intrinsic::smulh: {
2893 Value *Arg0 =
II->getArgOperand(0);
2894 Value *Arg1 =
II->getArgOperand(1);
2895 unsigned BitWidth =
II->getType()->getScalarSizeInBits();
2903 case Intrinsic::uadd_with_overflow:
2904 case Intrinsic::sadd_with_overflow: {
2912 const APInt *C0, *C1;
2913 Value *Arg0 =
II->getArgOperand(0);
2914 Value *Arg1 =
II->getArgOperand(1);
2915 bool IsSigned = IID == Intrinsic::sadd_with_overflow;
2916 bool HasNWAdd = IsSigned
2922 IsSigned ? C1->
sadd_ov(*C0, Overflow) : C1->
uadd_ov(*C0, Overflow);
2926 IID,
X, ConstantInt::get(Arg1->
getType(), NewC)));
2931 case Intrinsic::umul_with_overflow:
2932 case Intrinsic::smul_with_overflow:
2933 case Intrinsic::usub_with_overflow:
2938 case Intrinsic::ssub_with_overflow: {
2943 Value *Arg0 =
II->getArgOperand(0);
2944 Value *Arg1 =
II->getArgOperand(1);
2954 *
II,
Builder.CreateBinaryIntrinsic(Intrinsic::sadd_with_overflow,
2961 case Intrinsic::uadd_sat:
2962 case Intrinsic::sadd_sat:
2963 case Intrinsic::usub_sat:
2964 case Intrinsic::ssub_sat: {
2966 Type *Ty =
SI->getType();
2982 unsigned BitWidth = Ty->getScalarSizeInBits();
2987 unsigned BitWidth = Ty->getScalarSizeInBits();
2999 if (IID == Intrinsic::usub_sat &&
3002 auto *NewC =
Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat,
C, C1);
3004 Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, NewC,
A);
3010 C->isNotMinSignedValue()) {
3014 Intrinsic::sadd_sat, Arg0, NegVal));
3022 const APInt *Val, *Val2;
3025 IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
3026 if (
Other->getIntrinsicID() == IID &&
3034 NewVal = Val->
sadd_ov(*Val2, Overflow);
3047 IID,
X, ConstantInt::get(
II->getType(), NewVal)));
3053 case Intrinsic::minnum:
3054 case Intrinsic::maxnum:
3055 case Intrinsic::minimumnum:
3056 case Intrinsic::maximumnum:
3057 case Intrinsic::minimum:
3058 case Intrinsic::maximum: {
3059 Value *Arg0 =
II->getArgOperand(0);
3060 Value *Arg1 =
II->getArgOperand(1);
3069 case Intrinsic::maxnum:
3070 NewIID = Intrinsic::minnum;
3072 case Intrinsic::minnum:
3073 NewIID = Intrinsic::maxnum;
3075 case Intrinsic::maximumnum:
3076 NewIID = Intrinsic::minimumnum;
3078 case Intrinsic::minimumnum:
3079 NewIID = Intrinsic::maximumnum;
3081 case Intrinsic::maximum:
3082 NewIID = Intrinsic::minimum;
3084 case Intrinsic::minimum:
3085 NewIID = Intrinsic::maximum;
3091 Instruction *FNeg = UnaryOperator::CreateFNeg(NewCall);
3106 case Intrinsic::maxnum:
3109 case Intrinsic::minnum:
3112 case Intrinsic::maximumnum:
3115 case Intrinsic::minimumnum:
3118 case Intrinsic::maximum:
3121 case Intrinsic::minimum:
3131 IID,
X, ConstantFP::get(Arg0->
getType(), Res),
3140 X->getType() ==
Y->getType()) {
3142 Builder.CreateBinaryIntrinsic(IID,
X,
Y,
II,
II->getName());
3153 Builder.CreateBinaryIntrinsic(IID,
X, TruncC,
II,
II->getName());
3164 auto IsMinMaxOrXNegX = [IID, &
X](
Value *Op0,
Value *Op1) {
3166 return Op0->hasOneUse() ||
3167 (IID != Intrinsic::minimum && IID != Intrinsic::minnum &&
3168 IID != Intrinsic::minimumnum);
3172 if (IsMinMaxOrXNegX(Arg0, Arg1) || IsMinMaxOrXNegX(Arg1, Arg0)) {
3174 if (IID == Intrinsic::minimum || IID == Intrinsic::minnum ||
3175 IID == Intrinsic::minimumnum)
3182 case Intrinsic::matrix_multiply: {
3194 Value *Op0 =
II->getOperand(0);
3195 Value *Op1 =
II->getOperand(1);
3196 Value *OpNotNeg, *NegatedOp;
3197 unsigned NegatedOpArg, OtherOpArg;
3214 Value *OtherOp =
II->getOperand(OtherOpArg);
3232 NewArgs[NegatedOpArg] = OpNotNeg;
3238 case Intrinsic::fmuladd: {
3242 II->getFastMathFlags(),
SQ.getWithInstruction(
II)))
3244 II->getFastMathFlags());
3248 case Intrinsic::fma: {
3250 Value *Src0 =
II->getArgOperand(0);
3251 Value *Src1 =
II->getArgOperand(1);
3252 Value *Src2 =
II->getArgOperand(2);
3256 *
II,
Builder.CreateIntrinsic(IID,
II->getType(), {X, Y, Src2},
II));
3261 *
II,
Builder.CreateIntrinsic(IID,
II->getType(), {X, X, Src2},
II));
3266 SQ.getWithInstruction(
II)))
3282 case Intrinsic::copysign: {
3283 Value *Mag =
II->getArgOperand(0), *Sign =
II->getArgOperand(1);
3286 if (*KnownSignBit) {
3334 Value *Trunc =
Builder.CreateUnaryIntrinsic(Intrinsic::trunc, Sign,
II);
3354 case Intrinsic::fabs: {
3356 Value *Arg =
II->getArgOperand(0);
3373 Cond, AbsT, AbsF,
"",
nullptr,
3375 SI->setFastMathFlags(
II->getFastMathFlags() |
3379 SI->setHasNoSignedZeros(
false);
3390 Value *Magnitude, *Sign;
3391 if (
match(
II->getArgOperand(0),
3400 case Intrinsic::ceil:
3401 case Intrinsic::floor:
3402 case Intrinsic::round:
3403 case Intrinsic::roundeven:
3404 case Intrinsic::nearbyint:
3405 case Intrinsic::rint:
3406 case Intrinsic::trunc: {
3415 case Intrinsic::cos:
3416 case Intrinsic::amdgcn_cos:
3417 case Intrinsic::cosh: {
3419 Value *Src =
II->getArgOperand(0);
3428 if (IID == Intrinsic::cos) {
3434 case Intrinsic::sin:
3435 case Intrinsic::amdgcn_sin:
3436 case Intrinsic::sinh:
3437 case Intrinsic::tan:
3438 case Intrinsic::tanh: {
3447 if (IID == Intrinsic::sin) {
3453 case Intrinsic::ldexp: {
3454 Value *Src =
II->getArgOperand(0);
3455 Value *Exp =
II->getArgOperand(1);
3461 Src->getType()->getScalarType()->getFltSemantics();
3491 Exp->getType() == InnerExp->
getType()) {
3499 Builder.CreateBinaryIntrinsic(Intrinsic::sadd_sat, InnerExp, Exp);
3501 *
II,
Builder.CreateLdexp(InnerSrc, NewExp, FMF | InnerFlags));
3511 Builder.CreateSelect(ExtSrc, ConstantFP::get(
II->getType(), 2.0),
3512 ConstantFP::get(
II->getType(), 1.0));
3518 Builder.CreateSelect(ExtSrc, ConstantFP::get(
II->getType(), 0.5),
3519 ConstantFP::get(
II->getType(), 1.0));
3527 Value *SelectCond, *SelectLHS, *SelectRHS;
3528 if (
match(
II->getArgOperand(1),
3531 Value *NewLdexp =
nullptr;
3534 NewLdexp =
Builder.CreateLdexp(Src, SelectLHS,
II);
3537 NewLdexp =
Builder.CreateLdexp(Src, SelectRHS,
II);
3549 case Intrinsic::ptrauth_auth:
3550 case Intrinsic::ptrauth_resign: {
3553 bool NeedSign =
II->getIntrinsicID() == Intrinsic::ptrauth_resign;
3554 Value *Ptr =
II->getArgOperand(0);
3556 Value *Disc =
II->getArgOperand(2);
3557 Value *DS =
nullptr;
3559 DS = Bundle->Inputs[0];
3563 Value *AuthKey =
nullptr, *AuthDisc =
nullptr, *BasePtr;
3565 Value *OtherDS =
nullptr;
3568 OtherDS = Bundle->Inputs[0];
3589 if (!CPA || DS || !CPA->isKnownCompatibleWith(
Key, Disc,
DL))
3606 BasePtr =
Builder.CreatePtrToInt(CPA->getPointer(),
II->getType());
3611 if (AuthKey && NeedSign) {
3613 NewIntrin = Intrinsic::ptrauth_resign;
3614 }
else if (AuthKey) {
3616 NewIntrin = Intrinsic::ptrauth_auth;
3617 }
else if (NeedSign) {
3619 NewIntrin = Intrinsic::ptrauth_sign;
3638 std::vector<OperandBundleDef> Bundles;
3646 case Intrinsic::arm_neon_vtbl1:
3647 case Intrinsic::arm_neon_vtbl2:
3648 case Intrinsic::arm_neon_vtbl3:
3649 case Intrinsic::arm_neon_vtbl4:
3650 case Intrinsic::aarch64_neon_tbl1:
3651 case Intrinsic::aarch64_neon_tbl2:
3652 case Intrinsic::aarch64_neon_tbl3:
3653 case Intrinsic::aarch64_neon_tbl4:
3655 case Intrinsic::arm_neon_vtbx1:
3656 case Intrinsic::arm_neon_vtbx2:
3657 case Intrinsic::arm_neon_vtbx3:
3658 case Intrinsic::arm_neon_vtbx4:
3659 case Intrinsic::aarch64_neon_tbx1:
3660 case Intrinsic::aarch64_neon_tbx2:
3661 case Intrinsic::aarch64_neon_tbx3:
3662 case Intrinsic::aarch64_neon_tbx4:
3665 case Intrinsic::arm_neon_vmulls:
3666 case Intrinsic::arm_neon_vmullu:
3667 case Intrinsic::aarch64_neon_smull:
3668 case Intrinsic::aarch64_neon_umull: {
3669 Value *Arg0 =
II->getArgOperand(0);
3670 Value *Arg1 =
II->getArgOperand(1);
3678 bool Zext = (IID == Intrinsic::arm_neon_vmullu ||
3679 IID == Intrinsic::aarch64_neon_umull);
3702 case Intrinsic::arm_neon_aesd:
3703 case Intrinsic::arm_neon_aese:
3704 case Intrinsic::aarch64_crypto_aesd:
3705 case Intrinsic::aarch64_crypto_aese:
3706 case Intrinsic::aarch64_sve_aesd:
3707 case Intrinsic::aarch64_sve_aese: {
3708 Value *DataArg =
II->getArgOperand(0);
3709 Value *KeyArg =
II->getArgOperand(1);
3725 case Intrinsic::arm_neon_vshifts:
3726 case Intrinsic::arm_neon_vshiftu:
3727 case Intrinsic::aarch64_neon_sshl:
3728 case Intrinsic::aarch64_neon_ushl:
3730 case Intrinsic::hexagon_V6_vandvrt:
3731 case Intrinsic::hexagon_V6_vandvrt_128B: {
3735 if (ID0 != Intrinsic::hexagon_V6_vandqrt &&
3736 ID0 != Intrinsic::hexagon_V6_vandqrt_128B)
3738 Value *Bytes = Op0->getArgOperand(1), *Mask =
II->getArgOperand(1);
3742 uint64_t
C = Bytes1 & Mask1;
3743 if ((
C & 0xFF) && (
C & 0xFF00) && (
C & 0xFF0000) && (
C & 0xFF000000))
3748 case Intrinsic::stackrestore: {
3749 enum class ClassifyResult {
3753 CallWithSideEffects,
3757 return ClassifyResult::Alloca;
3761 if (
II->getIntrinsicID() == Intrinsic::stackrestore)
3762 return ClassifyResult::StackRestore;
3764 if (
II->mayHaveSideEffects())
3765 return ClassifyResult::CallWithSideEffects;
3768 return ClassifyResult::CallWithSideEffects;
3772 return ClassifyResult::None;
3779 if (SS->getIntrinsicID() == Intrinsic::stacksave &&
3780 SS->getParent() ==
II->getParent()) {
3782 bool CannotRemove =
false;
3783 for (++BI; &*BI !=
II; ++BI) {
3784 switch (Classify(&*BI)) {
3785 case ClassifyResult::None:
3789 case ClassifyResult::StackRestore:
3793 CannotRemove =
true;
3796 case ClassifyResult::Alloca:
3797 case ClassifyResult::CallWithSideEffects:
3800 CannotRemove =
true;
3816 bool CannotRemove =
false;
3817 for (++BI; &*BI != TI; ++BI) {
3818 switch (Classify(&*BI)) {
3819 case ClassifyResult::None:
3823 case ClassifyResult::StackRestore:
3827 case ClassifyResult::Alloca:
3828 case ClassifyResult::CallWithSideEffects:
3832 CannotRemove =
true;
3846 case Intrinsic::lifetime_end:
3849 if (
II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3850 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemory) ||
3851 II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress) ||
3852 II->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag))
3856 return I.getIntrinsicID() == Intrinsic::lifetime_start;
3860 case Intrinsic::assume: {
3862 auto RemoveBundle = [&, Idx = Idx]() ->
Instruction * {
3863 if (
II->getNumOperandBundles() == 1)
3871 case BundleAttr::Align: {
3881 return RemoveBundle();
3886 Builder.CreateAlignmentAssumption(
3888 OffsetPtr ?
const_cast<Value *
>(OffsetPtr->get()) :
nullptr);
3889 return RemoveBundle();
3896 const APInt *PtrOffset;
3899 PtrOffset->
sextOrTrunc(
DL.getIndexTypeSizeInBits(Ptr->getType()))
3903 Builder.CreateAlignmentAssumption(
3904 DL, BasePtr, *Alignment,
3906 return RemoveBundle();
3918 auto AlignMask = (*Alignment - 1);
3920 (KB.Zero & AlignMask) == (~*
Offset & AlignMask) &&
3921 (KB.One & AlignMask) == (*
Offset & AlignMask))
3922 return RemoveBundle();
3926 case BundleAttr::Dereferenceable: {
3935 return RemoveBundle();
3940 case BundleAttr::Ignore:
3941 return RemoveBundle();
3943 case BundleAttr::NonNull: {
3948 return RemoveBundle();
3957 return RemoveBundle();
3961 GEP &&
GEP->isInBounds() &&
3963 Ptr->getType()->getPointerAddressSpace())) {
3964 Builder.CreateNonnullAssumption(
GEP->stripInBoundsOffsets());
3965 return RemoveBundle();
3972 case BundleAttr::NoUndef: {
3976 return RemoveBundle();
3983 return RemoveBundle();
3988 case BundleAttr::SeparateStorage: {
3994 auto MaybeSimplifyHint = [&](
const Use &U) {
3995 Value *Hint = U.get();
3999 if (Hint != UnderlyingObject)
4002 MaybeSimplifyHint(Ptr1);
4003 MaybeSimplifyHint(Ptr2);
4007 case BundleAttr::DereferenceableOrNull:
4011 case BundleAttr::Cold:
4018 if (
II->hasOperandBundles())
4021 Value *IIOperand =
II->getArgOperand(0);
4049 A->getType()->isPointerTy()) {
4050 Builder.CreateNonnullAssumption(
A);
4061 uint64_t AlignMask = 1;
4077 if (!CI || CI->isZero())
4087 case Intrinsic::experimental_guard: {
4092 for (
unsigned i = 0; i <
CLOpts.guard_widening_window; i++) {
4098 Value *NextCond =
nullptr;
4101 Value *CurrCond =
II->getArgOperand(0);
4105 if (CurrCond != NextCond) {
4107 while (MoveI != NextInst) {
4119 case Intrinsic::vector_insert: {
4120 Value *Vec =
II->getArgOperand(0);
4121 Value *SubVec =
II->getArgOperand(1);
4122 Value *Idx =
II->getArgOperand(2);
4129 if (DstTy && VecTy && SubVecTy) {
4130 unsigned DstNumElts = DstTy->getNumElements();
4131 unsigned VecNumElts = VecTy->getNumElements();
4132 unsigned SubVecNumElts = SubVecTy->getNumElements();
4136 if (VecNumElts == SubVecNumElts)
4145 for (i = 0; i != SubVecNumElts; ++i)
4147 for (; i != VecNumElts; ++i)
4150 Value *WidenShuffle =
Builder.CreateShuffleVector(SubVec, WidenMask);
4153 for (
unsigned i = 0; i != IdxN; ++i)
4155 for (
unsigned i = DstNumElts; i != DstNumElts + SubVecNumElts; ++i)
4157 for (
unsigned i = IdxN + SubVecNumElts; i != DstNumElts; ++i)
4160 Value *Shuffle =
Builder.CreateShuffleVector(Vec, WidenShuffle, Mask);
4165 case Intrinsic::vector_extract: {
4166 Value *Vec =
II->getArgOperand(0);
4167 Value *Idx =
II->getArgOperand(1);
4169 Type *ReturnType =
II->getType();
4173 Value *InsertTuple, *InsertIdx, *InsertValue;
4177 InsertValue->
getType() == ReturnType) {
4182 if (ExtractIdx == Index)
4196 const auto &Attrs =
II->getFunction()->getAttributes().getFnAttrs();
4197 unsigned VScaleMin = Attrs.getVScaleRangeMin();
4198 unsigned ScaleFactor =
4200 if (ExtractIdx * ScaleFactor >= ALMUpperBound->
getZExtValue())
4208 if (DstTy && VecTy) {
4209 auto DstEltCnt = DstTy->getElementCount();
4210 auto VecEltCnt = VecTy->getElementCount();
4214 if (DstEltCnt == VecTy->getElementCount()) {
4221 if (VecEltCnt.isScalable() || DstEltCnt.isScalable())
4225 for (
unsigned i = 0; i != DstEltCnt.getKnownMinValue(); ++i)
4226 Mask.push_back(IdxN + i);
4228 Value *Shuffle =
Builder.CreateShuffleVector(Vec, Mask);
4233 case Intrinsic::experimental_vp_reverse: {
4235 Value *Vec =
II->getArgOperand(0);
4236 Value *Mask =
II->getArgOperand(1);
4239 Value *EVL =
II->getArgOperand(2);
4247 OldUnOp->getOpcode(),
X, OldUnOp, OldUnOp->getName(),
4253 case Intrinsic::vector_reduce_or:
4254 case Intrinsic::vector_reduce_and: {
4262 Value *Arg =
II->getArgOperand(0);
4273 if (FTy->getElementType() ==
Builder.getInt1Ty()) {
4275 Vect,
Builder.getIntNTy(FTy->getNumElements()));
4276 if (IID == Intrinsic::vector_reduce_and) {
4280 assert(IID == Intrinsic::vector_reduce_or &&
4281 "Expected or reduction.");
4282 Res =
Builder.CreateIsNotNull(Res);
4292 case Intrinsic::vector_reduce_add: {
4293 if (IID == Intrinsic::vector_reduce_add) {
4300 Value *Arg =
II->getArgOperand(0);
4313 if (VecToReduceCount.
isFixed()) {
4315 return BinaryOperator::CreateMul(
4317 ConstantInt::get(
Splat->getType(), VectorSize,
false,
4324 if (FTy->getElementType() ==
Builder.getInt1Ty()) {
4326 Vect,
Builder.getIntNTy(FTy->getNumElements()));
4327 Value *Res =
Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, V);
4328 Res =
Builder.CreateZExtOrTrunc(Res,
II->getType());
4338 case Intrinsic::vector_reduce_xor: {
4339 if (IID == Intrinsic::vector_reduce_xor) {
4347 Value *Arg =
II->getArgOperand(0);
4358 if (VTy->getElementType() ==
Builder.getInt1Ty()) {
4369 case Intrinsic::vector_reduce_mul: {
4370 if (IID == Intrinsic::vector_reduce_mul) {
4371 Value *Arg =
II->getArgOperand(0);
4391 if (IsZext || IsSext) {
4402 case Intrinsic::vector_reduce_umin:
4403 case Intrinsic::vector_reduce_umax: {
4404 if (IID == Intrinsic::vector_reduce_umin ||
4405 IID == Intrinsic::vector_reduce_umax) {
4412 Value *Arg =
II->getArgOperand(0);
4423 if (VTy->getElementType() ==
Builder.getInt1Ty()) {
4424 Value *Res = IID == Intrinsic::vector_reduce_umin
4425 ?
Builder.CreateAndReduce(Vect)
4426 :
Builder.CreateOrReduce(Vect);
4436 case Intrinsic::vector_reduce_smin:
4437 case Intrinsic::vector_reduce_smax: {
4438 if (IID == Intrinsic::vector_reduce_smin ||
4439 IID == Intrinsic::vector_reduce_smax) {
4454 Value *Arg =
II->getArgOperand(0);
4465 if (VTy->getElementType() ==
Builder.getInt1Ty()) {
4469 Value *Res = ((IID == Intrinsic::vector_reduce_smin) ==
4470 (ExtOpc == Instruction::CastOps::ZExt))
4471 ?
Builder.CreateAndReduce(Vect)
4472 :
Builder.CreateOrReduce(Vect);
4474 Res =
Builder.CreateCast(ExtOpc, Res,
II->getType());
4481 case Intrinsic::vector_reduce_fmax:
4482 case Intrinsic::vector_reduce_fmin:
4483 case Intrinsic::vector_reduce_fadd:
4484 case Intrinsic::vector_reduce_fmul: {
4485 bool CanReorderLanes = (IID != Intrinsic::vector_reduce_fadd &&
4486 IID != Intrinsic::vector_reduce_fmul) ||
4487 II->hasAllowReassoc();
4488 const unsigned ArgIdx = (IID == Intrinsic::vector_reduce_fadd ||
4489 IID == Intrinsic::vector_reduce_fmul)
4492 Value *Arg =
II->getArgOperand(ArgIdx);
4499 case Intrinsic::is_fpclass: {
4504 case Intrinsic::threadlocal_address: {
4513 case Intrinsic::fptoui_sat:
4514 case Intrinsic::fptosi_sat:
4518 case Intrinsic::frexp: {
4522 if (
match(
II->getArgOperand(0),
4525 II->getArgOperand(0), 0);
4526 Res =
Builder.CreateInsertValue(
4533 case Intrinsic::get_active_lane_mask: {
4534 const APInt *Op0, *Op1;
4540 II->getType(), Intrinsic::get_active_lane_mask,
4541 {Constant::getNullValue(OpTy),
4542 ConstantInt::get(OpTy, Op1->usub_sat(*Op0))}));
4546 case Intrinsic::experimental_get_vector_length: {
4549 std::max(
II->getArgOperand(0)->getType()->getScalarSizeInBits(),
4550 II->getType()->getScalarSizeInBits());
4553 SQ.getWithInstruction(
II))
4564 *
II,
Builder.CreateZExtOrTrunc(
II->getArgOperand(0),
II->getType()));
4585 bool IsVectorCond = Sel->getCondition()->getType()->isVectorTy();
4591 bool SimplifyBothArms =
4592 !
Op->getType()->isVectorTy() &&
II->getType()->isVectorTy();
4594 *
II, Sel,
false, SimplifyBothArms))
4614 return visitCallBase(*
II);
4629 if (FI1SyncScope != FI2->getSyncScopeID() ||
4636 if (NFI && isIdenticalOrStrongerFence(NFI, &FI))
4640 if (isIdenticalOrStrongerFence(PFI, &FI))
4647 return visitCallBase(
II);
4652 return visitCallBase(CBI);
4661 for (
size_t I = 0;
I < FormatStr.
size(); ++
I) {
4662 if (FormatStr[
I] !=
'%')
4666 if (
I + 1 < FormatStr.
size() && FormatStr[
I + 1] ==
'%') {
4677 Specifiers.
set(
static_cast<unsigned char>(FormatStr[J]));
4684 std::optional<unsigned> FirstArgIdx,
4686 if (Aspect ==
"float") {
4688 static constexpr Bitset<256> FloatSpecifiers{
'f',
'F',
'e',
'E',
4689 'g',
'G',
'a',
'A'};
4690 return (*Specifiers & FloatSpecifiers).
any();
4698 [](
Value *V) { return V->getType()->isFloatingPointTy(); });
4700 if (Aspect ==
"fixed") {
4702 static constexpr Bitset<256> FixedSpecifiers{
'r',
'R',
'k',
'K'};
4703 return (*Specifiers & FixedSpecifiers).
any();
4720 B.CreateCall(RelocNoneFn,
4730 if (Args.size() < 5)
4740 std::optional<unsigned> FirstArgIdx;
4741 [[maybe_unused]]
bool Error;
4746 FirstArgIdx.emplace();
4749 if (*FirstArgIdx > 0)
4752 FirstArgIdx.reset();
4754 if (AllAspects.
empty())
4760 std::optional<Bitset<256>> Specifiers;
4769 if (NeededAspects.
size() == AllAspects.
size())
4776 FnName, Callee->getFunctionType(),
4777 Callee->getAttributes().removeFnAttribute(Ctx,
"modular-format"));
4779 New->setCalledFunction(ModularFn);
4780 New->removeFnAttr(
"modular-format");
4806 InstCombineRAUW, InstCombineErase);
4807 if (
Value *With = Simplifier.optimizeCall(CI,
Builder)) {
4823 if (Underlying != TrampMem &&
4824 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
4834 if (
II->getIntrinsicID() == Intrinsic::init_trampoline) {
4838 InitTrampoline =
II;
4841 if (
II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4848 if (!InitTrampoline)
4852 if (InitTrampoline->
getOperand(0) != TrampMem)
4855 return InitTrampoline;
4867 if (
II->getIntrinsicID() == Intrinsic::init_trampoline &&
4868 II->getOperand(0) == TrampMem)
4880 Callee = Callee->stripPointerCasts();
4898 if (!IPC || !IPC->isNoopCast(
DL))
4906 if (IIID != Intrinsic::ptrauth_resign && IIID != Intrinsic::ptrauth_sign)
4910 std::optional<OperandBundleUse> PtrAuthBundleOrNone;
4915 PtrAuthBundleOrNone = Bundle;
4920 if (!PtrAuthBundleOrNone)
4923 Value *NewCallee =
nullptr;
4927 case Intrinsic::ptrauth_resign: {
4929 if (
II->getOperand(3) != PtrAuthBundleOrNone->Inputs[0])
4932 if (
II->getOperand(4) != PtrAuthBundleOrNone->Inputs[1])
4937 if (
II->getOperand(1) != PtrAuthBundleOrNone->Inputs[0])
4940 Value *NewBundleOps[] = {
II->getOperand(1),
II->getOperand(2)};
4942 NewCallee =
II->getOperand(0);
4949 case Intrinsic::ptrauth_sign: {
4951 if (
II->getOperand(1) != PtrAuthBundleOrNone->Inputs[0])
4954 if (
II->getOperand(2) != PtrAuthBundleOrNone->Inputs[1])
4956 NewCallee =
II->getOperand(0);
4966 NewCallee =
Builder.CreateBitOrPointerCast(NewCallee,
Callee->getType());
4991 if (!CPA->isKnownCompatibleWith(
Key, Discriminator,
DL))
5000bool InstCombinerImpl::annotateAnyAllocSite(
CallBase &
Call,
5037 if (NewAlign > ExistingAlign) {
5054 SmallVector<unsigned, 4> ArgNos;
5058 if (
V->getType()->isPointerTy()) {
5061 bool UseProvenance =
5064 V->getType()->getPointerAddressSpace());
5066 if (
Value *Res = simplifyNonNullOperand(V, UseProvenance)) {
5080 if (!ArgNos.
empty()) {
5083 AS = AS.addParamAttribute(Ctx, ArgNos,
5094 transformConstExprCastCall(
Call))
5158 return transformCallThroughTrampoline(
Call, *
II);
5161 if (Instruction *NewCall = foldPtrAuthIntrinsicCallee(
Call))
5165 if (Instruction *NewCall = foldPtrAuthConstantCallee(
Call))
5170 if (!
IA->canThrow()) {
5191 Type *RetArgTy = ReturnedArg->getType();
5194 Call,
Builder.CreateBitOrPointerCast(ReturnedArg, CallTy));
5210 ConstantInt *FunctionType =
nullptr;
5213 if (MDNode *MD = CalleeF->
getMetadata(LLVMContext::MD_kcfi_type))
5220 <<
": call to " << CalleeF->
getName()
5221 <<
" using a mismatching function pointer type\n";
5233 case Intrinsic::experimental_gc_statepoint: {
5235 SmallPtrSet<Value *, 32> LiveGcValues;
5237 GCRelocateInst &GCR = *
const_cast<GCRelocateInst *
>(Reloc);
5288 LiveGcValues.
insert(BasePtr);
5289 LiveGcValues.
insert(DerivedPtr);
5291 std::optional<OperandBundleUse> Bundle =
5293 unsigned NumOfGCLives = LiveGcValues.
size();
5294 if (!Bundle || NumOfGCLives == Bundle->Inputs.size())
5297 DenseMap<Value *, unsigned> Val2Idx;
5298 std::vector<Value *> NewLiveGc;
5299 for (
Value *V : Bundle->Inputs) {
5303 if (LiveGcValues.
count(V)) {
5304 It->second = NewLiveGc.size();
5305 NewLiveGc.push_back(V);
5307 It->second = NumOfGCLives;
5311 GCRelocateInst &GCR = *
const_cast<GCRelocateInst *
>(Reloc);
5313 assert(Val2Idx.
count(BasePtr) && Val2Idx[BasePtr] != NumOfGCLives &&
5314 "Missed live gc for base pointer");
5316 GCR.
setOperand(1, ConstantInt::get(OpIntTy1, Val2Idx[BasePtr]));
5318 assert(Val2Idx.
count(DerivedPtr) && Val2Idx[DerivedPtr] != NumOfGCLives &&
5319 "Missed live gc for derived pointer");
5321 GCR.
setOperand(2, ConstantInt::get(OpIntTy2, Val2Idx[DerivedPtr]));
5336bool InstCombinerImpl::transformConstExprCastCall(
CallBase &
Call) {
5343 "CallBr's don't have a single point after a def to insert at");
5348 if (
Callee->isDeclaration())
5354 if (
Callee->hasFnAttribute(
"thunk"))
5360 if (
Callee->hasFnAttribute(Attribute::Naked))
5376 FunctionType *FT =
Callee->getFunctionType();
5378 Type *NewRetTy = FT->getReturnType();
5381 if (OldRetTy != NewRetTy) {
5387 if (!
Caller->use_empty())
5391 if (!CallerPAL.isEmpty() && !
Caller->use_empty()) {
5392 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
5393 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(
5394 NewRetTy, CallerPAL.getRetAttrs())))
5402 if (!
Caller->use_empty()) {
5405 PhisNotSupportedBlock =
II->getNormalDest();
5406 if (PhisNotSupportedBlock)
5407 for (User *U :
Caller->users())
5409 if (PN->getParent() == PhisNotSupportedBlock)
5415 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5425 if (
Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
5426 Callee->getAttributes().hasAttrSomewhere(Attribute::Preallocated))
5430 for (
unsigned i = 0, e = NumCommonArgs; i !=
e; ++i, ++AI) {
5431 Type *ParamTy = FT->getParamType(i);
5432 Type *ActTy = (*AI)->getType();
5438 if (AttrBuilder(FT->getContext(), CallerPAL.getParamAttrs(i))
5439 .overlaps(AttributeFuncs::typeIncompatible(
5440 ParamTy, CallerPAL.getParamAttrs(i),
5441 AttributeFuncs::ASK_UNSAFE_TO_DROP)))
5445 CallerPAL.hasParamAttr(i, Attribute::Preallocated))
5448 if (CallerPAL.hasParamAttr(i, Attribute::SwiftError))
5451 if (CallerPAL.hasParamAttr(i, Attribute::ByVal) !=
5452 Callee->getAttributes().hasParamAttr(i, Attribute::ByVal))
5456 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
5457 !CallerPAL.isEmpty()) {
5462 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
5463 SRetIdx - AttributeList::FirstArgIndex >= FT->getNumParams())
5469 SmallVector<Value *, 8>
Args;
5471 Args.reserve(NumActualArgs);
5472 ArgAttrs.
reserve(NumActualArgs);
5475 AttrBuilder RAttrs(FT->getContext(), CallerPAL.getRetAttrs());
5480 AttributeFuncs::typeIncompatible(NewRetTy, CallerPAL.getRetAttrs()));
5484 for (
unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5485 Type *ParamTy = FT->getParamType(i);
5487 Value *NewArg = *AI;
5488 if ((*AI)->getType() != ParamTy)
5489 NewArg =
Builder.CreateBitOrPointerCast(*AI, ParamTy);
5490 Args.push_back(NewArg);
5494 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(
5495 ParamTy, CallerPAL.getParamAttrs(i), AttributeFuncs::ASK_SAFE_TO_DROP);
5497 CallerPAL.getParamAttrs(i).removeAttributes(Ctx, IncompatibleAttrs));
5502 for (
unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
5508 if (FT->getNumParams() < NumActualArgs) {
5510 if (FT->isVarArg()) {
5512 for (
unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5514 Value *NewArg = *AI;
5515 if (PTy != (*AI)->getType()) {
5519 NewArg =
Builder.CreateCast(opcode, *AI, PTy);
5521 Args.push_back(NewArg);
5524 ArgAttrs.
push_back(CallerPAL.getParamAttrs(i));
5529 AttributeSet FnAttrs = CallerPAL.getFnAttrs();
5534 assert((ArgAttrs.
size() == FT->getNumParams() || FT->isVarArg()) &&
5535 "missing argument attributes");
5536 AttributeList NewCallerPAL = AttributeList::get(
5544 NewCall =
Builder.CreateInvoke(Callee,
II->getNormalDest(),
5545 II->getUnwindDest(), Args, OpBundles);
5547 NewCall =
Builder.CreateCall(Callee, Args, OpBundles);
5556 NewCall->
copyMetadata(*Caller, {LLVMContext::MD_prof});
5561 if (OldRetTy !=
NV->getType() && !
Caller->use_empty()) {
5562 assert(!
NV->getType()->isVoidTy());
5564 NC->setDebugLoc(
Caller->getDebugLoc());
5567 assert(OptInsertPt &&
"No place to insert cast");
5569 Worklist.pushUsersToWorkList(*Caller);
5572 if (!
Caller->use_empty())
5574 else if (
Caller->hasValueHandle()) {
5575 if (OldRetTy ==
NV->getType())
5590InstCombinerImpl::transformCallThroughTrampoline(
CallBase &
Call,
5597 if (
Attrs.hasAttrSomewhere(Attribute::Nest))
5604 if (!NestAttrs.isEmpty()) {
5605 unsigned NestArgNo = 0;
5606 Type *NestTy =
nullptr;
5607 AttributeSet NestAttr;
5611 E = NestFTy->param_end();
5612 I !=
E; ++NestArgNo, ++
I) {
5613 AttributeSet AS = NestAttrs.getParamAttrs(NestArgNo);
5623 std::vector<Value*> NewArgs;
5624 std::vector<AttributeSet> NewArgAttrs;
5635 if (ArgNo == NestArgNo) {
5638 if (NestVal->
getType() != NestTy)
5639 NestVal =
Builder.CreateBitCast(NestVal, NestTy,
"nest");
5640 NewArgs.push_back(NestVal);
5641 NewArgAttrs.push_back(NestAttr);
5648 NewArgs.push_back(*
I);
5649 NewArgAttrs.push_back(
Attrs.getParamAttrs(ArgNo));
5660 std::vector<Type*> NewTypes;
5661 NewTypes.reserve(FTy->getNumParams()+1);
5668 E = FTy->param_end();
5671 if (ArgNo == NestArgNo)
5673 NewTypes.push_back(NestTy);
5679 NewTypes.push_back(*
I);
5688 FunctionType *NewFTy =
5690 AttributeList NewPAL =
5691 AttributeList::get(FTy->getContext(),
Attrs.getFnAttrs(),
5692 Attrs.getRetAttrs(), NewArgAttrs);
5700 II->getUnwindDest(), NewArgs, OpBundles);
5706 CBI->getIndirectDests(), NewArgs, OpBundles);
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 cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
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 SDValue foldBitOrderCrossLogicOp(SDNode *N, SelectionDAG &DAG)
static Type * getPromotedType(Type *Ty)
Return the specified type promoted as it would be to pass though a va_arg area.
static Instruction * createOverflowTuple(IntrinsicInst *II, Value *Result, Constant *Overflow)
Creates a result tuple for an overflow intrinsic II with a given Result and a constant Overflow value...
static void referenceAspect(StringRef Aspect, StringRef ImplName, Module *M, IRBuilderBase &B)
static IntrinsicInst * findInitTrampolineFromAlloca(Value *TrampMem)
static bool removeTriviallyEmptyRange(IntrinsicInst &EndI, InstCombinerImpl &IC, std::function< bool(const IntrinsicInst &)> IsStart)
static bool inputDenormalIsDAZ(const Function &F, const Type *Ty)
static Instruction * reassociateMinMaxWithConstantInOperand(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
If this min/max has a matching min/max operand with a constant, try to push the constant operand into...
static bool isIdempotentBinaryIntrinsic(Intrinsic::ID IID)
Helper to match idempotent binary intrinsics, namely, intrinsics where f(f(x, y), y) == f(x,...
static bool signBitMustBeTheSame(Value *Op0, Value *Op1, const SimplifyQuery &SQ)
Return true if two values Op0 and Op1 are known to have the same sign.
static Value * optimizeModularFormat(CallInst *CI, IRBuilderBase &B)
static Instruction * moveAddAfterMinMax(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0.
static Instruction * simplifyInvariantGroupIntrinsic(IntrinsicInst &II, InstCombinerImpl &IC)
This function transforms launder.invariant.group like: launder(launder(x)) -> launder(x) (the result ...
static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E, unsigned NumOperands)
static std::optional< bool > getKnownSign(Value *Op, const SimplifyQuery &SQ)
static bool hasUndefSource(AnyMemTransferInst *MI)
Recognize a memcpy/memmove from a trivially otherwise unused alloca.
static Instruction * factorizeMinMaxTree(IntrinsicInst *II)
Reduce a sequence of min/max intrinsics with a common operand.
static Instruction * foldClampRangeOfTwo(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
If we have a clamp pattern like max (min X, 42), 41 – where the output can only be one of two possibl...
static Value * simplifyReductionOperand(Value *Arg, bool CanReorderLanes)
static IntrinsicInst * findInitTrampolineFromBB(IntrinsicInst *AdjustTramp, Value *TrampMem)
static bool isAspectNeeded(StringRef Aspect, CallInst *CI, std::optional< unsigned > FirstArgIdx, const std::optional< Bitset< 256 > > &Specifiers)
static Value * foldIntrinsicUsingDistributiveLaws(IntrinsicInst *II, InstCombiner::BuilderTy &Builder)
static std::optional< bool > getKnownSignOrZero(Value *Op, const SimplifyQuery &SQ)
static Value * foldMinimumOverTrailingOrLeadingZeroCount(Value *I0, Value *I1, const DataLayout &DL, InstCombiner::BuilderTy &Builder)
Fold an unsigned minimum of trailing or leading zero bits counts: umin(cttz(CtOp1,...
static bool rightDistributesOverLeft(Instruction::BinaryOps LOp, bool HasNUW, bool HasNSW, Intrinsic::ID ROp)
Return whether "(X ROp Y) LOp Z" is always equal to "(X LOp Z) ROp (Y LOp Z)".
static Value * foldIdempotentBinaryIntrinsicRecurrence(InstCombinerImpl &IC, IntrinsicInst *II)
Attempt to simplify value-accumulating recurrences of kind: umax.acc = phi i8 [ umax,...
static bool ldexpSaturatingAddIsSafe(Type *FpTy, Type *ExpTy)
static Instruction * foldCtpop(IntrinsicInst &II, InstCombinerImpl &IC)
static Instruction * simplifyNeonTbl(IntrinsicInst &II, InstCombiner &IC, bool IsExtension)
Convert tbl/tbx intrinsics to shufflevector if the mask is constant, and at most two source operands ...
static Instruction * foldCttzCtlz(IntrinsicInst &II, InstCombinerImpl &IC)
static IntrinsicInst * findInitTrampoline(Value *Callee)
static Value * foldCmpIntrinsicOfExtended(IntrinsicInst *II, InstCombiner::BuilderTy &Builder, const DataLayout &DL)
Fold an scmp/ucmp intrinsic whose operands are extended from a narrower type: scmp (sext X),...
static Bitset< 256 > parseFormatStringSpecifiers(StringRef FormatStr)
static FCmpInst::Predicate fpclassTestIsFCmp0(FPClassTest Mask, const Function &F, Type *Ty)
static bool leftDistributesOverRight(Instruction::BinaryOps LOp, bool HasNUW, bool HasNSW, Intrinsic::ID ROp)
Return whether "X LOp (Y ROp Z)" is always equal to "(X LOp Y) ROp (X LOp Z)".
static Value * reassociateMinMaxWithConstants(IntrinsicInst *II, IRBuilderBase &Builder, const SimplifyQuery &SQ)
If this min/max has a constant operand and an operand that is a matching min/max with a constant oper...
static Value * foldSinAndCosToSinCos(IntrinsicInst *II, IRBuilderBase &B, InstCombinerImpl &IC)
static bool mayFlushDenormalsToPositiveZero(const CallInst *CI)
Flushing a denormal to +0.0 breaks f(-x) = -f(x) for odd f.
static CallInst * canonicalizeConstantArg0ToArg1(CallInst &Call)
static Instruction * foldNeonShift(IntrinsicInst *II, InstCombinerImpl &IC)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
static bool inputDenormalIsIEEE(DenormalMode Mode)
Return true if it's possible to assume IEEE treatment of input denormals in F for Val.
static const Function * getCalledFunction(const Value *V)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
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 the SmallBitVector class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
static constexpr roundingMode rmNearestTiesToEven
static LLVM_ABI bool hasSignBitInMSB(const fltSemantics &)
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
static APFloat getSmallest(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) finite number in the given semantics.
Class for arbitrary precision integers.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
bool sgt(const APInt &RHS) const
Signed greater than comparison.
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.
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
unsigned getBitWidth() const
Return the number of bits in the APInt.
bool ult(const APInt &RHS) const
Unsigned less than comparison.
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
bool isShiftedMask() const
Return true if this APInt value contains a non-empty sequence of ones with the remainder zero.
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
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.
This class represents any memset intrinsic.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
This class holds the attributes for a particular argument, parameter, function, or return value.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
static LLVM_ABI Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
static LLVM_ABI Attribute getWithDereferenceableOrNullBytes(LLVMContext &Context, uint64_t Bytes)
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
InstListType::reverse_iterator reverse_iterator
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI bool isSigned() const
Whether the intrinsic is signed or unsigned.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
static BinaryOperator * CreateNSW(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
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.
static BinaryOperator * CreateNUW(BinaryOps Opc, Value *V1, Value *V2, const Twine &Name="")
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
static LLVM_ABI BinaryOperator * CreateNSWNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
This is a constexpr reimplementation of a subset of std::bitset.
constexpr bool any() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
MaybeAlign getRetAlign() const
Extract the alignment of the return value.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool isInAllocaArgument(unsigned ArgNo) const
Determine whether this argument is passed in an alloca.
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
uint64_t getParamDereferenceableBytes(unsigned i) const
Extract the number of dereferenceable bytes for a call or parameter (0=unknown).
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
static LLVM_ABI CallBase * removeOperandBundleAt(CallBase *CB, size_t Offset, InsertPosition InsertPtr=nullptr)
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
Attribute getFnAttr(StringRef Kind) const
Get the attribute of a given kind for the function.
bool doesNotThrow() const
Determine if the call cannot unwind.
void addRetAttr(Attribute::AttrKind Kind)
Adds the attribute to the return value.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
bool isConvergent() const
Determine if the invoke is convergent.
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
Value * getReturnedArgOperand() const
If one of the arguments has the 'returned' attribute, returns its operand value.
static LLVM_ABI CallBase * Create(CallBase *CB, ArrayRef< OperandBundleDef > Bundles, InsertPosition InsertPt=nullptr)
Create a clone of CB with a different set of operand bundles and insert it before InsertPt.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
void setCalledOperand(Value *V)
static LLVM_ABI CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This class represents a function call, abstracting a target machine's calling convention.
bool isNoTailCall() const
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool isMustTailCall() const
static LLVM_ABI Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ 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_UGT
unsigned greater than
@ ICMP_SGT
signed greater 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_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Predicate getUnorderedPredicate() const
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
ConstantFP - Floating Point Values [float, double].
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getInfinity(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 LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
This class represents a range of values.
LLVM_ABI ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
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...
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
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.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Lightweight error class with error context and mandatory checking.
static FMFSource intersect(Value *A, Value *B)
Intersect the FMF from two instructions.
This class represents an extension of floating point types.
Convenience struct for specifying and reasoning about fast-math flags.
bool allowReassoc() const
Flag queries.
An instruction for ordering other memory operations.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this fence instruction.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Type::subtype_iterator param_iterator
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
bool isConvergent() const
Determine if the call is convergent.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
AttributeList getAttributes() const
Return the attribute list for this Function.
bool doesNotThrow() const
Determine if the function cannot unwind.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
LLVM_ABI Value * getBasePtr() const
unsigned getBasePtrIndex() const
The index into the associate statepoint's argument list which contains the base pointer of the pointe...
LLVM_ABI Value * getDerivedPtr() const
unsigned getDerivedPtrIndex() const
The index into the associate statepoint's argument list which contains the pointer whose relocation t...
std::vector< const GCRelocateInst * > getGCRelocates() const
Get list of all gc reloactes linked to this statepoint May contain several relocations for the same b...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
PointerType * getType() const
Global values are always pointers.
Common base class shared among various IRBuilders.
Value * CreateAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNull=false)
LLVM_ABI Value * CreateLaunderInvariantGroup(Value *Ptr)
Create a launder.invariant.group intrinsic call.
ConstantInt * getTrue()
Get the constant value for i1 true.
LLVM_ABI Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
ConstantInt * getFalse()
Get the constant value for i1 false.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
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.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
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 * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
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 * 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,...
Instruction * SimplifyAnyMemSet(AnyMemSetInst *MI)
Instruction * foldItoFPtoI(FPToIntTy &FI)
fpto{s/u}i.sat --> X or zext(X) or sext(X) or trunc(X) This is safe if the intermediate type has enou...
Instruction * visitFree(CallInst &FI, Value *FreedOp)
Instruction * visitCallBrInst(CallBrInst &CBI)
OverflowResult computeOverflow(Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS, Instruction *CtxI) const
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Value * foldReversedIntrinsicOperands(IntrinsicInst *II)
If all arguments of the intrinsic are reverses, try to pull the reverse after the intrinsic.
const InstCombineCLOptions & CLOpts
Value * tryGetLog2(Value *Op, bool AssumeNonZero)
Instruction * visitFenceInst(FenceInst &FI)
Instruction * foldShuffledIntrinsicOperands(IntrinsicInst *II)
If all arguments of the intrinsic are unary shuffles with the same mask, try to shuffle after the int...
Instruction * visitInvokeInst(InvokeInst &II)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
void CreateNonTerminatorUnreachable(Instruction *InsertAt)
Create and insert the idiom we use to indicate a block is unreachable without having to rewrite the C...
Instruction * visitVAEndInst(VAEndInst &I)
Instruction * matchBSwapOrBitReverse(Instruction &I, bool MatchBSwaps, bool MatchBitReversals)
Given an initial instruction, check to see if it is the root of a bswap/bitreverse idiom.
Constant * unshuffleConstant(ArrayRef< int > ShMask, Constant *C, VectorType *NewCTy)
Find a constant NewC that has property: shuffle(NewC, poison, ShMask) = C for lanes that select NewC.
Instruction * visitAllocSite(Instruction &FI)
Instruction * SimplifyAnyMemTransfer(AnyMemTransferInst *MI)
Instruction * visitCallInst(CallInst &CI)
CallInst simplification.
The core instruction combiner logic.
const DataLayout & getDataLayout() const
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
DominatorTree & getDominatorTree() const
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 * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const Instruction *CtxI=nullptr, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
LLVM_ABI std::optional< Instruction * > targetInstCombineIntrinsic(IntrinsicInst &II)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
OptimizationRemarkEmitter & ORE
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 Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
bool isTerminator() const
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI std::optional< InstListType::iterator > getInsertionPointAfterDef()
Get the first insertion point at which the result of this instruction is defined.
LLVM_ABI bool isIdenticalTo(const Instruction *I) const LLVM_READONLY
Return true if the specified instruction is exactly identical to the current one.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static ICmpInst::Predicate getPredicate(Intrinsic::ID ID)
Returns the comparison predicate underlying the intrinsic.
ICmpInst::Predicate getPredicate() const
Returns the comparison predicate underlying the intrinsic.
bool isSigned() const
Whether the intrinsic is signed or unsigned.
A Module instance is used to store all the information related to an LLVM module.
StringRef getName() const
Get a short "name" for the module.
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
bool isCommutative() const
Return true if the instruction is commutative.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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)
This instruction constructs a fixed permutation of two input vectors.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
bool test(unsigned Idx) const
Returns true if bit Idx is set.
bool all() const
Returns true if all bits are set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
void setVolatile(bool V)
Specify whether this is a volatile store or not.
void setAlignment(Align Align)
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this store instruction.
Represent a constant reference to a string, i.e.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
constexpr size_t size() const
Get the string size.
LLVM_ABI size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Class to represent struct types.
static LLVM_ABI bool isCallingConvCCompatible(CallBase *CI)
Returns true if call site / callee has cdecl-compatible calling conventions.
Provides information about what library functions are available for the current target.
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
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 bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
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...
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVM_ABI const fltSemantics & getFltSemantics() const
bool isVoidTy() const
Return true if this is 'void'.
static UnaryOperator * CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
This represents the llvm.va_end intrinsic.
static LLVM_ABI void ValueIsDeleted(Value *V)
static LLVM_ABI void ValueIsRAUWd(Value *Old, Value *New)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
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 const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
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.
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
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_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.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_BSwap(const Opnd0 &Op0)
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
auto m_BitReverse(const Opnd0 &Op0)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
auto m_Poison()
Match an arbitrary poison constant.
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)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
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()...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
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'.
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.
cstfp_pred_ty< is_neg_zero_fp > m_NegZeroFP()
Match a floating-point negative zero.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
auto m_CopySign(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.
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::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
match_combine_or< match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > >, OpTy > m_ZExtOrSExtOrSelf(const OpTy &Op)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
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_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
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)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, 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)
auto m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
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.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
Exact_match< T > m_Exact(const T &SubPattern)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
auto m_UnOp()
Match an arbitrary unary operation and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_MaxOrMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
auto m_VecReverse(const Opnd0 &Op0)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
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.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
BinOpPred_match< LHS, RHS, is_bitwiselogic_op > m_BitwiseLogic(const LHS &L, const RHS &R)
Matches bitwise logic operations.
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.
auto m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
@ System
Synchronized with respect to all concurrently executing threads.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
@ 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.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI Value * simplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FMul, fold the result or return null.
LLVM_ABI APInt possiblyDemandedEltsInMask(Value *Mask)
Given a mask vector of the form <Y x i1>, return an APInt (of bitwidth Y) for each lane which may be ...
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
constexpr int64_t minIntN(int64_t N)
Gets the minimum value for a N-bit signed integer.
LLVM_ABI Value * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to @llvm.objectsize into an integer value of the given Type.
LLVM_ABI AssumeSeparateStorageInfo getAssumeSeparateStorageInfo(OperandBundleUse)
LLVM_ABI Value * getAllocAlignment(const CallBase *V, const TargetLibraryInfo *TLI)
Gets the alignment argument for an aligned_alloc-like function, using either built-in knowledge based...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
LLVM_ABI Value * simplifyCall(CallBase *Call, Value *Callee, ArrayRef< Value * > Args, const SimplifyQuery &Q)
Given a callsite, callee, and arguments, fold the result or return null.
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...
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
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 bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
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...
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
LLVM_ABI Constant * getLosslessUnsignedTrunc(Constant *C, Type *DestTy, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
bool isModSet(const ModRefInfo MRI)
void sort(IteratorTy Start, IteratorTy End)
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
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 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...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
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 ...
auto find_if_not(R &&Range, UnaryPredicate P)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
bool isAtLeastOrStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
LLVM_ABI Constant * getLosslessSignedTrunc(Constant *C, Type *DestTy, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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 bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI 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.
constexpr int PoisonMaskElem
@ Mod
The access may modify the value stored in memory.
LLVM_ABI Value * simplifyFMAFMul(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for the multiplication of a FMA, fold the result or return null.
LLVM_ABI Value * simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q)
Given a constrained FP intrinsic call, tries to compute its simplified version.
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 minNum semantics.
OperandBundleDefT< Value * > OperandBundleDef
LLVM_ABI AssumeNonNullInfo getAssumeNonNullInfo(OperandBundleUse)
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
constexpr int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
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...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI std::optional< APInt > getAllocSize(const CallBase *CB, const TargetLibraryInfo *TLI, function_ref< const Value *(const Value *)> Mapper=[](const Value *V) { return V;})
Return the size of the requested allocation.
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
unsigned Log2(Align A)
Returns the log2 of the alignment.
LLVM_ABI bool maskContainsAllOneOrUndef(Value *Mask)
Given a mask vector of i1, Return true if any of the elements of this predicate mask are known to be ...
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
LLVM_ABI AssumeDereferenceableInfo getAssumeDereferenceableInfo(OperandBundleUse)
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 AssumeNoUndefInfo getAssumeNoUndefInfo(OperandBundleUse)
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
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.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Represent subnormal handling kind for floating point instruction inputs and outputs.
@ IEEE
IEEE-754 denormal numbers preserved.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
SelectPatternFlavor Flavor
SimplifyQuery getWithInstruction(const Instruction *I) const