25#include "llvm/IR/IntrinsicsDirectX.h"
35#define DEBUG_TYPE "dxil-op-lower"
59 : M(M), OpBuilder(M), DRM(DRM), DRTM(DRTM), MMDI(MMDI) {}
71 if (
Error E = ReplaceCall(CI)) {
72 std::string Message(
toString(std::move(
E)));
84 struct IntrinArgSelect {
86#define DXIL_OP_INTRINSIC_ARG_SELECT_TYPE(name) name,
87#include "DXILOperation.inc"
97 Error replaceNamedStructUses(CallInst *Intrin, CallInst *DXILOp) {
100 if (!IntrinTy->isLayoutIdentical(DXILOpTy))
102 "Type mismatch between intrinsic and DXIL op",
107 EVI->setOperand(0, DXILOp);
109 IVI->setOperand(0, DXILOp);
112 "be used by insert- and extractvalue",
117 void setDxPrecise(CallInst *CI) {
118 const StringRef
Key =
"dx.precise";
132 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
133 OpBuilder.getIRB().SetInsertPoint(CI);
135 if (ArgSelects.
size()) {
136 for (
const IntrinArgSelect &
A : ArgSelects) {
138 case IntrinArgSelect::Type::Index:
141 case IntrinArgSelect::Type::I8:
142 Args.push_back(OpBuilder.getIRB().getInt8((uint8_t)
A.Value));
144 case IntrinArgSelect::Type::I32:
145 Args.push_back(OpBuilder.getIRB().getInt32(
A.Value));
153 Expected<CallInst *> OpCall =
154 OpBuilder.tryCreateOp(DXILOp, Args, CI->
getName(),
F.getReturnType());
159 setDxPrecise(*OpCall);
162 if (
Error E = replaceNamedStructUses(CI, *OpCall))
178 CallInst *Cast = OpBuilder.getIRB().CreateIntrinsicWithoutFolding(
179 Intrinsic::dx_resource_casthandle, {Ty,
V->getType()}, {
V});
180 CleanupCasts.push_back(Cast);
184 void cleanupHandleCasts() {
188 for (CallInst *Cast : CleanupCasts) {
197 if (Cast->
getType() != OpBuilder.getHandleType()) {
204 assert(
Def->getIntrinsicID() == Intrinsic::dx_resource_casthandle &&
205 "Unbalanced pair of temporary handle casts");
218 F->eraseFromParent();
220 CleanupCasts.clear();
223 void cleanupNonUniformResourceIndexCalls() {
234 CleanupNURI->eraseFromParent();
235 CleanupNURI =
nullptr;
243 void removeResourceGlobals(CallInst *CI) {
247 Store->eraseFromParent();
249 if (GV->use_empty()) {
250 GV->removeDeadConstantUsers();
251 GV->eraseFromParent();
257 void replaceHandleFromBindingCall(CallInst *CI,
Value *Replacement) {
259 Intrinsic::dx_resource_handlefrombinding);
261 removeResourceGlobals(CI);
268 if (NameGlobal && NameGlobal->use_empty())
269 NameGlobal->eraseFromParent();
272 bool hasNonUniformIndex(
Value *IndexOp) {
276 SmallVector<Value *, 16> Worklist;
277 SmallPtrSet<Value *, 16> Visited;
280 while (!Worklist.
empty()) {
290 if (CI->
getIntrinsicID() == Intrinsic::dx_resource_nonuniformindex)
296 for (
Value *Incoming :
Phi->incoming_values())
302 if (Inst->getNumOperands() > 0 && !Inst->isTerminator())
303 for (
Value *
Op : Inst->operands())
309 Error validateRawBufferElementIndex(
Value *Resource,
Value *ElementIndex) {
314 if (IsStructured && IsPoison)
316 "Element index of structured buffer may not be poison",
319 if (!IsStructured && !IsPoison)
321 "Element index of raw buffer must be poison",
327 [[nodiscard]]
bool lowerToCreateHandle(
Function &
F) {
333 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
336 auto *It = DRM.find(CI);
337 assert(It != DRM.end() &&
"Resource not in map?");
338 dxil::ResourceInfo &RI = *It;
346 ConstantInt::get(Int32Ty,
Binding.LowerBound));
348 bool HasNonUniformIndex =
349 (
Binding.Size == 1) ?
false : hasNonUniformIndex(IndexOp);
350 std::array<Value *, 4>
Args{
352 ConstantInt::get(Int32Ty,
Binding.BindingID), IndexOp,
353 ConstantInt::get(Int1Ty, HasNonUniformIndex)};
354 Expected<CallInst *> OpCall =
355 OpBuilder.tryCreateOp(OpCode::CreateHandle, Args, CI->
getName());
359 Value *Cast = createTmpHandleCast(*OpCall, CI->
getType());
360 replaceHandleFromBindingCall(CI, Cast);
365 [[nodiscard]]
bool lowerToBindAndAnnotateHandle(
Function &
F) {
370 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
373 auto *It = DRM.find(CI);
374 assert(It != DRM.end() &&
"Resource not in map?");
375 dxil::ResourceInfo &RI = *It;
378 dxil::ResourceTypeInfo &RTI = DRTM[RI.
getHandleTy()];
384 ConstantInt::get(Int32Ty,
Binding.LowerBound));
386 std::pair<uint32_t, uint32_t> Props =
391 uint32_t UpperBound =
Binding.Size == 0
392 ? std::numeric_limits<uint32_t>::max()
394 Constant *ResBind = OpBuilder.getResBind(
Binding.LowerBound, UpperBound,
396 bool NonUniformIndex =
397 (
Binding.Size == 1) ?
false : hasNonUniformIndex(IndexOp);
398 Constant *NonUniformOp = ConstantInt::get(Int1Ty, NonUniformIndex);
399 std::array<Value *, 3> BindArgs{ResBind, IndexOp, NonUniformOp};
400 Expected<CallInst *> OpBind = OpBuilder.tryCreateOp(
401 OpCode::CreateHandleFromBinding, BindArgs, CI->
getName());
405 std::array<Value *, 2> AnnotateArgs{
406 *OpBind, OpBuilder.getResProps(Props.first, Props.second)};
407 Expected<CallInst *> OpAnnotate = OpBuilder.tryCreateOp(
408 OpCode::AnnotateHandle, AnnotateArgs,
413 Value *Cast = createTmpHandleCast(*OpAnnotate, CI->
getType());
414 replaceHandleFromBindingCall(CI, Cast);
422 bool lowerHandleFromBinding(
Function &
F) {
423 if (MMDI.DXILVersion < VersionTuple(1, 6))
424 return lowerToCreateHandle(
F);
425 return lowerToBindAndAnnotateHandle(
F);
431 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
434 auto *It = DRM.find(CI);
435 assert(It != DRM.end() &&
"Resource not in map?");
436 dxil::ResourceInfo &RI = *It;
437 dxil::ResourceTypeInfo &RTI = DRTM[RI.
getHandleTy()];
440 Value *IsSamplerHeap =
443 std::pair<uint32_t, uint32_t> Props =
446 bool NonUniformIndex = hasNonUniformIndex(IndexOp);
447 Value *NonUniformOp =
450 std::array<Value *, 3>
Args{IndexOp, IsSamplerHeap, NonUniformOp};
451 Expected<CallInst *> OpCreateHandle = OpBuilder.tryCreateOp(
452 OpCode::CreateHandleFromHeap, Args, CI->
getName());
456 std::array<Value *, 2> AnnotateArgs{
457 *OpCreateHandle, OpBuilder.getResProps(Props.first, Props.second)};
458 Expected<CallInst *> OpAnnotate = OpBuilder.tryCreateOp(
459 OpCode::AnnotateHandle, AnnotateArgs,
464 Value *Cast = createTmpHandleCast(*OpAnnotate, CI->
getType());
473 Error replaceResRetUses(CallInst *Intrin, CallInst *
Op,
bool HasCheckBit) {
482 Value *CheckOp =
nullptr;
486 ArrayRef<unsigned> Indices = EVI->getIndices();
493 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
494 OpCode::CheckAccessFullyMapped, {NewEVI},
502 EVI->replaceAllUsesWith(CheckOp);
503 EVI->eraseFromParent();
515 "Expected only use to be extract of first element");
517 OldTy =
ST->getElementType(0);
525 if (OldResult != Intrin) {
532 std::array<Value *, 4> Extracts = {};
540 size_t IndexVal = IndexOp->getZExtValue();
541 assert(IndexVal < 4 &&
"Index into buffer load out of range");
542 if (!Extracts[IndexVal])
545 EEI->eraseFromParent();
553 const unsigned N = VecTy->getNumElements();
557 if (!DynamicAccesses.
empty()) {
561 Type *ElTy = VecTy->getElementType();
562 Type *ArrayTy = ArrayType::get(ElTy,
N);
565 for (
int I = 0,
E =
N;
I !=
E; ++
I) {
569 ArrayTy, Alloca, {
Zero, ConstantInt::get(Int32Ty,
I)},
"",
574 for (ExtractElementInst *EEI : DynamicAccesses) {
576 ArrayTy, Alloca, {
Zero, EEI->getIndexOperand()},
"",
580 EEI->eraseFromParent();
588 for (
int I = 0,
E =
N;
I !=
E; ++
I)
593 for (
int I = 0,
E =
N;
I !=
E; ++
I)
599 if (OldResult != Intrin) {
607 [[nodiscard]]
bool lowerTypedBufferLoad(
Function &
F,
bool HasCheckBit) {
611 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
615 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
624 std::array<Value *, 3>
Args{Handle, Index0, Index1};
625 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
626 OpCode::BufferLoad, Args, CI->
getName(), NewRetTy);
629 if (
Error E = replaceResRetUses(CI, *OpCall, HasCheckBit))
641 static void collectInsertedElements(
Value *Vec,
644 assert(NumElts <=
Elements.size() &&
"Not enough room for the components");
652 Base = IEI->getOperand(0);
656 for (
unsigned I = 0;
I < NumElts; ++
I)
657 Elements[
I] =
C->getAggregateElement(
I);
661 while (!Chain.
empty()) {
664 if (IndexVal < NumElts)
672 static void extractElementsIntoArgs(
IRBuilder<> &IRB,
674 unsigned ArgIdx,
Value *Src,
675 unsigned MaxElements) {
682 unsigned Count = VecTy->getNumElements();
683 assert(
Count <= MaxElements &&
"Too many elements for the arg list");
686 collectInsertedElements(Src, Elements);
688 for (
unsigned I = 0;
I <
Count; ++
I)
689 Args[ArgIdx +
I] = Elements[
I]
691 : IRB.CreateExtractElement(
692 Src, ConstantInt::
get(IRB.getInt32Ty(),
I));
697 static void extractNonZeroOffsets(
IRBuilder<> &IRB,
699 unsigned ArgIdx,
Value *Offsets,
700 unsigned MaxElements) {
702 bool OffsetsAreZero = COff && COff->isNullValue();
704 extractElementsIntoArgs(IRB, Args, ArgIdx, Offsets, MaxElements);
707 [[nodiscard]]
bool lowerTextureLoad(
Function &
F) {
711 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
716 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
725 dxil::ResourceTypeInfo &RTI = DRTM[HandleTy];
727 if (RTI.
isUAV() && Kind != dxil::ResourceKind::Texture2DMS &&
728 Kind != dxil::ResourceKind::Texture2DMSArray)
739 extractElementsIntoArgs(IRB, Args, 2, Coords, 3);
740 extractNonZeroOffsets(IRB, Args, 5, Offsets, 3);
742 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
743 OpCode::TextureLoad, Args, CI->
getName(), NewRetTy);
746 if (
Error E = replaceResRetUses(CI, *OpCall,
false))
749 eraseDeadInsertElementChains(VectorArgs);
758 [[nodiscard]]
bool lowerSampleOp(
761 SmallVectorImpl<Value *> &)> EmitExtraArgs) {
763 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
768 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
770 createTmpHandleCast(CI->
getArgOperand(1), OpBuilder.getHandleType());
781 UndefF, UndefI, UndefI, UndefI};
784 extractElementsIntoArgs(IRB, Args, 2, Coords, 4);
785 extractNonZeroOffsets(IRB, Args, 6, Offsets, 3);
788 EmitExtraArgs(IRB, CI, Args);
790 Expected<CallInst *> OpCall =
791 OpBuilder.tryCreateOp(
Op, Args, CI->
getName(), NewRetTy);
794 if (
Error E = replaceResRetUses(CI, *OpCall,
false))
797 eraseDeadInsertElementChains(VectorArgs);
803 [[nodiscard]]
bool lowerSample(
Function &
F,
bool HasClamp) {
804 return lowerSampleOp(
F, OpCode::Sample, 2, 3,
806 SmallVectorImpl<Value *> &Args) {
814 [[nodiscard]]
bool lowerSampleBias(
Function &
F,
bool HasClamp) {
815 return lowerSampleOp(
816 F, OpCode::SampleBias, 2, 4,
818 SmallVectorImpl<Value *> &Args) {
827 [[nodiscard]]
bool lowerSampleLevel(
Function &
F) {
828 return lowerSampleOp(
829 F, OpCode::SampleLevel, 2, 4,
830 [](
IRBuilder<> &, CallInst *CI, SmallVectorImpl<Value *> &Args) {
836 [[nodiscard]]
bool lowerSampleGrad(
Function &
F,
bool HasClamp) {
837 return lowerSampleOp(
838 F, OpCode::SampleGrad, 2, 5,
840 SmallVectorImpl<Value *> &Args) {
845 size_t DDXStart =
Args.size();
846 Args.append(3, UndefF);
847 extractElementsIntoArgs(IRB, Args, DDXStart, DDX, 3);
849 size_t DDYStart =
Args.size();
850 Args.append(3, UndefF);
851 extractElementsIntoArgs(IRB, Args, DDYStart, DDY, 3);
857 [[nodiscard]]
bool lowerRawBufferLoad(
Function &
F) {
858 const DataLayout &
DL =
F.getDataLayout();
863 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
868 Type *NewRetTy = OpBuilder.getResRetType(ScalarTy);
871 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
875 DL.getTypeSizeInBits(OldTy) /
DL.getTypeSizeInBits(ScalarTy);
876 Value *
Mask = ConstantInt::get(Int8Ty, ~(~0U << NumElements));
878 ConstantInt::get(Int32Ty,
DL.getPrefTypeAlign(ScalarTy).value());
885 Expected<CallInst *> OpCall =
886 MMDI.DXILVersion >= VersionTuple(1, 2)
887 ? OpBuilder.tryCreateOp(OpCode::RawBufferLoad,
890 : OpBuilder.tryCreateOp(OpCode::BufferLoad,
891 {Handle, Index0, Index1}, CI->
getName(),
895 if (
Error E = replaceResRetUses(CI, *OpCall,
true))
902 [[nodiscard]]
bool lowerCBufferLoad(
Function &
F) {
905 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
910 Type *NewRetTy = OpBuilder.getCBufRetType(ScalarTy);
913 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
916 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
917 OpCode::CBufferLoadLegacy, {Handle,
Index}, CI->
getName(), NewRetTy);
920 if (
Error E = replaceNamedStructUses(CI, *OpCall))
928 [[nodiscard]]
bool lowerUpdateCounter(
Function &
F) {
932 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
935 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
938 std::array<Value *, 2>
Args{Handle, Op1};
940 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
941 OpCode::UpdateCounter, Args, CI->
getName(), Int32Ty);
952 [[nodiscard]]
bool lowerBarrierByMemoryHandle(
Function &
F) {
955 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
958 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
961 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
962 OpCode::BarrierByMemoryHandle, {Handle, SemanticFlags});
971 [[nodiscard]]
bool lowerGetDimensionsX(
Function &
F) {
975 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
978 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
981 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
982 OpCode::GetDimensions, {Handle,
Undef}, CI->
getName(), Int32Ty);
993 [[nodiscard]]
bool lowerGetPointer(
Function &
F) {
996 assert(
F.user_empty() &&
"getpointer operations should have been removed");
1008 bool FillWithUndef) {
1009 std::array<Value *, 4> DataElements{
nullptr,
nullptr,
nullptr,
nullptr};
1010 extractElementsIntoArgs(IRB, DataElements, 0,
Data, 4);
1016 if (DataElements[
I] ==
nullptr)
1021 return DataElements;
1026 static void eraseDeadInsertElementChain(
Value *
Data) {
1029 InsertElementInst *Tmp = IEI;
1035 [[nodiscard]]
bool lowerBufferStore(
Function &
F,
bool IsRaw) {
1036 const DataLayout &
DL =
F.getDataLayout();
1041 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
1045 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
1061 DL.getTypeSizeInBits(DataTy) /
DL.getTypeSizeInBits(ScalarTy);
1062 Value *
Mask = ConstantInt::get(Int8Ty, IsRaw ? ~(~0U << NumElements)
1066 if (NumElements > 4)
1068 "Buffer store data must have at most 4 elements",
1071 std::array<Value *, 4> DataElements =
1072 splitStoreData(IRB,
Data, NumElements, IsRaw);
1076 Handle, Index0, Index1, DataElements[0],
1077 DataElements[1], DataElements[2], DataElements[3],
Mask};
1078 if (IsRaw && MMDI.DXILVersion >= VersionTuple(1, 2)) {
1079 Op = OpCode::RawBufferStore;
1082 ConstantInt::get(Int32Ty,
DL.getPrefTypeAlign(ScalarTy).value()));
1084 Expected<CallInst *> OpCall =
1085 OpBuilder.tryCreateOp(
Op, Args, CI->
getName());
1090 eraseDeadInsertElementChain(
Data);
1108 for (
const WeakTrackingVH &VH : Vectors)
1110 eraseDeadInsertElementChain(
V);
1113 [[nodiscard]]
bool lowerTextureStore(
Function &
F) {
1114 const DataLayout &
DL =
F.getDataLayout();
1119 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
1124 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
1131 DL.getTypeSizeInBits(DataTy) /
DL.getTypeSizeInBits(ScalarTy);
1132 if (NumElements > 4)
1134 "Texture store data must have at most 4 elements",
1138 std::array<Value *, 4> DataElements =
1139 splitStoreData(IRB,
Data, NumElements,
false);
1142 std::array<Value *, 9>
Args{
1144 Undef, DataElements[0], DataElements[1],
1145 DataElements[2], DataElements[3],
Mask};
1148 extractElementsIntoArgs(IRB, Args, 1, Coords, 3);
1150 Expected<CallInst *> OpCall =
1151 OpBuilder.tryCreateOp(OpCode::TextureStore, Args, CI->
getName());
1156 eraseDeadInsertElementChains(VectorArgs);
1162 [[nodiscard]]
bool lowerResourceAtomicBinOp(
Function &
F) {
1165 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
1171 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
1178 std::array<Value *, 6>
Args{Handle, BinOp, Coord0,
1179 Coord1, Coord2, NewValue};
1180 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
1185 std::string Message(
toString(std::move(
E)));
1199 [[nodiscard]]
bool lowerResourceAtomicCompareExchange(
Function &
F) {
1202 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
1208 createTmpHandleCast(CI->
getArgOperand(0), OpBuilder.getHandleType());
1215 std::array<Value *, 6>
Args{Handle, Coord0, Coord1,
1216 Coord2, CompareValue, NewValue};
1217 Expected<CallInst *> OpCall =
1218 OpBuilder.tryCreateOp(dxil::OpCode::AtomicCompareExchange, Args,
1223 std::string Message(
toString(std::move(
E)));
1237 [[nodiscard]]
bool lowerCtpopToCountBits(
Function &
F) {
1241 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
1246 Type *RetTy = Int32Ty;
1247 Type *FRT =
F.getReturnType();
1249 RetTy = VectorType::get(RetTy, VT);
1251 Expected<CallInst *> OpCall = OpBuilder.tryCreateOp(
1252 dxil::OpCode::CountBits, Args, CI->
getName(), RetTy);
1266 CastOp = Instruction::ZExt;
1267 CastOp2 = Instruction::SExt;
1270 "Currently only lowering 16, 32, or 64 bit ctpop to CountBits \
1272 CastOp = Instruction::Trunc;
1273 CastOp2 = Instruction::Trunc;
1278 bool NeedsCast =
false;
1280 if ((
I->getOpcode() == CastOp ||
I->getOpcode() == CastOp2) &&
1281 I->getType() == RetTy) {
1282 I->replaceAllUsesWith(*OpCall);
1283 I->eraseFromParent();
1303 [[nodiscard]]
bool lowerLifetimeIntrinsic(
Function &
F) {
1305 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
1309 "Expected operand of lifetime intrinsic to be a pointer");
1311 auto ZeroOrUndef = [&](
Type *Ty) {
1312 return MMDI.ValidatorVersion < VersionTuple(1, 6)
1314 : UndefValue::
get(Ty);
1317 Value *Val =
nullptr;
1319 if (GV->hasInitializer() || GV->isExternallyInitialized())
1321 Val = ZeroOrUndef(GV->getValueType());
1323 Val = ZeroOrUndef(AI->getAllocatedType());
1325 assert(Val &&
"Expected operand of lifetime intrinsic to be a global "
1326 "variable or alloca instruction");
1334 [[nodiscard]]
bool lowerIsFPClass(
Function &
F) {
1338 return replaceFunction(
F, [&](CallInst *CI) ->
Error {
1347 switch (TCI->getZExtValue()) {
1348 case FPClassTest::fcInf:
1349 OpCode = dxil::OpCode::IsInf;
1351 case FPClassTest::fcNan:
1352 OpCode = dxil::OpCode::IsNaN;
1354 case FPClassTest::fcNormal:
1355 OpCode = dxil::OpCode::IsNormal;
1357 case FPClassTest::fcFinite:
1358 OpCode = dxil::OpCode::IsFinite;
1361 SmallString<128>
Msg =
1362 formatv(
"Unsupported FPClassTest {0} for DXIL Op Lowering",
1363 TCI->getZExtValue());
1367 Expected<CallInst *> OpCall =
1378 bool lowerIntrinsics() {
1379 bool Updated =
false;
1380 bool HasErrors =
false;
1383 if (!
F.isDeclaration())
1389 case Intrinsic::dx_resource_casthandle:
1391 case Intrinsic::dbg_value:
1394 F.eraseFromParent();
1398 F.eraseFromParent();
1401 "Unsupported intrinsic {0} for DXIL lowering",
F.getName());
1402 M.getContext().emitError(
Msg);
1407#define DXIL_OP_INTRINSIC(OpCode, Intrin, ...) \
1409 HasErrors |= replaceFunctionWithOp( \
1410 F, OpCode, ArrayRef<IntrinArgSelect>{__VA_ARGS__}); \
1412#include "DXILOperation.inc"
1413 case Intrinsic::dx_resource_handlefrombinding:
1414 HasErrors |= lowerHandleFromBinding(
F);
1416 case Intrinsic::dx_resource_handlefromheap:
1417 HasErrors |= lowerHandleFromHeap(
F);
1419 case Intrinsic::dx_resource_getbasepointer:
1420 case Intrinsic::dx_resource_getpointer:
1421 HasErrors |= lowerGetPointer(
F);
1423 case Intrinsic::dx_resource_nonuniformindex:
1425 "overloaded llvm.dx.resource.nonuniformindex intrinsics?");
1428 case Intrinsic::dx_resource_load_typedbuffer:
1429 HasErrors |= lowerTypedBufferLoad(
F,
true);
1431 case Intrinsic::dx_resource_load_level:
1432 HasErrors |= lowerTextureLoad(
F);
1434 case Intrinsic::dx_resource_sample:
1435 HasErrors |= lowerSample(
F,
false);
1437 case Intrinsic::dx_resource_sample_clamp:
1438 HasErrors |= lowerSample(
F,
true);
1440 case Intrinsic::dx_resource_samplebias:
1441 HasErrors |= lowerSampleBias(
F,
false);
1443 case Intrinsic::dx_resource_samplebias_clamp:
1444 HasErrors |= lowerSampleBias(
F,
true);
1446 case Intrinsic::dx_resource_samplelevel:
1447 HasErrors |= lowerSampleLevel(
F);
1449 case Intrinsic::dx_resource_samplegrad:
1450 HasErrors |= lowerSampleGrad(
F,
false);
1452 case Intrinsic::dx_resource_samplegrad_clamp:
1453 HasErrors |= lowerSampleGrad(
F,
true);
1455 case Intrinsic::dx_resource_store_typedbuffer:
1456 HasErrors |= lowerBufferStore(
F,
false);
1458 case Intrinsic::dx_resource_store_texture:
1459 HasErrors |= lowerTextureStore(
F);
1461 case Intrinsic::dx_resource_load_rawbuffer:
1462 HasErrors |= lowerRawBufferLoad(
F);
1464 case Intrinsic::dx_resource_store_rawbuffer:
1465 HasErrors |= lowerBufferStore(
F,
true);
1467 case Intrinsic::dx_resource_load_cbufferrow_2:
1468 case Intrinsic::dx_resource_load_cbufferrow_4:
1469 case Intrinsic::dx_resource_load_cbufferrow_8:
1470 HasErrors |= lowerCBufferLoad(
F);
1472 case Intrinsic::dx_resource_updatecounter:
1473 HasErrors |= lowerUpdateCounter(
F);
1475 case Intrinsic::dx_barrier_by_memory_handle:
1476 HasErrors |= lowerBarrierByMemoryHandle(
F);
1478 case Intrinsic::dx_resource_atomic_binop:
1479 HasErrors |= lowerResourceAtomicBinOp(
F);
1481 case Intrinsic::dx_resource_atomic_compare_exchange:
1482 HasErrors |= lowerResourceAtomicCompareExchange(
F);
1484 case Intrinsic::dx_resource_getdimensions_x:
1485 HasErrors |= lowerGetDimensionsX(
F);
1487 case Intrinsic::ctpop:
1488 HasErrors |= lowerCtpopToCountBits(
F);
1490 case Intrinsic::lifetime_start:
1491 case Intrinsic::lifetime_end:
1493 F.eraseFromParent();
1495 if (MMDI.DXILVersion < VersionTuple(1, 6))
1496 HasErrors |= lowerLifetimeIntrinsic(
F);
1501 case Intrinsic::is_fpclass:
1502 HasErrors |= lowerIsFPClass(
F);
1507 if (Updated && !HasErrors) {
1508 cleanupHandleCasts();
1509 cleanupNonUniformResourceIndexCalls();
1523 const bool MadeChanges = OpLowerer(M, DRM, DRTM, MMDI).lowerIntrinsics();
1536class DXILOpLoweringLegacy :
public ModulePass {
1538 bool runOnModule(
Module &M)
override {
1540 getAnalysis<DXILResourceWrapperPass>().getResourceMap();
1542 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
1544 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
1546 return OpLowerer(M, DRM, DRTM, MMDI).lowerIntrinsics();
1548 StringRef getPassName()
const override {
return "DXIL Op Lowering"; }
1549 DXILOpLoweringLegacy() : ModulePass(
ID) {}
1552 void getAnalysisUsage(llvm::AnalysisUsage &AU)
const override {
1555 AU.
addRequired<DXILMetadataAnalysisWrapperPass>();
1563char DXILOpLoweringLegacy::ID = 0;
1574 return new DXILOpLoweringLegacy();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static constexpr uint8_t TypedUAVStoreWriteMask
Write mask covering all four components of a UAV element.
DXIL Resource Implicit Binding
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
if(!TBB||Cond.size()< 1) return false
ModuleAnalysisManager MAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the SmallVector class.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
size_t size() const
Get the array size.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Diagnostic information for unsupported feature in backend.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Error takeError()
Take ownership of the stored error.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
static GetElementPtrInst * CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
BasicBlock::iterator GetInsertPoint() const
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
LLVMContext & getContext() const
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Type * getFloatTy()
Fetch the type representing a 32-bit floating point value.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
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 InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
LLVMContext & getContext() const
Get the global data context.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
The instances of the Type class are immutable: once they are created, they are never changed.
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.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getOperand(unsigned i) const
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
TargetExtType * getHandleTy() const
LLVM_ABI std::pair< uint32_t, uint32_t > getAnnotateProps(Module &M, dxil::ResourceTypeInfo &RTI) const
const ResourceBinding & getBinding() const
dxil::ResourceClass getResourceClass() const
LLVM_ABI bool isUAV() const
LLVM_ABI bool isSampler() const
dxil::ResourceKind getResourceKind() const
An efficient, type-erasing, non-owning reference to a callable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
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.
ResourceKind
The kind of resource for an SRV or UAV resource.
NodeAddr< DefNode * > Def
NodeAddr< PhiNode * > Phi
NodeAddr< UseNode * > Use
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto unique(Range &&R, Predicate P)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
ModulePass * createDXILOpLoweringLegacyPass()
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.