28#include "llvm/IR/IntrinsicsAMDGPU.h"
36#define DEBUG_TYPE "AMDGPUtti"
40struct AMDGPUImageDMaskIntrinsic {
44#define GET_AMDGPUImageDMaskIntrinsicTable_IMPL
45#include "AMDGPUGenSearchableTables.inc"
55 assert(!Src0.isNaN() && !Src1.isNaN() && !Src2.isNaN() &&
56 "nans handled separately");
74 bool AllowI16SExt =
false) {
75 Type *VTy =
V.getType();
84 APFloat FloatValue(ConstFloat->getValueAPF());
85 bool LosesInfo =
true;
94 APInt IntValue(ConstInt->getValue());
103 Value *CastCandidate;
110 if (!IsExt && !IsFloat && AllowI16SExt)
123 Type *VTy =
V.getType();
132 return Builder.CreateExtractElement(VecCast->
getOperand(0), Idx);
156 Func(Args, OverloadTys);
172 bool RemoveOldIntr = &OldIntr != &InstToReplace;
181static std::optional<Instruction *>
189 if (
const auto *LZMappingInfo =
191 if (
auto *ConstantLod =
193 if (ConstantLod->isZero() || ConstantLod->isNegative()) {
198 II,
II, NewImageDimIntr->
Intr, IC, [&](
auto &Args,
auto &ArgTys) {
199 Args.erase(Args.begin() + ImageDimIntr->LodIndex);
206 if (
const auto *MIPMappingInfo =
208 if (
auto *ConstantMip =
210 if (ConstantMip->isZero()) {
215 II,
II, NewImageDimIntr->
Intr, IC, [&](
auto &Args,
auto &ArgTys) {
216 Args.erase(Args.begin() + ImageDimIntr->MipIndex);
223 if (
const auto *BiasMappingInfo =
225 if (
auto *ConstantBias =
227 if (ConstantBias->isZero()) {
232 II,
II, NewImageDimIntr->
Intr, IC, [&](
auto &Args,
auto &ArgTys) {
233 Args.erase(Args.begin() + ImageDimIntr->BiasIndex);
234 ArgTys.erase(ArgTys.begin() + ImageDimIntr->BiasTyArg);
241 if (
const auto *OffsetMappingInfo =
243 if (
auto *ConstantOffset =
245 if (ConstantOffset->isZero()) {
248 OffsetMappingInfo->NoOffset, ImageDimIntr->
Dim);
250 II,
II, NewImageDimIntr->
Intr, IC, [&](
auto &Args,
auto &ArgTys) {
251 Args.erase(Args.begin() + ImageDimIntr->OffsetIndex);
267 (DimInfo->
MSAA ? 1 : 0);
269 if (ConstantSlice && ConstantSlice->isZero()) {
274 [&](
auto &Args,
auto &ArgTys) {
275 Args.erase(Args.begin() + SliceIndex);
282 if (ST->hasD16Images()) {
288 if (
II.hasOneUse()) {
291 if (
User->getOpcode() == Instruction::FPTrunc &&
295 [&](
auto &Args,
auto &ArgTys) {
298 ArgTys[0] = User->getType();
307 bool AllHalfExtracts =
true;
309 for (
User *U :
II.users()) {
311 if (!Ext || !Ext->hasOneUse()) {
312 AllHalfExtracts =
false;
317 if (!Tr || !Tr->getType()->isHalfTy()) {
318 AllHalfExtracts =
false;
325 if (!ExtractTruncPairs.
empty() && AllHalfExtracts) {
336 OverloadTys[0] = HalfVecTy;
339 M, ImageDimIntr->
Intr, OverloadTys);
341 II.mutateType(HalfVecTy);
342 II.setCalledFunction(HalfDecl);
345 for (
auto &[Ext, Tr] : ExtractTruncPairs) {
346 Value *Idx = Ext->getIndexOperand();
348 Builder.SetInsertPoint(Tr);
350 Value *HalfExtract = Builder.CreateExtractElement(&
II, Idx);
353 Tr->replaceAllUsesWith(HalfExtract);
356 for (
auto &[Ext, Tr] : ExtractTruncPairs) {
367 if (!ST->hasA16() && !ST->hasG16())
372 bool HasSampler = BaseOpcode->
Sampler;
373 bool FloatCoord =
false;
375 bool OnlyDerivatives =
false;
380 bool AllowI16SExt = !HasSampler;
383 OperandIndex < ImageDimIntr->VAddrEnd; OperandIndex++) {
384 Value *Coord =
II.getOperand(OperandIndex);
387 if (OperandIndex < ImageDimIntr->CoordStart ||
392 OnlyDerivatives =
true;
401 if (!OnlyDerivatives && !ST->hasA16())
402 OnlyDerivatives =
true;
405 if (!OnlyDerivatives && ImageDimIntr->
NumBiasArgs != 0) {
408 "Only image instructions with a sampler can have a bias");
410 OnlyDerivatives =
true;
413 if (OnlyDerivatives && (!ST->hasG16() || ImageDimIntr->
GradientStart ==
421 II,
II,
II.getIntrinsicID(), IC, [&](
auto &Args,
auto &ArgTys) {
422 ArgTys[ImageDimIntr->GradientTyArg] = CoordType;
423 if (!OnlyDerivatives) {
424 ArgTys[ImageDimIntr->CoordTyArg] = CoordType;
427 if (ImageDimIntr->NumBiasArgs != 0)
428 ArgTys[ImageDimIntr->BiasTyArg] = Type::getHalfTy(II.getContext());
434 OperandIndex < EndIndex; OperandIndex++) {
436 convertTo16Bit(*II.getOperand(OperandIndex), IC.Builder);
441 Value *Bias = II.getOperand(ImageDimIntr->BiasIndex);
442 Args[ImageDimIntr->BiasIndex] = convertTo16Bit(*Bias, IC.Builder);
476 if (
I.hasNoSignedZeros() &&
486 Value *Src =
nullptr;
489 if (Src->getType()->isHalfTy())
506 unsigned VWidth = VTy->getNumElements();
509 for (
int i = VWidth - 1; i > 0; --i) {
531 unsigned VWidth = VTy->getNumElements();
537 SVI->getShuffleMask(ShuffleMask);
539 for (
int I = VWidth - 1;
I > 0; --
I) {
540 if (ShuffleMask.empty()) {
568 unsigned LaneArgIdx)
const {
569 unsigned MaskBits = ST->getWavefrontSizeLog2();
576 if (!
Known.isConstant())
583 Value *LaneArg =
II.getArgOperand(LaneArgIdx);
585 ConstantInt::get(LaneArg->
getType(),
Known.getConstant() & DemandedMask);
586 if (MaskedConst != LaneArg) {
587 II.getOperandUse(LaneArgIdx).set(MaskedConst);
597 unsigned ScaleArgIdx) {
598 Value *Scale =
II.getArgOperand(ScaleArgIdx);
600 if (StrippedSign != Scale) {
606 if (!BC || !BC->hasOneUse() || !BC->getSrcTy()->isIntegerTy(32))
619 CallInst *NewCall =
B.CreateCall(&NewCallee,
Ops, OpBundles);
635 if (ST.isWave32() &&
match(
V, W32Pred))
637 if (ST.isWave64() &&
match(
V, W64Pred))
644 if (!
I || !ST.isWaveSizeKnown())
648 if (!ST.hasWavefrontsEvenlySplittingXDim(
F,
true))
651 unsigned WaveSize = ST.getWavefrontSize();
656 return match(
V, TidX) && ST.getMaxWorkitemID(
F, 0) < WaveSize;
662 const auto IID =
II.getIntrinsicID();
663 assert(IID == Intrinsic::amdgcn_readlane ||
664 IID == Intrinsic::amdgcn_readfirstlane ||
665 IID == Intrinsic::amdgcn_permlane64);
675 const bool IsReadLane = (IID == Intrinsic::amdgcn_readlane);
679 Value *LaneID =
nullptr;
681 LaneID =
II.getOperand(1);
695 const auto DoIt = [&](
unsigned OpIdx,
699 Ops.push_back(LaneID);
715 return DoIt(0,
II.getCalledFunction());
719 Type *SrcTy = Src->getType();
725 return DoIt(0, Remangled);
733 return DoIt(1,
II.getCalledFunction());
735 return DoIt(0,
II.getCalledFunction());
746 unsigned Depth = 0) {
756 return CI->getZExtValue();
765 std::optional<uint64_t>
LHS =
769 std::optional<uint64_t>
RHS =
778 return CI ? std::optional<uint64_t>(CI->getZExtValue()) : std::nullopt;
786 unsigned WaveSize = ST.getWavefrontSize();
788 for (
unsigned Lane :
seq(WaveSize)) {
790 if (!Val || *Val >= WaveSize)
792 Ids[Lane] =
static_cast<uint8_t>(*Val);
799template <
unsigned Period>
801 static_assert(
isPowerOf2_32(Period),
"Period must be a power of two");
802 for (
size_t I = Period,
E = Ids.
size();
I <
E; ++
I)
803 if (Ids[
I] != Ids[
I % Period] + (
I & ~(Period - 1)))
811 for (
unsigned I = 0;
I <
N; ++
I)
827 return Ids[3] << 6 | Ids[2] << 4 | Ids[1] << 2 | Ids[0];
834 for (
unsigned J = 0; J <
N; ++J)
835 if (Ids[J] != (
N - 1) - J)
847 for (
unsigned J = 1; J < 16; ++J)
848 if (Ids[J] != (Ids[0] + J) % 16)
866 unsigned Mask = Ids[0];
869 for (
unsigned J = 0; J < 16; ++J)
870 if (Ids[J] != (Mask ^ J))
880 unsigned Selector = 0;
881 for (
unsigned J = 0; J < 8; ++J)
882 Selector |= Ids[J] << (J * 3);
891 for (
unsigned J = 0; J < 16; ++J)
892 Sel |=
static_cast<uint64_t>(Ids[J] & 0xF) << (J * 4);
899 if (Ids.
size() != 64)
901 for (
unsigned J = 0; J < 64; ++J)
902 if (Ids[J] != (J ^ 32))
913 for (
unsigned J = 0; J < 16; ++J) {
914 if (Ids[J] < 16 || Ids[J] >= 32)
916 if (Ids[J + 16] != Ids[J] - 16)
927static std::optional<unsigned>
936 unsigned AndMask = 0, OrMask = 0, XorMask = 0;
937 for (
unsigned B = 0;
B < 5; ++
B) {
938 unsigned Bit0 = (Ids[0] >>
B) & 1;
939 unsigned Bit1 = (Ids[1ull <<
B] >>
B) & 1;
942 XorMask |= Bit0 <<
B;
950 for (
unsigned I :
seq(32u)) {
951 unsigned Expected = ((
I & AndMask) | OrMask) ^ XorMask;
966static std::optional<unsigned>
977 for (
unsigned I = 0;
I < 32; ++
I)
978 if (Ids[
I] != (
I +
N) % 32)
990 return B.CreateIntrinsic(Intrinsic::amdgcn_update_dpp, {Ty},
992 B.getInt32(0xF),
B.getInt32(0xF),
B.getTrue()});
997 return B.CreateIntrinsic(Intrinsic::amdgcn_mov_dpp8, {Val->
getType()},
998 {Val,
B.getInt32(Selector)});
1005 return B.CreateIntrinsic(Intrinsic::amdgcn_permlane16, {Ty},
1007 B.getInt32(
Hi),
B.getFalse(),
B.getFalse()});
1015 return B.CreateIntrinsic(Intrinsic::amdgcn_permlanex16, {Ty},
1017 B.getInt32(
Hi),
B.getFalse(),
B.getFalse()});
1025 assert(
DL.getTypeSizeInBits(OrigTy) == 32 &&
1026 "ds_swizzle only supports 32-bit operands");
1030 Src =
B.CreatePtrToInt(Src, I32Ty);
1031 else if (OrigTy != I32Ty)
1032 Src =
B.CreateBitCast(Src, I32Ty);
1033 Value *Result =
B.CreateIntrinsic(Intrinsic::amdgcn_ds_swizzle, {},
1036 return B.CreateIntToPtr(Result, OrigTy);
1037 if (OrigTy != I32Ty)
1038 return B.CreateBitCast(Result, OrigTy);
1044 return B.CreateIntrinsic(Intrinsic::amdgcn_permlane64, {Val->
getType()},
1055 [](
const auto &
E) {
return E.value() ==
E.index(); }))
1079 if (ST.hasDPPRowShare()) {
1084 if (ST.hasDPP() && ST.hasGFX10Insts()) {
1094 if (ST.hasPermlane16Insts()) {
1114 if (ST.hasDsSwizzleRotateMode()) {
1127static std::optional<Instruction *>
1131 if (
DL.getTypeSizeInBits(
II.getType()) != 32)
1132 return std::nullopt;
1134 if (!ST.isWaveSizeKnown())
1135 return std::nullopt;
1137 unsigned WaveSize = ST.getWavefrontSize();
1138 bool IsBpermute =
II.getIntrinsicID() == Intrinsic::amdgcn_ds_bpermute;
1139 Value *Src =
II.getArgOperand(IsBpermute ? 1 : 0);
1140 Value *Index =
II.getArgOperand(IsBpermute ? 0 : 1);
1145 for (
unsigned Lane :
seq(WaveSize)) {
1147 if (!Val || (*Val & 3) || (*Val >> 2) >= WaveSize)
1148 return std::nullopt;
1149 Ids[Lane] =
static_cast<uint8_t>(*Val >> 2);
1153 return std::nullopt;
1158 return std::nullopt;
1172 const APInt *Acc =
nullptr;
1180 Value *AccumDelta =
nullptr;
1184 Value *NewAcc =
nullptr;
1185 const APInt *AccumDeltaC =
nullptr;
1187 NewAcc = AccumDelta;
1189 NewAcc = ConstantInt::get(
II.getType(), *Acc + *AccumDeltaC);
1203std::optional<Instruction *>
1207 case Intrinsic::amdgcn_implicitarg_ptr: {
1208 if (
II.getFunction()->hasFnAttribute(
"amdgpu-no-implicitarg-ptr"))
1210 uint64_t ImplicitArgBytes = ST->getImplicitArgNumBytes(*
II.getFunction());
1212 uint64_t CurrentOrNullBytes =
1213 II.getAttributes().getRetDereferenceableOrNullBytes();
1214 if (CurrentOrNullBytes != 0) {
1217 uint64_t NewBytes = std::max(CurrentOrNullBytes, ImplicitArgBytes);
1220 II.removeRetAttr(Attribute::DereferenceableOrNull);
1224 uint64_t CurrentBytes =
II.getAttributes().getRetDereferenceableBytes();
1225 uint64_t NewBytes = std::max(CurrentBytes, ImplicitArgBytes);
1226 if (NewBytes != CurrentBytes) {
1232 return std::nullopt;
1234 case Intrinsic::amdgcn_rcp: {
1235 Value *Src =
II.getArgOperand(0);
1246 if (
II.isStrictFP())
1264 auto IID = SrcCI->getIntrinsicID();
1269 if (IID == Intrinsic::amdgcn_sqrt || IID == Intrinsic::sqrt) {
1279 SrcCI->getModule(), Intrinsic::amdgcn_rsq, {SrcCI->getType()});
1282 II.setFastMathFlags(InnerFMF);
1284 II.setCalledFunction(NewDecl);
1290 case Intrinsic::amdgcn_sqrt:
1291 case Intrinsic::amdgcn_rsq:
1292 case Intrinsic::amdgcn_tanh: {
1293 Value *Src =
II.getArgOperand(0);
1305 if (IID == Intrinsic::amdgcn_sqrt && Src->getType()->isHalfTy()) {
1307 II.getModule(), Intrinsic::sqrt, {II.getType()});
1308 II.setCalledFunction(NewDecl);
1314 case Intrinsic::amdgcn_log:
1315 case Intrinsic::amdgcn_exp2: {
1316 const bool IsLog = IID == Intrinsic::amdgcn_log;
1317 const bool IsExp = IID == Intrinsic::amdgcn_exp2;
1318 Value *Src =
II.getArgOperand(0);
1328 if (
C->isInfinity()) {
1331 if (!
C->isNegative())
1335 if (IsExp &&
C->isNegative())
1339 if (
II.isStrictFP())
1343 Constant *Quieted = ConstantFP::get(Ty,
C->getValue().makeQuiet());
1348 if (
C->isZero() || (
C->getValue().isDenormal() && Ty->isFloatTy())) {
1350 : ConstantFP::get(Ty, 1.0);
1354 if (IsLog &&
C->isNegative())
1362 case Intrinsic::amdgcn_frexp_mant:
1363 case Intrinsic::amdgcn_frexp_exp: {
1364 Value *Src =
II.getArgOperand(0);
1370 if (IID == Intrinsic::amdgcn_frexp_mant) {
1372 II, ConstantFP::get(
II.getContext(), Significand));
1392 case Intrinsic::amdgcn_class: {
1393 Value *Src0 =
II.getArgOperand(0);
1394 Value *Src1 =
II.getArgOperand(1);
1398 II.getModule(), Intrinsic::is_fpclass, Src0->getType()));
1401 II.setArgOperand(1, ConstantInt::get(Src1->getType(),
1422 case Intrinsic::amdgcn_cvt_pkrtz: {
1423 auto foldFPTruncToF16RTZ = [](
Value *Arg) ->
Value * {
1436 return ConstantFP::get(HalfTy, Val);
1439 Value *Src =
nullptr;
1441 if (Src->getType()->isHalfTy())
1448 if (
Value *Src0 = foldFPTruncToF16RTZ(
II.getArgOperand(0))) {
1449 if (
Value *Src1 = foldFPTruncToF16RTZ(
II.getArgOperand(1))) {
1459 case Intrinsic::amdgcn_cvt_pknorm_i16:
1460 case Intrinsic::amdgcn_cvt_pknorm_u16:
1461 case Intrinsic::amdgcn_cvt_pk_i16:
1462 case Intrinsic::amdgcn_cvt_pk_u16: {
1463 Value *Src0 =
II.getArgOperand(0);
1464 Value *Src1 =
II.getArgOperand(1);
1476 case Intrinsic::amdgcn_cvt_off_f32_i4: {
1477 Value* Arg =
II.getArgOperand(0);
1491 constexpr size_t ResValsSize = 16;
1492 static constexpr float ResVals[ResValsSize] = {
1493 0.0, 0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375,
1494 -0.5, -0.4375, -0.375, -0.3125, -0.25, -0.1875, -0.125, -0.0625};
1496 ConstantFP::get(Ty, ResVals[CArg->
getZExtValue() & (ResValsSize - 1)]);
1499 case Intrinsic::amdgcn_ubfe:
1500 case Intrinsic::amdgcn_sbfe: {
1502 Value *Src =
II.getArgOperand(0);
1509 unsigned IntSize = Ty->getIntegerBitWidth();
1514 if ((Width & (IntSize - 1)) == 0) {
1519 if (Width >= IntSize) {
1521 II, 2, ConstantInt::get(CWidth->
getType(), Width & (IntSize - 1)));
1532 ConstantInt::get(COffset->
getType(),
Offset & (IntSize - 1)));
1536 bool Signed = IID == Intrinsic::amdgcn_sbfe;
1538 if (!CWidth || !COffset)
1548 if (
Offset + Width < IntSize) {
1552 RightShift->takeName(&
II);
1559 RightShift->takeName(&
II);
1562 case Intrinsic::amdgcn_exp:
1563 case Intrinsic::amdgcn_exp_row:
1564 case Intrinsic::amdgcn_exp_compr: {
1570 bool IsCompr = IID == Intrinsic::amdgcn_exp_compr;
1572 for (
int I = 0;
I < (IsCompr ? 2 : 4); ++
I) {
1573 if ((!IsCompr && (EnBits & (1ULL <<
I)) == 0) ||
1574 (IsCompr && ((EnBits & (0x3ULL << (2 *
I))) == 0))) {
1575 Value *Src =
II.getArgOperand(
I + 2);
1589 case Intrinsic::amdgcn_fmed3: {
1590 Value *Src0 =
II.getArgOperand(0);
1591 Value *Src1 =
II.getArgOperand(1);
1592 Value *Src2 =
II.getArgOperand(2);
1594 for (
Value *Src : {Src0, Src1, Src2}) {
1599 if (
II.isStrictFP())
1636 const APFloat *ConstSrc0 =
nullptr;
1637 const APFloat *ConstSrc1 =
nullptr;
1638 const APFloat *ConstSrc2 =
nullptr;
1643 const bool IsPosInfinity = ConstSrc0 && ConstSrc0->
isPosInfinity();
1663 const bool IsPosInfinity = ConstSrc1 && ConstSrc1->
isPosInfinity();
1686 auto *Quieted = ConstantFP::get(
II.getType(), ConstSrc2->
makeQuiet());
1706 CI->copyFastMathFlags(&
II);
1732 II.setArgOperand(0, Src0);
1733 II.setArgOperand(1, Src1);
1734 II.setArgOperand(2, Src2);
1744 ConstantFP::get(
II.getType(), Result));
1749 if (!ST->hasMed3_16())
1758 IID, {
X->getType()}, {
X,
Y, Z}, &
II,
II.getName());
1766 case Intrinsic::amdgcn_mbcnt_hi:
1771 case Intrinsic::amdgcn_mbcnt_lo: {
1781 IID == Intrinsic::amdgcn_mbcnt_lo && ST->isWave64() ? 32 : 31;
1787 if (std::optional<ConstantRange> ExistingRange =
II.getRange()) {
1788 ComputedRange = ComputedRange.
intersectWith(*ExistingRange);
1789 if (ComputedRange == *ExistingRange)
1793 II.addRangeRetAttr(ComputedRange);
1796 case Intrinsic::amdgcn_ballot: {
1797 Value *Arg =
II.getArgOperand(0);
1802 if (Src->isZero()) {
1807 if (ST->isWave32() &&
II.getType()->getIntegerBitWidth() == 64) {
1814 {IC.Builder.getInt32Ty()},
1815 {II.getArgOperand(0)}),
1822 case Intrinsic::amdgcn_cluster_workgroup_max_id_x:
1823 case Intrinsic::amdgcn_cluster_workgroup_max_id_y:
1824 case Intrinsic::amdgcn_cluster_workgroup_max_id_z:
1825 case Intrinsic::amdgcn_cluster_workgroup_max_flat_id: {
1832 const auto &Dims = ClusterDims.
getDims();
1833 if (Dims[0] == 0 || Dims[1] == 0 || Dims[2] == 0)
1838 case Intrinsic::amdgcn_cluster_workgroup_max_id_x:
1839 MaxID = Dims[0] - 1;
1841 case Intrinsic::amdgcn_cluster_workgroup_max_id_y:
1842 MaxID = Dims[1] - 1;
1844 case Intrinsic::amdgcn_cluster_workgroup_max_id_z:
1845 MaxID = Dims[2] - 1;
1847 case Intrinsic::amdgcn_cluster_workgroup_max_flat_id:
1848 MaxID = Dims[0] * Dims[1] * Dims[2] - 1;
1856 case Intrinsic::amdgcn_wavefrontsize: {
1857 if (ST->isWaveSizeKnown())
1859 II, ConstantInt::get(
II.getType(), ST->getWavefrontSize()));
1862 case Intrinsic::amdgcn_wqm_vote: {
1869 case Intrinsic::amdgcn_kill: {
1871 if (!
C || !
C->getZExtValue())
1877 case Intrinsic::amdgcn_s_sendmsg:
1878 case Intrinsic::amdgcn_s_sendmsghalt: {
1884 Value *M0Val =
II.getArgOperand(1);
1889 uint16_t MsgId, OpId, StreamId;
1890 decodeMsg(
static_cast<unsigned>(MsgImm->getZExtValue()), MsgId, OpId,
1893 if (!msgDoesNotUseM0(MsgId, *ST))
1897 II.dropUBImplyingAttrsAndMetadata();
1901 case Intrinsic::amdgcn_update_dpp: {
1902 Value *Old =
II.getArgOperand(0);
1907 if (BC->isNullValue() || RM->getZExtValue() != 0xF ||
1914 case Intrinsic::amdgcn_permlane16:
1915 case Intrinsic::amdgcn_permlane16_var:
1916 case Intrinsic::amdgcn_permlanex16:
1917 case Intrinsic::amdgcn_permlanex16_var: {
1919 Value *VDstIn =
II.getArgOperand(0);
1924 unsigned int FiIdx = (IID == Intrinsic::amdgcn_permlane16 ||
1925 IID == Intrinsic::amdgcn_permlanex16)
1932 unsigned int BcIdx = FiIdx + 1;
1941 case Intrinsic::amdgcn_wave_shuffle:
1943 case Intrinsic::amdgcn_permlane64:
1944 case Intrinsic::amdgcn_readfirstlane:
1945 case Intrinsic::amdgcn_readlane:
1946 case Intrinsic::amdgcn_ds_bpermute: {
1948 unsigned SrcIdx = IID == Intrinsic::amdgcn_ds_bpermute ? 1 : 0;
1949 const Use &Src =
II.getArgOperandUse(SrcIdx);
1953 if (IID == Intrinsic::amdgcn_readlane &&
1960 if (IID == Intrinsic::amdgcn_ds_bpermute) {
1961 const Use &Lane =
II.getArgOperandUse(0);
1965 II.getModule(), Intrinsic::amdgcn_readlane,
II.getType());
1966 II.setCalledFunction(NewDecl);
1967 II.setOperand(0, Src);
1968 II.setOperand(1, NewLane);
1973 if (IID == Intrinsic::amdgcn_ds_bpermute)
1979 return std::nullopt;
1981 case Intrinsic::amdgcn_wave_match_b32: {
1982 const Use &Src0 =
II.getArgOperandUse(0);
1983 const Use &Src1 =
II.getArgOperandUse(1);
1986 II.getModule(), Intrinsic::amdgcn_ballot,
II.getType());
1993 case Intrinsic::amdgcn_writelane: {
1997 return std::nullopt;
1999 case Intrinsic::amdgcn_trig_preop: {
2002 if (!
II.getType()->isDoubleTy())
2005 Value *Src =
II.getArgOperand(0);
2006 Value *Segment =
II.getArgOperand(1);
2015 if (StrippedSign != Src)
2018 if (
II.isStrictFP())
2040 unsigned SegmentVal =
2041 static_cast<unsigned>(Cseg->
getValue().trunc(5).getZExtValue());
2042 unsigned Shift = SegmentVal * 53;
2047 static const uint32_t TwoByPi[] = {
2048 0xa2f9836e, 0x4e441529, 0xfc2757d1, 0xf534ddc0, 0xdb629599, 0x3c439041,
2049 0xfe5163ab, 0xdebbc561, 0xb7246e3a, 0x424dd2e0, 0x06492eea, 0x09d1921c,
2050 0xfe1deb1c, 0xb129a73e, 0xe88235f5, 0x2ebb4484, 0xe99c7026, 0xb45f7e41,
2051 0x3991d639, 0x835339f4, 0x9c845f8b, 0xbdf9283b, 0x1ff897ff, 0xde05980f,
2052 0xef2f118b, 0x5a0a6d1f, 0x6d367ecf, 0x27cb09b7, 0x4f463f66, 0x9e5fea2d,
2053 0x7527bac7, 0xebe5f17b, 0x3d0739f7, 0x8a5292ea, 0x6bfb5fb1, 0x1f8d5d08,
2057 unsigned Idx = Shift >> 5;
2058 if (Idx + 2 >= std::size(TwoByPi)) {
2063 unsigned BShift = Shift & 0x1f;
2064 uint64_t Thi =
Make_64(TwoByPi[Idx], TwoByPi[Idx + 1]);
2065 uint64_t Tlo =
Make_64(TwoByPi[Idx + 2], 0);
2067 Thi = (Thi << BShift) | (Tlo >> (64 - BShift));
2071 int Scale = -53 - Shift;
2078 case Intrinsic::amdgcn_sdot2:
2079 case Intrinsic::amdgcn_udot2:
2080 case Intrinsic::amdgcn_sdot4:
2081 case Intrinsic::amdgcn_udot4:
2082 case Intrinsic::amdgcn_sdot8:
2083 case Intrinsic::amdgcn_udot8: {
2084 Value *Src0 =
II.getArgOperand(0);
2085 Value *Src1 =
II.getArgOperand(1);
2089 II.setArgOperand(0, Src1);
2090 II.setArgOperand(1, Src0);
2102 case Intrinsic::amdgcn_sudot4:
2103 case Intrinsic::amdgcn_sudot8: {
2104 Value *Src0 =
II.getArgOperand(1);
2105 Value *Src1 =
II.getArgOperand(3);
2110 Value *Sign0 =
II.getArgOperand(0);
2111 Value *Sign1 =
II.getArgOperand(2);
2112 II.setArgOperand(0, Sign1);
2113 II.setArgOperand(1, Src1);
2114 II.setArgOperand(2, Sign0);
2115 II.setArgOperand(3, Src0);
2127 case Intrinsic::amdgcn_fmul_legacy: {
2128 Value *Op0 =
II.getArgOperand(0);
2129 Value *Op1 =
II.getArgOperand(1);
2131 for (
Value *Src : {Op0, Op1}) {
2152 case Intrinsic::amdgcn_fma_legacy: {
2153 Value *Op0 =
II.getArgOperand(0);
2154 Value *Op1 =
II.getArgOperand(1);
2155 Value *Op2 =
II.getArgOperand(2);
2157 for (
Value *Src : {Op0, Op1, Op2}) {
2179 II.getModule(), Intrinsic::fma,
II.getType()));
2184 case Intrinsic::amdgcn_is_shared:
2185 case Intrinsic::amdgcn_is_private: {
2186 Value *Src =
II.getArgOperand(0);
2196 case Intrinsic::amdgcn_make_buffer_rsrc: {
2197 Value *Src =
II.getArgOperand(0);
2202 std::optional<unsigned> Width = ST->getBufferResourceNumRecordsWidth();
2204 return std::nullopt;
2206 if (
II.getArgOperand(2)->getType() == NumRecordsTy)
2207 return std::nullopt;
2211 Intrinsic::amdgcn_make_buffer_rsrc,
2212 {
II.getType(), Src->getType(), NumRecordsTy}, Args);
2218 II.getAttributes().removeParamAttributes(
II.getContext(), 2));
2222 case Intrinsic::amdgcn_raw_buffer_store_format:
2223 case Intrinsic::amdgcn_raw_ptr_buffer_store_format:
2224 case Intrinsic::amdgcn_struct_buffer_store_format:
2225 case Intrinsic::amdgcn_struct_ptr_buffer_store_format:
2226 case Intrinsic::amdgcn_raw_tbuffer_store:
2227 case Intrinsic::amdgcn_raw_ptr_tbuffer_store:
2228 case Intrinsic::amdgcn_struct_tbuffer_store:
2229 case Intrinsic::amdgcn_struct_ptr_tbuffer_store:
2230 case Intrinsic::amdgcn_image_store_1d:
2231 case Intrinsic::amdgcn_image_store_1darray:
2232 case Intrinsic::amdgcn_image_store_2d:
2233 case Intrinsic::amdgcn_image_store_2darray:
2234 case Intrinsic::amdgcn_image_store_2darraymsaa:
2235 case Intrinsic::amdgcn_image_store_2dmsaa:
2236 case Intrinsic::amdgcn_image_store_3d:
2237 case Intrinsic::amdgcn_image_store_cube:
2238 case Intrinsic::amdgcn_image_store_mip_1d:
2239 case Intrinsic::amdgcn_image_store_mip_1darray:
2240 case Intrinsic::amdgcn_image_store_mip_2d:
2241 case Intrinsic::amdgcn_image_store_mip_2darray:
2242 case Intrinsic::amdgcn_image_store_mip_3d:
2243 case Intrinsic::amdgcn_image_store_mip_cube: {
2248 if (ST->hasDefaultComponentBroadcast())
2250 else if (ST->hasDefaultComponentZero())
2260 case Intrinsic::amdgcn_prng_b32: {
2261 auto *Src =
II.getArgOperand(0);
2265 return std::nullopt;
2267 case Intrinsic::amdgcn_mfma_scale_f32_16x16x128_f8f6f4:
2268 case Intrinsic::amdgcn_mfma_scale_f32_32x32x64_f8f6f4: {
2269 Value *Src0 =
II.getArgOperand(0);
2270 Value *Src1 =
II.getArgOperand(1);
2276 auto getFormatNumRegs = [](uint64_t FormatVal) {
2277 switch (FormatVal) {
2291 bool MadeChange =
false;
2292 unsigned Src0NumElts = getFormatNumRegs(CBSZ);
2293 unsigned Src1NumElts = getFormatNumRegs(BLGP);
2297 if (Src0Ty->getNumElements() > Src0NumElts) {
2304 if (Src1Ty->getNumElements() > Src1NumElts) {
2312 return std::nullopt;
2319 IID, {Src0->getType(), Src1->getType()}, Args, &
II);
2323 case Intrinsic::amdgcn_wmma_f32_16x16x128_f8f6f4:
2324 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
2325 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
2326 Value *Src0 =
II.getArgOperand(1);
2327 Value *Src1 =
II.getArgOperand(3);
2333 bool MadeChange =
false;
2339 if (Src0Ty->getNumElements() > Src0NumElts) {
2346 if (Src1Ty->getNumElements() > Src1NumElts) {
2354 return std::nullopt;
2361 IID, {
II.getArgOperand(5)->getType(), Src0->getType(), Src1->getType()},
2371 if (std::optional<unsigned> ScaleArgIdx =
2376 return std::nullopt;
2390 const bool IsLoad = !
II.getType()->isVoidTy();
2392 if (getAMDGPUImageDMaskIntrinsic(
II.getIntrinsicID()))
2393 DMaskIdx = IsLoad ? 0 : 1;
2396 :
II.getOperand(0)->getType());
2397 unsigned VWidth = IIVTy->getNumElements();
2400 Type *EltTy = IIVTy->getElementType();
2407 uint64_t OffsetAdd = 0;
2413 const unsigned UnusedComponentsAtFront = DemandedElts.
countr_zero();
2418 DemandedElts = (1 << ActiveBits) - 1;
2420 if (UnusedComponentsAtFront > 0) {
2425 bool CanAdjustOffset = BufInfo &&
2426 (BufInfo->
Kind == AMDGPU::BufferKindLoad ||
2427 BufInfo->
Kind == AMDGPU::BufferKindSLoad) &&
2432 if (CanAdjustOffset && BufInfo->
Kind == AMDGPU::BufferKindSLoad &&
2433 ActiveBits == 4 && UnusedComponentsAtFront == 1)
2434 CanAdjustOffset =
false;
2437 unsigned FormatBitsPerComp = 0;
2438 if (CanAdjustOffset && BufInfo->
isTyped()) {
2448 if (OldFormat && ActiveBits <= OldFormat->NumComponents)
2455 ConstantInt::get(Args[FormatIdx]->
getType(), NewFormat->
Format);
2458 CanAdjustOffset =
false;
2462 if (CanAdjustOffset) {
2465 DemandedElts &= ~((1 << UnusedComponentsAtFront) - 1);
2466 auto *
Offset = Args[OffsetIdx];
2467 uint64_t SingleComponentSizeInBits =
2471 OffsetAdd = UnusedComponentsAtFront * SingleComponentSizeInBits / 8;
2472 auto *OffsetAddVal = ConstantInt::get(
Offset->getType(), OffsetAdd);
2492 unsigned NewDMaskVal = 0;
2493 unsigned OrigLdStIdx = 0;
2494 for (
unsigned SrcIdx = 0; SrcIdx < 4; ++SrcIdx) {
2495 const unsigned Bit = 1 << SrcIdx;
2496 if (!!(DMaskVal & Bit)) {
2497 if (!!DemandedElts[OrigLdStIdx])
2503 if (DMaskVal != NewDMaskVal)
2504 Args[DMaskIdx] = ConstantInt::get(DMask->
getType(), NewDMaskVal);
2507 unsigned NewNumElts = DemandedElts.
popcount();
2511 if (NewNumElts >= VWidth && DemandedElts.
isMask()) {
2513 II.setArgOperand(DMaskIdx, Args[DMaskIdx]);
2525 OverloadTys[0] = NewTy;
2529 for (
unsigned OrigStoreIdx = 0; OrigStoreIdx < VWidth; ++OrigStoreIdx)
2530 if (DemandedElts[OrigStoreIdx])
2533 if (NewNumElts == 1)
2540 II.getIntrinsicID(), OverloadTys, Args);
2546 if (OffsetAdd != 0) {
2559 if (NewNumElts == 1) {
2565 unsigned NewLoadIdx = 0;
2566 for (
unsigned OrigLoadIdx = 0; OrigLoadIdx < VWidth; ++OrigLoadIdx) {
2567 if (!!DemandedElts[OrigLoadIdx])
2583 APInt &UndefElts)
const {
2588 const unsigned FirstElt = DemandedElts.
countr_zero();
2590 const unsigned MaskLen = LastElt - FirstElt + 1;
2592 unsigned OldNumElts = VT->getNumElements();
2593 if (MaskLen == OldNumElts && MaskLen != 1)
2596 Type *EltTy = VT->getElementType();
2604 Value *Src =
II.getArgOperand(0);
2609 II.getOperandBundlesAsDefs(OpBundles);
2626 for (
unsigned I = 0;
I != MaskLen; ++
I) {
2627 if (DemandedElts[FirstElt +
I])
2628 ExtractMask[
I] = FirstElt +
I;
2637 for (
unsigned I = 0;
I != MaskLen; ++
I) {
2638 if (DemandedElts[FirstElt +
I])
2639 InsertMask[FirstElt +
I] =
I;
2651 SimplifyAndSetOp)
const {
2652 switch (
II.getIntrinsicID()) {
2653 case Intrinsic::amdgcn_readfirstlane:
2654 SimplifyAndSetOp(&
II, 0, DemandedElts, UndefElts);
2659 BufInfo && (BufInfo->Kind == AMDGPU::BufferKindLoad ||
2660 BufInfo->Kind == AMDGPU::BufferKindSLoad))
2662 if (getAMDGPUImageDMaskIntrinsic(
II.getIntrinsicID()))
2666 return std::nullopt;
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static Value * createPermlane16(IRBuilderBase &B, Value *Val, uint32_t Lo, uint32_t Hi)
Emit v_permlane16 with the precomputed lane-select halves.
static std::optional< unsigned > matchRowSharePattern(ArrayRef< uint8_t > Ids)
Match a row-share pattern: all 16 lanes of each row read the same source lane.
static bool matchMirrorPattern(ArrayRef< uint8_t > Ids)
Match an N-lane reversal (mirror) pattern.
static bool canSafelyConvertTo16Bit(Value &V, bool IsFloat, bool AllowI16SExt=false)
static bool tryBuildShuffleMap(Value *Index, const GCNSubtarget &ST, SmallVectorImpl< uint8_t > &Ids, const DataLayout &DL)
Build the per-lane shuffle map by evaluating Index for every lane in the wave.
static std::optional< unsigned > matchQuadPermPattern(ArrayRef< uint8_t > Ids)
Match a 4-lane (quad) permutation, encoded as the v_mov_b32_dpp QUAD_PERM control word: bits[1:0]=Ids...
static std::optional< unsigned > matchDsSwizzleRotatePattern(ArrayRef< uint8_t > Ids)
Match a GFX9+ DS_SWIZZLE rotate-mode permutation: a cyclic left-rotation of all 32 lanes within each ...
static std::optional< unsigned > matchHalfRowPermPattern(ArrayRef< uint8_t > Ids)
Match an 8-lane arbitrary permutation, encoded as the v_mov_b32_dpp8 24-bit selector (three bits per ...
static std::optional< unsigned > matchRowXMaskPattern(ArrayRef< uint8_t > Ids)
Match an XOR mask pattern within each 16-lane row: Ids[J] == Mask ^ J, with Mask in [1,...
static constexpr auto matchHalfRowMirrorPattern
static Value * createPermlaneX16(IRBuilderBase &B, Value *Val, uint32_t Lo, uint32_t Hi)
Emit v_permlanex16 with the precomputed lane-select halves.
static bool isRowPattern(ArrayRef< uint8_t > Ids)
Match an N-lane row pattern: each lane in [0, N) reads from a source lane in the same N-lane row,...
static bool canContractSqrtToRsq(const FPMathOperator *SqrtOp)
Return true if it's legal to contract llvm.amdgcn.rcp(llvm.sqrt)
static CallInst * rewriteCall(IRBuilderBase &B, CallInst &Old, Function &NewCallee, ArrayRef< Value * > Ops)
static Value * convertTo16Bit(Value &V, InstCombiner::BuilderTy &Builder)
static constexpr auto isFullRowPattern
static constexpr auto isQuadPattern
static APInt trimTrailingZerosInVector(InstCombiner &IC, Value *UseV, Instruction *I)
static uint64_t computePermlane16Masks(ArrayRef< uint8_t > Ids)
Pack a 16-lane permutation into a single 64-bit value: four bits per output lane, lane J in bits [J*4...
static bool matchHalfWaveSwapPattern(ArrayRef< uint8_t > Ids)
Match a half-wave swap: lane J reads from lane J ^ 32.
static bool hasPeriodicLayout(ArrayRef< uint8_t > Ids)
Lanes are partitioned into groups of Period; each group is a translated copy of the first: Ids[I] = I...
static std::optional< uint64_t > evalLaneExpr(Value *V, unsigned Lane, const GCNSubtarget &ST, const DataLayout &DL, unsigned Depth=0)
Evaluate V as a function of the lane ID and return its value on Lane, or std::nullopt if V is not a c...
static std::optional< Instruction * > tryOptimizeShufflePattern(InstCombiner &IC, IntrinsicInst &II, const GCNSubtarget &ST)
Try to fold a wave_shuffle/ds_bpermute whose lane index is a constant function of the lane ID into a ...
static constexpr auto isHalfRowPattern
static APInt defaultComponentBroadcast(Value *V)
static std::optional< unsigned > matchDsSwizzleBitmaskPattern(ArrayRef< uint8_t > Ids)
Match a DS_SWIZZLE bitmask-mode permutation: dst_lane = ((src_lane & AND) | OR) ^ XOR with each mask ...
static Value * createDsSwizzle(IRBuilderBase &B, Value *Val, unsigned Offset, const DataLayout &DL)
Emit ds_swizzle with the given immediate, bitcasting/converting between pointer/float types and i32 a...
static std::optional< Instruction * > modifyIntrinsicCall(IntrinsicInst &OldIntr, Instruction &InstToReplace, unsigned NewIntr, InstCombiner &IC, std::function< void(SmallVectorImpl< Value * > &, SmallVectorImpl< Type * > &)> Func)
Applies Func(OldIntr.Args, OldIntr.ArgTys), creates intrinsic call with modified arguments (based on ...
static Value * matchShuffleToHWIntrinsic(IRBuilderBase &B, Value *Src, ArrayRef< uint8_t > Ids, const GCNSubtarget &ST, const DataLayout &DL)
Given a shuffle map, try to emit the best hardware intrinsic.
static std::optional< unsigned > matchRowRotatePattern(ArrayRef< uint8_t > Ids)
Match a 16-lane cyclic rotation; returns the rotation amount in [1, 15].
static bool isCrossRowPattern(ArrayRef< uint8_t > Ids)
Match a cross-row permutation suitable for v_permlanex16: every lane in the low 16-lane half reads fr...
static bool isThreadID(const GCNSubtarget &ST, Value *V)
static Value * createUpdateDpp(IRBuilderBase &B, Value *Val, unsigned Ctrl)
Emit v_mov_b32_dpp with the given control word, row/bank masks 0xF, and bound_ctrl=1 so out-of-bounds...
static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1, const APFloat &Src2)
static std::optional< Instruction * > simplifyAMDGCNImageIntrinsic(const GCNSubtarget *ST, const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr, IntrinsicInst &II, InstCombiner &IC)
static Value * createMovDpp8(IRBuilderBase &B, Value *Val, unsigned Selector)
Emit v_mov_b32_dpp8 with the given 24-bit lane selector.
static Instruction * foldAddIntoDotAccumulator(IntrinsicInst &II, unsigned AccIdx, unsigned ClampIdx, InstCombiner &IC)
Try to fold an addition into the accumulator when saturation is disabled.
static Value * matchFPExtFromF16(Value *Arg)
Match an fpext from half to float, or a constant we can convert.
static constexpr auto matchFullRowMirrorPattern
static bool simplifyExponentOnlyScaleArg(InstCombiner &IC, IntrinsicInst &II, unsigned ScaleArgIdx)
Simplify the f32 scale operand of a V_CVT_SCALEF32_* conversion, of which only the exponent field is ...
static Value * createPermlane64(IRBuilderBase &B, Value *Val)
Emit v_permlane64 (swap of the two 32-lane halves of a wave64).
Contains the definition of a TargetInstrInfo class that is common to all AMD GPUs.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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...
Utilities for dealing with flags related to floating point properties and mode controls.
AMD GCN specific subclass of TargetSubtarget.
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
uint64_t IntrinsicInst * II
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
static ClusterDimsAttr get(const Function &F)
const std::array< unsigned, 3 > & getDims() const
static constexpr roundingMode rmTowardZero
static constexpr roundingMode rmNearestTiesToEven
static constexpr const fltSemantics & IEEEhalf()
static constexpr const fltSemantics & IEEEsingle()
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
bool bitwiseIsEqual(const APFloat &RHS) const
bool isPosInfinity() const
APFloat makeQuiet() const
Assuming this is an IEEE-754 NaN value, quiet its signaling bit.
APInt bitcastToAPInt() const
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Class for arbitrary precision integers.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
void clearBit(unsigned BitPosition)
Set a given bit to 0.
unsigned popcount() const
Count the number of bits set.
LLVM_ABI uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const
unsigned getActiveBits() const
Compute the number of active bits in the value.
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
unsigned countr_zero() const
Count the number of trailing zero bits.
bool isMask(unsigned numBits) const
Represent a constant reference to an array (0 or more elements consecutively in memory),...
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
size_t size() const
Get the array size.
static LLVM_ABI Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
bool isTypeLegal(Type *Ty) const override
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
void removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Removes the attribute from the given argument.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
void setAttributes(AttributeList A)
Set the attributes for this call.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
AttributeList getAttributes() const
Return the attributes for this call.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
ConstantFP - Floating Point Values [float, double].
const APFloat & getValueAPF() const
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
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.
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
This is an important base class in LLVM.
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.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
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.
Tagged union holding either a T or a Error.
This class represents an extension of floating point types.
Utility class for floating point operations which can have information about relaxed accuracy require...
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
bool hasApproxFunc() const
Test if this operation allows approximations of math library functions or intrinsics.
LLVM_ABI float getFPAccuracy() const
Get the maximum error permitted by this operation in ULPs.
Convenience struct for specifying and reasoning about fast-math flags.
bool allowContract() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
bool simplifyDemandedLaneMaskArg(InstCombiner &IC, IntrinsicInst &II, unsigned LaneAgIdx) const
Simplify a lane index operand (e.g.
std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const override
Instruction * hoistLaneIntrinsicThroughOperand(InstCombiner &IC, IntrinsicInst &II) const
Value * simplifyAMDGCNMemoryIntrinsicDemanded(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts) const
Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics.
std::optional< Value * > simplifyDemandedVectorEltsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp) const override
KnownIEEEMode fpenvIEEEMode(const Instruction &I) const
Return KnownIEEEMode::On if we know if the use context can assume "amdgpu-ieee"="true" and KnownIEEEM...
Value * simplifyAMDGCNLaneIntrinsicDemanded(InstCombiner &IC, IntrinsicInst &II, const APInt &DemandedElts, APInt &UndefElts) const
bool canSimplifyLegacyMulToMul(const Instruction &I, const Value *Op0, const Value *Op1, InstCombiner &IC) const
Common base class shared among various IRBuilders.
ConstantInt * getInt1(bool V)
Get a constant value representing either true or false.
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Value * CreateExtractVector(Type *DstType, Value *SrcVec, Value *Idx, const Twine &Name="")
Create a call to the vector.extract intrinsic.
Module * getModule() const
Get the module.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Value * CreateMaxNum(Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create call to the maxnum intrinsic.
Value * CreateShl(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.
Value * CreateMaximumNum(Value *LHS, Value *RHS, const Twine &Name="")
Create call to the maximum intrinsic.
Value * CreateMinNum(Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create call to the minnum intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Value * CreateFAddFMF(Value *L, Value *R, FMFSource FMFSource, const Twine &Name="", MDNode *FPMD=nullptr)
Value * CreateMinimumNum(Value *LHS, Value *RHS, const Twine &Name="")
Create call to the minimumnum intrinsic.
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Value * CreateFMulFMF(Value *L, Value *R, FMFSource FMFSource, const Twine &Name="", MDNode *FPMD=nullptr)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
The core instruction combiner logic.
const DataLayout & getDataLayout() const
virtual Instruction * eraseInstFromFunction(Instruction &I)=0
Combiner aware instruction erasure.
DominatorTree & getDominatorTree() const
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
virtual bool SimplifyDemandedBits(Instruction *I, unsigned OpNo, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)=0
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
static Value * stripSignOnlyFPOps(Value *Val)
Ignore all operations which only change the sign of a value, returning the underlying magnitude value...
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
const SimplifyQuery & getSimplifyQuery() const
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction,...
void dropPoisonGeneratingAnnotations()
Drops flags, attributes and metadata that may generate poison.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Class to represent integer types.
A wrapper class for inspecting calls to intrinsic functions.
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
A Module instance is used to store all the information related to an LLVM module.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isPointerTy() const
True if this is an instance of PointerType.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVM_ABI Type * getWithNewType(Type *EltTy) const
Given vector type, change the element type, whilst keeping the old number of elements.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntegerTy() const
True if this is an instance of IntegerType.
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
bool isVoidTy() const
Return true if this is 'void'.
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.
const Use & getOperandUse(unsigned i) const
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
constexpr ScalarTy getFixedValue() const
const ParentTy * getParent() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
APInt getExponentOnlyScaleDemandedBits()
LLVM_READONLY const MIMGOffsetMappingInfo * getMIMGOffsetMappingInfo(unsigned Offset)
uint8_t wmmaScaleF8F6F4FormatToNumRegs(unsigned Fmt)
const ImageDimIntrinsicInfo * getImageDimIntrinsicByBaseOpcode(unsigned BaseOpcode, unsigned Dim)
std::optional< unsigned > getExponentOnlyScaleArgIdx(unsigned IntrID)
LLVM_READONLY const MIMGMIPMappingInfo * getMIMGMIPMappingInfo(unsigned MIP)
bool isTriviallyUniform(const Value *V, const Instruction *CtxI)
Return true if we can easily prove that V is uniform at CtxI.
const BufferIntrinsicInfo * lookupBufferIntrinsic(unsigned Intr)
LLVM_READONLY const MIMGBiasMappingInfo * getMIMGBiasMappingInfo(unsigned Bias)
std::optional< APFloat > evaluateRcp(const APFloat &Val)
Evaluate the constant-folded result of v_rcp for Val, accounting for the hardware's denormal flushing...
LLVM_READONLY const MIMGLZMappingInfo * getMIMGLZMappingInfo(unsigned L)
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfo(unsigned DimEnum)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
const ImageDimIntrinsicInfo * getImageDimIntrinsicInfo(unsigned Intr)
const RsrcIntrinsic * lookupRsrcIntrinsic(unsigned Intr)
const GcnBufferFormatInfo * getGcnBufferFormatInfo(uint8_t BitsPerComp, uint8_t NumComponents, uint8_t NumFormat, const MCSubtargetInfo &STI)
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
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.
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.
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_Value()
Match an arbitrary value and ignore it.
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_ConstantFP()
Match an arbitrary ConstantFP and ignore it.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
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.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
@ 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,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
constexpr bool isMask_32(uint32_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
auto dyn_cast_or_null(const Y &Val)
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
constexpr unsigned MaxAnalysisRecursionDepth
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
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...
constexpr int PoisonMaskElem
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
@ NearestTiesToEven
roundTiesToEven.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
constexpr uint64_t Make_64(uint32_t High, uint32_t Low)
Make a 64-bit integer from a high / low pair of 32-bit integers.
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.
The argument layout of a buffer intrinsic.
bool isFormatFromRsrc() const
Whether the data is converted according to the format in the resource.
unsigned getOffsetArg() const
The main offset: the voffset if there is one, and the soffset otherwise.
std::optional< unsigned > getFormatArg() const
Represent subnormal handling kind for floating point instruction inputs and outputs.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
SimplifyQuery getWithInstruction(const Instruction *I) const
LLVM_ABI bool isUndefValue(Value *V) const
If CanUseUndef is true, returns whether V is undef.