LLVM 20.0.0git
DXILOpBuilder.cpp
Go to the documentation of this file.
1//===- DXILOpBuilder.cpp - Helper class for build DIXLOp functions --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file This file contains class to help build DXIL op functions.
10//===----------------------------------------------------------------------===//
11
12#include "DXILOpBuilder.h"
13#include "DXILConstants.h"
14#include "llvm/IR/Module.h"
17#include <optional>
18
19using namespace llvm;
20using namespace llvm::dxil;
21
22constexpr StringLiteral DXILOpNamePrefix = "dx.op.";
23
24namespace {
25enum OverloadKind : uint16_t {
26 UNDEFINED = 0,
27 VOID = 1,
28 HALF = 1 << 1,
29 FLOAT = 1 << 2,
30 DOUBLE = 1 << 3,
31 I1 = 1 << 4,
32 I8 = 1 << 5,
33 I16 = 1 << 6,
34 I32 = 1 << 7,
35 I64 = 1 << 8,
36 UserDefineType = 1 << 9,
37 ObjectType = 1 << 10,
38};
39struct Version {
40 unsigned Major = 0;
41 unsigned Minor = 0;
42};
43
44struct OpOverload {
45 Version DXILVersion;
46 uint16_t ValidTys;
47};
48} // namespace
49
50struct OpStage {
51 Version DXILVersion;
53};
54
56 Version DXILVersion;
58};
59
60static const char *getOverloadTypeName(OverloadKind Kind) {
61 switch (Kind) {
62 case OverloadKind::HALF:
63 return "f16";
64 case OverloadKind::FLOAT:
65 return "f32";
66 case OverloadKind::DOUBLE:
67 return "f64";
68 case OverloadKind::I1:
69 return "i1";
70 case OverloadKind::I8:
71 return "i8";
72 case OverloadKind::I16:
73 return "i16";
74 case OverloadKind::I32:
75 return "i32";
76 case OverloadKind::I64:
77 return "i64";
78 case OverloadKind::VOID:
79 case OverloadKind::UNDEFINED:
80 return "void";
81 case OverloadKind::ObjectType:
82 case OverloadKind::UserDefineType:
83 break;
84 }
85 llvm_unreachable("invalid overload type for name");
86}
87
88static OverloadKind getOverloadKind(Type *Ty) {
89 if (!Ty)
90 return OverloadKind::VOID;
91
92 Type::TypeID T = Ty->getTypeID();
93 switch (T) {
94 case Type::VoidTyID:
95 return OverloadKind::VOID;
96 case Type::HalfTyID:
97 return OverloadKind::HALF;
98 case Type::FloatTyID:
99 return OverloadKind::FLOAT;
100 case Type::DoubleTyID:
101 return OverloadKind::DOUBLE;
102 case Type::IntegerTyID: {
103 IntegerType *ITy = cast<IntegerType>(Ty);
104 unsigned Bits = ITy->getBitWidth();
105 switch (Bits) {
106 case 1:
107 return OverloadKind::I1;
108 case 8:
109 return OverloadKind::I8;
110 case 16:
111 return OverloadKind::I16;
112 case 32:
113 return OverloadKind::I32;
114 case 64:
115 return OverloadKind::I64;
116 default:
117 llvm_unreachable("invalid overload type");
118 return OverloadKind::VOID;
119 }
120 }
122 return OverloadKind::UserDefineType;
123 case Type::StructTyID:
124 return OverloadKind::ObjectType;
125 default:
126 llvm_unreachable("invalid overload type");
127 return OverloadKind::VOID;
128 }
129}
130
131static std::string getTypeName(OverloadKind Kind, Type *Ty) {
132 if (Kind < OverloadKind::UserDefineType) {
133 return getOverloadTypeName(Kind);
134 } else if (Kind == OverloadKind::UserDefineType) {
135 StructType *ST = cast<StructType>(Ty);
136 return ST->getStructName().str();
137 } else if (Kind == OverloadKind::ObjectType) {
138 StructType *ST = cast<StructType>(Ty);
139 return ST->getStructName().str();
140 } else {
141 std::string Str;
143 Ty->print(OS);
144 return OS.str();
145 }
146}
147
148// Static properties.
151 // Offset in DXILOpCodeNameTable.
154 // Offset in DXILOpCodeClassNameTable.
159 int OverloadParamIndex; // parameter index which control the overload.
160 // When < 0, should be only 1 overload type.
161};
162
163// Include getOpCodeClassName getOpCodeProperty, getOpCodeName and
164// getOpCodeParameterKind which generated by tableGen.
165#define DXIL_OP_OPERATION_TABLE
166#include "DXILOperation.inc"
167#undef DXIL_OP_OPERATION_TABLE
168
169static std::string constructOverloadName(OverloadKind Kind, Type *Ty,
170 const OpCodeProperty &Prop) {
171 if (Kind == OverloadKind::VOID) {
172 return (Twine(DXILOpNamePrefix) + getOpCodeClassName(Prop)).str();
173 }
174 return (Twine(DXILOpNamePrefix) + getOpCodeClassName(Prop) + "." +
175 getTypeName(Kind, Ty))
176 .str();
177}
178
179static std::string constructOverloadTypeName(OverloadKind Kind,
180 StringRef TypeName) {
181 if (Kind == OverloadKind::VOID)
182 return TypeName.str();
183
184 assert(Kind < OverloadKind::UserDefineType && "invalid overload kind");
185 return (Twine(TypeName) + getOverloadTypeName(Kind)).str();
186}
187
189 ArrayRef<Type *> EltTys,
190 LLVMContext &Ctx) {
192 if (ST)
193 return ST;
194
195 return StructType::create(Ctx, EltTys, Name);
196}
197
198static StructType *getResRetType(Type *OverloadTy, LLVMContext &Ctx) {
199 OverloadKind Kind = getOverloadKind(OverloadTy);
200 std::string TypeName = constructOverloadTypeName(Kind, "dx.types.ResRet.");
201 Type *FieldTypes[5] = {OverloadTy, OverloadTy, OverloadTy, OverloadTy,
202 Type::getInt32Ty(Ctx)};
203 return getOrCreateStructType(TypeName, FieldTypes, Ctx);
204}
205
207 return getOrCreateStructType("dx.types.Handle", PointerType::getUnqual(Ctx),
208 Ctx);
209}
210
212 Type *OverloadTy) {
213 switch (Kind) {
214 case OpParamType::VoidTy:
215 return Type::getVoidTy(Ctx);
216 case OpParamType::HalfTy:
217 return Type::getHalfTy(Ctx);
218 case OpParamType::FloatTy:
219 return Type::getFloatTy(Ctx);
220 case OpParamType::DoubleTy:
221 return Type::getDoubleTy(Ctx);
222 case OpParamType::Int1Ty:
223 return Type::getInt1Ty(Ctx);
224 case OpParamType::Int8Ty:
225 return Type::getInt8Ty(Ctx);
226 case OpParamType::Int16Ty:
227 return Type::getInt16Ty(Ctx);
228 case OpParamType::Int32Ty:
229 return Type::getInt32Ty(Ctx);
230 case OpParamType::Int64Ty:
231 return Type::getInt64Ty(Ctx);
232 case OpParamType::OverloadTy:
233 return OverloadTy;
234 case OpParamType::ResRetTy:
235 return getResRetType(OverloadTy, Ctx);
236 case OpParamType::HandleTy:
237 return getHandleType(Ctx);
238 }
239 llvm_unreachable("Invalid parameter kind");
240 return nullptr;
241}
242
243static ShaderKind getShaderKindEnum(Triple::EnvironmentType EnvType) {
244 switch (EnvType) {
245 case Triple::Pixel:
246 return ShaderKind::pixel;
247 case Triple::Vertex:
248 return ShaderKind::vertex;
249 case Triple::Geometry:
250 return ShaderKind::geometry;
251 case Triple::Hull:
252 return ShaderKind::hull;
253 case Triple::Domain:
254 return ShaderKind::domain;
255 case Triple::Compute:
256 return ShaderKind::compute;
257 case Triple::Library:
258 return ShaderKind::library;
260 return ShaderKind::raygeneration;
262 return ShaderKind::intersection;
263 case Triple::AnyHit:
264 return ShaderKind::anyhit;
266 return ShaderKind::closesthit;
267 case Triple::Miss:
268 return ShaderKind::miss;
269 case Triple::Callable:
270 return ShaderKind::callable;
271 case Triple::Mesh:
272 return ShaderKind::mesh;
274 return ShaderKind::amplification;
275 default:
276 break;
277 }
279 "Shader Kind Not Found - Invalid DXIL Environment Specified");
280}
281
284 LLVMContext &Context, Type *OverloadTy) {
285 SmallVector<Type *> ArgTys;
286 ArgTys.emplace_back(Type::getInt32Ty(Context));
287 for (dxil::OpParamType Ty : Types)
288 ArgTys.emplace_back(getTypeFromOpParamType(Ty, Context, OverloadTy));
289 return ArgTys;
290}
291
292/// Construct DXIL function type. This is the type of a function with
293/// the following prototype
294/// OverloadType dx.op.<opclass>.<return-type>(int opcode, <param types>)
295/// <param-types> are constructed from types in Prop.
297 LLVMContext &Context,
298 Type *OverloadTy) {
299
300 switch (OpCode) {
301#define DXIL_OP_FUNCTION_TYPE(OpCode, RetType, ...) \
302 case OpCode: \
303 return FunctionType::get( \
304 getTypeFromOpParamType(RetType, Context, OverloadTy), \
305 getArgTypesFromOpParamTypes({__VA_ARGS__}, Context, OverloadTy), \
306 /*isVarArg=*/false);
307#include "DXILOperation.inc"
308 }
309 llvm_unreachable("Invalid OpCode?");
310}
311
312/// Get index of the property from PropList valid for the most recent
313/// DXIL version not greater than DXILVer.
314/// PropList is expected to be sorted in ascending order of DXIL version.
315template <typename T>
316static std::optional<size_t> getPropIndex(ArrayRef<T> PropList,
317 const VersionTuple DXILVer) {
318 size_t Index = PropList.size() - 1;
319 for (auto Iter = PropList.rbegin(); Iter != PropList.rend();
320 Iter++, Index--) {
321 const T &Prop = *Iter;
322 if (VersionTuple(Prop.DXILVersion.Major, Prop.DXILVersion.Minor) <=
323 DXILVer) {
324 return Index;
325 }
326 }
327 return std::nullopt;
328}
329
330namespace llvm {
331namespace dxil {
332
333// No extra checks on TargetTriple need be performed to verify that the
334// Triple is well-formed or that the target is supported since these checks
335// would have been done at the time the module M is constructed in the earlier
336// stages of compilation.
337DXILOpBuilder::DXILOpBuilder(Module &M) : M(M), IRB(M.getContext()) {
338 Triple TT(Triple(M.getTargetTriple()));
339 DXILVersion = TT.getDXILVersion();
340 ShaderStage = TT.getEnvironment();
341 // Ensure Environment type is known
342 if (ShaderStage == Triple::UnknownEnvironment) {
344 Twine(DXILVersion.getAsString()) +
345 ": Unknown Compilation Target Shader Stage specified ",
346 /*gen_crash_diag*/ false);
347 }
348}
349
351 return make_error<StringError>(
352 Twine("Cannot create ") + getOpCodeName(OpCode) + " operation: " + Msg,
354}
355
358 Type *RetTy) {
359 const OpCodeProperty *Prop = getOpCodeProperty(OpCode);
360
361 Type *OverloadTy = nullptr;
362 if (Prop->OverloadParamIndex == 0) {
363 if (!RetTy)
364 return makeOpError(OpCode, "Op overloaded on unknown return type");
365 OverloadTy = RetTy;
366 } else if (Prop->OverloadParamIndex > 0) {
367 // The index counts including the return type
368 unsigned ArgIndex = Prop->OverloadParamIndex - 1;
369 if (static_cast<unsigned>(ArgIndex) >= Args.size())
370 return makeOpError(OpCode, "Wrong number of arguments");
371 OverloadTy = Args[ArgIndex]->getType();
372 }
373 FunctionType *DXILOpFT =
374 getDXILOpFunctionType(OpCode, M.getContext(), OverloadTy);
375
376 std::optional<size_t> OlIndexOrErr =
377 getPropIndex(ArrayRef(Prop->Overloads), DXILVersion);
378 if (!OlIndexOrErr.has_value())
379 return makeOpError(OpCode, Twine("No valid overloads for DXIL version ") +
380 DXILVersion.getAsString());
381
382 uint16_t ValidTyMask = Prop->Overloads[*OlIndexOrErr].ValidTys;
383
384 OverloadKind Kind = getOverloadKind(OverloadTy);
385
386 // Check if the operation supports overload types and OverloadTy is valid
387 // per the specified types for the operation
388 if ((ValidTyMask != OverloadKind::UNDEFINED) &&
389 (ValidTyMask & (uint16_t)Kind) == 0)
390 return makeOpError(OpCode, "Invalid overload type");
391
392 // Perform necessary checks to ensure Opcode is valid in the targeted shader
393 // kind
394 std::optional<size_t> StIndexOrErr =
395 getPropIndex(ArrayRef(Prop->Stages), DXILVersion);
396 if (!StIndexOrErr.has_value())
397 return makeOpError(OpCode, Twine("No valid stage for DXIL version ") +
398 DXILVersion.getAsString());
399
400 uint16_t ValidShaderKindMask = Prop->Stages[*StIndexOrErr].ValidStages;
401
402 // Ensure valid shader stage properties are specified
403 if (ValidShaderKindMask == ShaderKind::removed)
404 return makeOpError(OpCode, "Operation has been removed");
405
406 // Shader stage need not be validated since getShaderKindEnum() fails
407 // for unknown shader stage.
408
409 // Verify the target shader stage is valid for the DXIL operation
410 ShaderKind ModuleStagekind = getShaderKindEnum(ShaderStage);
411 if (!(ValidShaderKindMask & ModuleStagekind))
412 return makeOpError(OpCode, "Invalid stage");
413
414 std::string DXILFnName = constructOverloadName(Kind, OverloadTy, *Prop);
415 FunctionCallee DXILFn = M.getOrInsertFunction(DXILFnName, DXILOpFT);
416
417 // We need to inject the opcode as the first argument.
420 OpArgs.append(Args.begin(), Args.end());
421
422 return IRB.CreateCall(DXILFn, OpArgs);
423}
424
426 Type *RetTy) {
428 if (Error E = Result.takeError())
429 llvm_unreachable("Invalid arguments for operation");
430 return *Result;
431}
432
434 return ::getOpCodeName(DXILOp);
435}
436} // namespace dxil
437} // namespace llvm
static ShaderKind getShaderKindEnum(Triple::EnvironmentType EnvType)
static Type * getTypeFromOpParamType(OpParamType Kind, LLVMContext &Ctx, Type *OverloadTy)
static std::optional< size_t > getPropIndex(ArrayRef< T > PropList, const VersionTuple DXILVer)
Get index of the property from PropList valid for the most recent DXIL version not greater than DXILV...
static SmallVector< Type * > getArgTypesFromOpParamTypes(ArrayRef< dxil::OpParamType > Types, LLVMContext &Context, Type *OverloadTy)
static StructType * getResRetType(Type *OverloadTy, LLVMContext &Ctx)
static const char * getOverloadTypeName(OverloadKind Kind)
static OverloadKind getOverloadKind(Type *Ty)
static StructType * getOrCreateStructType(StringRef Name, ArrayRef< Type * > EltTys, LLVMContext &Ctx)
static StructType * getHandleType(LLVMContext &Ctx)
static std::string constructOverloadName(OverloadKind Kind, Type *Ty, const OpCodeProperty &Prop)
static FunctionType * getDXILOpFunctionType(dxil::OpCode OpCode, LLVMContext &Context, Type *OverloadTy)
Construct DXIL function type.
constexpr StringLiteral DXILOpNamePrefix
static std::string constructOverloadTypeName(OverloadKind Kind, StringRef TypeName)
return RetTy
std::string Name
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
@ UNDEFINED
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
reverse_iterator rend() const
Definition: ArrayRef.h:157
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
reverse_iterator rbegin() const
Definition: ArrayRef.h:156
This class represents a function call, abstracting a target machine's calling convention.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
Class to represent function types.
Definition: DerivedTypes.h:103
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:483
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2432
Class to represent integer types.
Definition: DerivedTypes.h:40
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Definition: DerivedTypes.h:72
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:299
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:169
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:696
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:838
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Class to represent struct types.
Definition: DerivedTypes.h:216
static StructType * getTypeByName(LLVMContext &C, StringRef Name)
Return the type with the specified name, or null if there is none by that name.
Definition: Type.cpp:620
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:501
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
@ RayGeneration
Definition: Triple.h:282
@ UnknownEnvironment
Definition: Triple.h:243
@ ClosestHit
Definition: Triple.h:285
@ Amplification
Definition: Triple.h:289
@ Intersection
Definition: Triple.h:283
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getHalfTy(LLVMContext &C)
static Type * getDoubleTy(LLVMContext &C)
static IntegerType * getInt1Ty(LLVMContext &C)
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:54
@ HalfTyID
16-bit floating point type
Definition: Type.h:56
@ VoidTyID
type with no size
Definition: Type.h:63
@ FloatTyID
32-bit floating point type
Definition: Type.h:58
@ StructTyID
Structures.
Definition: Type.h:73
@ IntegerTyID
Arbitrary bit width integers.
Definition: Type.h:70
@ DoubleTyID
64-bit floating point type
Definition: Type.h:59
@ PointerTyID
Pointers.
Definition: Type.h:72
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt16Ty(LLVMContext &C)
static IntegerType * getInt8Ty(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
static Type * getFloatTy(LLVMContext &C)
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:136
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:29
std::string getAsString() const
Retrieve a string representation of the version number.
Expected< CallInst * > tryCreateOp(dxil::OpCode Op, ArrayRef< Value * > Args, Type *RetTy=nullptr)
Try to create a call instruction for the given DXIL op.
CallInst * createOp(dxil::OpCode Op, ArrayRef< Value * > Args, Type *RetTy=nullptr)
Create a call instruction for the given DXIL op.
static const char * getOpCodeName(dxil::OpCode DXILOp)
Return the name of the given opcode.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static Error makeOpError(dxil::OpCode OpCode, Twine Msg)
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
StringRef getTypeName()
We provide a function which tries to compute the (demangled) name of a type statically.
Definition: TypeName.h:27
Version DXILVersion
uint32_t ValidAttrs
llvm::SmallVector< OpOverload > Overloads
llvm::SmallVector< OpAttribute > Attributes
dxil::OpCodeClass OpCodeClass
unsigned OpCodeNameOffset
unsigned OpCodeClassNameOffset
llvm::SmallVector< OpStage > Stages
dxil::OpCode OpCode
uint32_t ValidStages
Version DXILVersion