LLVM 24.0.0git
DXContainerGlobals.cpp
Go to the documentation of this file.
1//===- DXContainerGlobals.cpp - DXContainer global generator pass ---------===//
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// DXContainerGlobalsPass implementation.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DXILRootSignature.h"
14#include "DXILShaderFlags.h"
15#include "DirectX.h"
18#include "llvm/ADT/StringRef.h"
22#include "llvm/CodeGen/Passes.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/Module.h"
29#include "llvm/Pass.h"
32#include "llvm/Support/MD5.h"
33#include "llvm/Support/Path.h"
36#include <cstdint>
37
38using namespace llvm;
39using namespace llvm::dxil;
40using namespace llvm::mcdxbc;
41
43 "dx-Zss", cl::desc("Compute Shader Hash considering source information"));
46
47namespace {
48class DXContainerGlobals : public llvm::ModulePass {
49
50 GlobalVariable *buildContainerGlobal(Module &M, Constant *Content,
53 StringRef SectionData, StringRef MetadataName,
55 GlobalVariable *getFeatureFlags(Module &M);
56 void computeShaderHashAndDebugName(Module &M,
58 GlobalVariable *buildSignature(Module &M, Signature &Sig, StringRef Name,
60 void addSignature(Module &M, SmallVector<GlobalValue *> &Globals);
61 void addRootSignature(Module &M, SmallVector<GlobalValue *> &Globals);
62 void addResourcesForPSV(Module &M, PSVRuntimeInfo &PSV);
63 void addPipelineStateValidationInfo(Module &M,
65 void addCompilerVersion(Module &M, SmallVector<GlobalValue *> &Globals);
66 void addSourceInfo(Module &M, SmallVector<GlobalValue *> &Globals);
67
68public:
69 static char ID; // Pass identification, replacement for typeid
70 DXContainerGlobals() : ModulePass(ID) {}
71
72 StringRef getPassName() const override {
73 return "DXContainer Global Emitter";
74 }
75
76 bool runOnModule(Module &M) override;
77
78 void getAnalysisUsage(AnalysisUsage &AU) const override {
79 AU.setPreservesAll();
80 AU.addRequired<ShaderFlagsAnalysisWrapper>();
81 AU.addRequired<RootSignatureAnalysisWrapper>();
82 AU.addRequired<DXILMetadataAnalysisWrapperPass>();
83 AU.addRequired<DXILResourceTypeWrapperPass>();
84 AU.addRequired<DXILResourceWrapperPass>();
85 }
86};
87
88} // namespace
89
90bool DXContainerGlobals::runOnModule(Module &M) {
92 Globals.push_back(getFeatureFlags(M));
93 computeShaderHashAndDebugName(M, Globals);
94 addSignature(M, Globals);
95 addRootSignature(M, Globals);
96 addPipelineStateValidationInfo(M, Globals);
97 addCompilerVersion(M, Globals);
98 addSourceInfo(M, Globals);
99 appendToCompilerUsed(M, Globals);
100 return true;
101}
102
103GlobalVariable *DXContainerGlobals::getFeatureFlags(Module &M) {
104 uint64_t CombinedFeatureFlags = getAnalysis<ShaderFlagsAnalysisWrapper>()
105 .getShaderFlags()
106 .getCombinedFlags()
107 .getFeatureFlags();
108
109 Constant *FeatureFlagsConstant =
110 ConstantInt::get(M.getContext(), APInt(64, CombinedFeatureFlags));
111 return buildContainerGlobal(M, FeatureFlagsConstant, "dx.sfi0", "SFI0");
112}
113
114void DXContainerGlobals::addSection(Module &M,
116 StringRef SectionData,
117 StringRef MetadataName,
118 StringRef SectionName) {
119 Constant *SectionConstant = ConstantDataArray::getString(
120 M.getContext(), SectionData, /*AddNull*/ false);
121 Globals.emplace_back(
122 buildContainerGlobal(M, SectionConstant, MetadataName, SectionName));
123}
124
125void DXContainerGlobals::computeShaderHashAndDebugName(
126 Module &M, SmallVector<GlobalValue *> &Globals) {
127 ConstantDataArray *DXILConstant;
128 MD5 Digest;
129 dxbc::ShaderHash HashData = {0, {0}};
130
132 if (auto *ILDB = M.getNamedGlobal("dx.ildb")) {
133 DXILConstant = cast<ConstantDataArray>(ILDB->getInitializer());
134 HashData.Flags = static_cast<uint32_t>(dxbc::HashFlags::IncludesSource);
135 } else {
136 reportFatalUsageError("/Zss requires debug info (/Zi or /Zs)");
137 }
138 } else {
139 DXILConstant =
140 cast<ConstantDataArray>(M.getNamedGlobal("dx.dxil")->getInitializer());
141 }
142
143 Digest.update(DXILConstant->getRawDataValues());
144 MD5::MD5Result MD5 = Digest.final();
145
146 memcpy(reinterpret_cast<void *>(&HashData.Digest), MD5.data(), 16);
148 HashData.swapBytes();
149 StringRef Data(reinterpret_cast<char *>(&HashData), sizeof(dxbc::ShaderHash));
150
151 Constant *ModuleConstant =
153 Globals.emplace_back(
154 buildContainerGlobal(M, ModuleConstant, "dx.hash", "HASH"));
155
156 if (M.debug_compile_units().empty())
157 return;
158
159 SmallString<40> DebugNameStr;
160 Digest.stringifyResult(MD5, DebugNameStr);
161 DebugNameStr += ".pdb";
162 if (!PdbDebugPath.empty()) {
163 StringRef DebugFile = PdbDebugPath.getValue();
164 SmallString<256> AbsoluteDebugName;
165 if (sys::path::is_separator(DebugFile.back())) {
166 // If /Fd was specified as a directory, put the MD5.pdb file there.
167 AbsoluteDebugName = DebugFile;
168 sys::path::append(AbsoluteDebugName, DebugNameStr);
169 } else {
170 // Otherwise, use /Fd value as a user-provided PDB file name.
171 DebugNameStr = DebugFile;
172 AbsoluteDebugName = DebugNameStr;
173 }
174
175 // Pass PDB name to DXContainerPDBPass via PDBNAME section.
176 addSection(M, Globals, AbsoluteDebugName, "dx.pdb.name",
178 // Pass module hash to DXContainerPDBPass.
179 Globals.emplace_back(buildContainerGlobal(
180 M, ConstantDataArray::get(M.getContext(), ArrayRef(HashData.Digest)),
181 "dx.pdb.hash", ModuleHashSectionName));
182 }
183
184 // Emit ILDN part in debug info mode.
185 mcdxbc::DebugName DebugName;
186 DebugName.setFilename(DebugNameStr);
187 SmallString<64> ILDNData;
188 raw_svector_ostream OS(ILDNData);
189 DebugName.write(OS);
190 addSection(M, Globals, ILDNData, "dx.ildn", "ILDN");
191}
192
193GlobalVariable *DXContainerGlobals::buildContainerGlobal(
194 Module &M, Constant *Content, StringRef Name, StringRef SectionName) {
195 auto *GV = new llvm::GlobalVariable(
196 M, Content->getType(), true, GlobalValue::PrivateLinkage, Content, Name);
197 GV->setSection(SectionName);
198 GV->setAlignment(Align(4));
199 return GV;
200}
201
202GlobalVariable *DXContainerGlobals::buildSignature(Module &M, Signature &Sig,
203 StringRef Name,
204 StringRef SectionName) {
205 SmallString<256> Data;
206 raw_svector_ostream OS(Data);
207 Sig.write(OS);
209 ConstantDataArray::getString(M.getContext(), Data, /*AddNull*/ false);
210 return buildContainerGlobal(M, Constant, Name, SectionName);
211}
212
213void DXContainerGlobals::addSignature(Module &M,
215 // FIXME: support graphics shader.
216 // see issue https://github.com/llvm/llvm-project/issues/90504.
217
218 Signature InputSig;
219 Globals.emplace_back(buildSignature(M, InputSig, "dx.isg1", "ISG1"));
220
221 Signature OutputSig;
222 Globals.emplace_back(buildSignature(M, OutputSig, "dx.osg1", "OSG1"));
223}
224
225void DXContainerGlobals::addRootSignature(Module &M,
227
228 dxil::ModuleMetadataInfo &MMI =
229 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
230
231 // Root Signature in Library don't compile to DXContainer.
233 return;
234
235 auto &RSA = getAnalysis<RootSignatureAnalysisWrapper>().getRSInfo();
236 const Function *EntryFunction = nullptr;
237
239 assert(MMI.EntryPropertyVec.size() == 1);
240 EntryFunction = MMI.EntryPropertyVec[0].Entry;
241 }
242
243 const mcdxbc::RootSignatureDesc *RS = RSA.getDescForFunction(EntryFunction);
244 if (!RS)
245 return;
246
247 SmallString<256> Data;
248 raw_svector_ostream OS(Data);
249
250 RS->write(OS);
251
252 addSection(M, Globals, Data, "dx.rts0", "RTS0");
253}
254
255void DXContainerGlobals::addResourcesForPSV(Module &M, PSVRuntimeInfo &PSV) {
256 const DXILResourceMap &DRM =
257 getAnalysis<DXILResourceWrapperPass>().getResourceMap();
258 DXILResourceTypeMap &DRTM =
259 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
260
261 auto MakeBinding =
262 [](const dxil::ResourceInfo::ResourceBinding &Binding,
264 const dxbc::PSV::ResourceFlags Flags = dxbc::PSV::ResourceFlags()) {
265 dxbc::PSV::v2::ResourceBindInfo BindInfo;
266 BindInfo.Type = Type;
267 BindInfo.LowerBound = Binding.LowerBound;
268 assert(
269 (Binding.Size == 0 ||
270 (uint64_t)Binding.LowerBound + Binding.Size - 1 <= UINT32_MAX) &&
271 "Resource range is too large");
272 BindInfo.UpperBound = (Binding.Size == 0)
273 ? UINT32_MAX
274 : Binding.LowerBound + Binding.Size - 1;
275 BindInfo.Space = Binding.Space;
276 BindInfo.Kind = static_cast<dxbc::PSV::ResourceKind>(Kind);
277 BindInfo.Flags = Flags;
278 return BindInfo;
279 };
280
281 for (const dxil::ResourceInfo &RI : DRM.cbuffers()) {
282 const dxil::ResourceInfo::ResourceBinding &Binding = RI.getBinding();
283 PSV.Resources.push_back(MakeBinding(Binding, dxbc::PSV::ResourceType::CBV,
284 dxil::ResourceKind::CBuffer));
285 }
286 for (const dxil::ResourceInfo &RI : DRM.samplers()) {
287 const dxil::ResourceInfo::ResourceBinding &Binding = RI.getBinding();
288 PSV.Resources.push_back(MakeBinding(Binding,
289 dxbc::PSV::ResourceType::Sampler,
290 dxil::ResourceKind::Sampler));
291 }
292 for (const dxil::ResourceInfo &RI : DRM.srvs()) {
293 const dxil::ResourceInfo::ResourceBinding &Binding = RI.getBinding();
294
295 dxil::ResourceTypeInfo &TypeInfo = DRTM[RI.getHandleTy()];
297 if (TypeInfo.isStruct())
298 ResType = dxbc::PSV::ResourceType::SRVStructured;
299 else if (TypeInfo.isTyped())
300 ResType = dxbc::PSV::ResourceType::SRVTyped;
301 else
302 ResType = dxbc::PSV::ResourceType::SRVRaw;
303
304 PSV.Resources.push_back(
305 MakeBinding(Binding, ResType, TypeInfo.getResourceKind()));
306 }
307 for (const dxil::ResourceInfo &RI : DRM.uavs()) {
308 const dxil::ResourceInfo::ResourceBinding &Binding = RI.getBinding();
309
310 dxil::ResourceTypeInfo &TypeInfo = DRTM[RI.getHandleTy()];
312 if (RI.hasCounter())
313 ResType = dxbc::PSV::ResourceType::UAVStructuredWithCounter;
314 else if (TypeInfo.isStruct())
315 ResType = dxbc::PSV::ResourceType::UAVStructured;
316 else if (TypeInfo.isTyped())
317 ResType = dxbc::PSV::ResourceType::UAVTyped;
318 else
319 ResType = dxbc::PSV::ResourceType::UAVRaw;
320
321 dxbc::PSV::ResourceFlags Flags;
322 // TODO: Add support for dxbc::PSV::ResourceFlag::UsedByAtomic64, tracking
323 // with https://github.com/llvm/llvm-project/issues/104392
324 Flags.Flags = 0u;
325
326 PSV.Resources.push_back(
327 MakeBinding(Binding, ResType, TypeInfo.getResourceKind(), Flags));
328 }
329}
330
331void DXContainerGlobals::addPipelineStateValidationInfo(
332 Module &M, SmallVector<GlobalValue *> &Globals) {
333 SmallString<256> Data;
334 raw_svector_ostream OS(Data);
335 PSVRuntimeInfo PSV;
337 PSV.BaseData.MaximumWaveLaneCount = std::numeric_limits<uint32_t>::max();
338
339 dxil::ModuleMetadataInfo &MMI =
340 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
341 assert(MMI.EntryPropertyVec.size() == 1 ||
345 static_cast<uint8_t>(MMI.ShaderProfile - Triple::Pixel);
346
347 addResourcesForPSV(M, PSV);
348
349 // Hardcoded values here to unblock loading the shader into D3D.
350 //
351 // TODO: Lots more stuff to do here!
352 //
353 // See issue https://github.com/llvm/llvm-project/issues/96674.
354 switch (MMI.ShaderProfile) {
355 case Triple::Compute:
356 PSV.BaseData.NumThreadsX = MMI.EntryPropertyVec[0].NumThreadsX;
357 PSV.BaseData.NumThreadsY = MMI.EntryPropertyVec[0].NumThreadsY;
358 PSV.BaseData.NumThreadsZ = MMI.EntryPropertyVec[0].NumThreadsZ;
359 if (MMI.EntryPropertyVec[0].WaveSizeMin) {
360 PSV.BaseData.MinimumWaveLaneCount = MMI.EntryPropertyVec[0].WaveSizeMin;
362 MMI.EntryPropertyVec[0].WaveSizeMax
363 ? MMI.EntryPropertyVec[0].WaveSizeMax
364 : MMI.EntryPropertyVec[0].WaveSizeMin;
365 }
366 break;
367 default:
368 break;
369 }
370
371 if (MMI.ShaderProfile != Triple::Library &&
373 PSV.EntryName = MMI.EntryPropertyVec[0].Entry->getName();
374
375 PSV.finalize(MMI.ShaderProfile);
376 PSV.write(OS);
377 addSection(M, Globals, Data, "dx.psv0", "PSV0");
378}
379
380void DXContainerGlobals::addCompilerVersion(
381 Module &M, SmallVector<GlobalValue *> &Globals) {
382 if (M.debug_compile_units().empty())
383 return;
384
385 SmallString<256> Data;
386 raw_svector_ostream OS(Data);
387 mcdxbc::CompilerVersion CompilerVersion;
388 CompilerVersion.write(OS);
389 addSection(M, Globals, Data, "dx.vers", "VERS");
390}
391
392void DXContainerGlobals::addSourceInfo(Module &M,
394 dxil::ModuleMetadataInfo &MMI =
395 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
396
398 return;
399
400 MMI.SourceInfo->computeEntries();
401 MMI.SourceInfo->finalize();
402 SmallString<256> Data;
403 raw_svector_ostream OS(Data);
404 MMI.SourceInfo->write(OS);
405 addSection(M, Globals, Data, "dx.srci", "SRCI");
406}
407
408char DXContainerGlobals::ID = 0;
409INITIALIZE_PASS_BEGIN(DXContainerGlobals, "dxil-globals",
410 "DXContainer Global Emitter", false, true)
415INITIALIZE_PASS_END(DXContainerGlobals, "dxil-globals",
416 "DXContainer Global Emitter", false, true)
417
419 return new DXContainerGlobals();
420}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
cl::opt< std::string > PdbDebugPath
cl::opt< bool > SourceInDebugModule
static cl::opt< bool > ShaderHashDependsOnSource("dx-Zss", cl::desc("Compute Shader Hash considering source information"))
DXIL Resource Implicit Binding
Module.h This file contains the declarations for the Module class.
static Error addSection(const NewSectionInfo &NewSection, Object &Obj)
Machine Check Debug Module
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
LLVM_ABI StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
This is an important base class in LLVM.
Definition Constant.h:43
iterator_range< iterator > samplers()
iterator_range< iterator > srvs()
iterator_range< iterator > cbuffers()
iterator_range< iterator > uavs()
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
static LLVM_ABI void stringifyResult(MD5Result &Result, SmallVectorImpl< char > &Str)
Translates the bytes in Res to a hex string that is deposited into Str.
Definition MD5.cpp:286
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
char back() const
Get the last character in the string.
Definition StringRef.h:153
@ RootSignature
Definition Triple.h:409
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI bool isTyped() const
LLVM_ABI bool isStruct() const
dxil::ResourceKind getResourceKind() const
Wrapper pass for the legacy pass manager.
LLVM_ABI void write(raw_ostream &OS)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
ResourceKind
The kind of resource for an SRV or UAV resource.
Definition DXILABI.h:44
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition Path.cpp:618
constexpr bool IsBigEndianHost
This is an optimization pass for GlobalISel generic memory operations.
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
ModulePass * createDXContainerGlobalsPass()
Pass for generating DXContainer part globals.
static constexpr StringLiteral ModuleHashSectionName
Contains module hash.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static constexpr StringLiteral PdbFileNameSectionName
Contains PDB output file name.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
std::optional< mcdxbc::SourceInfoBuilder > SourceInfo
Triple::EnvironmentType ShaderProfile
SmallVector< EntryProperties > EntryPropertyVec
LLVM_ABI void write(raw_ostream &OS) const
LLVM_ABI void setFilename(StringRef DebugFilename)
LLVM_ABI void write(raw_ostream &OS) const
dxbc::PSV::v3::RuntimeInfo BaseData
SmallVector< dxbc::PSV::v2::ResourceBindInfo > Resources
LLVM_ABI void finalize(Triple::EnvironmentType Stage, uint32_t Version=std::numeric_limits< uint32_t >::max())
LLVM_ABI void write(raw_ostream &OS, uint32_t Version=std::numeric_limits< uint32_t >::max()) const