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"));
46cl::opt<bool> PdbInPrivate("dx-pdb-in-private",
47 cl::desc("Store PDB in private user data"));
48
49namespace {
50class DXContainerGlobals : public llvm::ModulePass {
51
52 GlobalVariable *buildContainerGlobal(Module &M, Constant *Content,
55 StringRef SectionData, StringRef MetadataName,
57 GlobalVariable *getFeatureFlags(Module &M);
58 void computeShaderHashAndDebugName(Module &M,
60 GlobalVariable *buildSignature(Module &M, Signature &Sig, StringRef Name,
62 void addSignature(Module &M, SmallVector<GlobalValue *> &Globals);
63 void addRootSignature(Module &M, SmallVector<GlobalValue *> &Globals);
64 void addResourcesForPSV(Module &M, PSVRuntimeInfo &PSV);
65 void addPipelineStateValidationInfo(Module &M,
67 void addCompilerVersion(Module &M, SmallVector<GlobalValue *> &Globals);
68 void addSourceInfo(Module &M, SmallVector<GlobalValue *> &Globals);
69
70public:
71 static char ID; // Pass identification, replacement for typeid
72 DXContainerGlobals() : ModulePass(ID) {}
73
74 StringRef getPassName() const override {
75 return "DXContainer Global Emitter";
76 }
77
78 bool runOnModule(Module &M) override;
79
80 void getAnalysisUsage(AnalysisUsage &AU) const override {
81 AU.setPreservesAll();
82 AU.addRequired<ShaderFlagsAnalysisWrapper>();
83 AU.addRequired<RootSignatureAnalysisWrapper>();
84 AU.addRequired<DXILMetadataAnalysisWrapperPass>();
85 AU.addRequired<DXILResourceTypeWrapperPass>();
86 AU.addRequired<DXILResourceWrapperPass>();
87 }
88};
89
90} // namespace
91
92bool DXContainerGlobals::runOnModule(Module &M) {
94 Globals.push_back(getFeatureFlags(M));
95 computeShaderHashAndDebugName(M, Globals);
96 addSignature(M, Globals);
97 addRootSignature(M, Globals);
98 addPipelineStateValidationInfo(M, Globals);
99 addCompilerVersion(M, Globals);
100 addSourceInfo(M, Globals);
101 appendToCompilerUsed(M, Globals);
102 return true;
103}
104
105GlobalVariable *DXContainerGlobals::getFeatureFlags(Module &M) {
106 uint64_t CombinedFeatureFlags = getAnalysis<ShaderFlagsAnalysisWrapper>()
107 .getShaderFlags()
108 .getCombinedFlags()
109 .getFeatureFlags();
110
111 Constant *FeatureFlagsConstant =
112 ConstantInt::get(M.getContext(), APInt(64, CombinedFeatureFlags));
113 return buildContainerGlobal(M, FeatureFlagsConstant, "dx.sfi0", "SFI0");
114}
115
116void DXContainerGlobals::addSection(Module &M,
118 StringRef SectionData,
119 StringRef MetadataName,
120 StringRef SectionName) {
121 Constant *SectionConstant = ConstantDataArray::getString(
122 M.getContext(), SectionData, /*AddNull*/ false);
123 Globals.emplace_back(
124 buildContainerGlobal(M, SectionConstant, MetadataName, SectionName));
125}
126
127void DXContainerGlobals::computeShaderHashAndDebugName(
128 Module &M, SmallVector<GlobalValue *> &Globals) {
129 ConstantDataArray *DXILConstant;
130 MD5 Digest;
131 dxbc::ShaderHash HashData = {0, {0}};
132
134 if (auto *ILDB = M.getNamedGlobal("dx.ildb")) {
135 DXILConstant = cast<ConstantDataArray>(ILDB->getInitializer());
136 HashData.Flags = static_cast<uint32_t>(dxbc::HashFlags::IncludesSource);
137 } else {
138 reportFatalUsageError("/Zss requires debug info (/Zi or /Zs)");
139 }
140 } else {
141 DXILConstant =
142 cast<ConstantDataArray>(M.getNamedGlobal("dx.dxil")->getInitializer());
143 }
144
145 Digest.update(DXILConstant->getRawDataValues());
146 MD5::MD5Result MD5 = Digest.final();
147
148 memcpy(reinterpret_cast<void *>(&HashData.Digest), MD5.data(), 16);
150 HashData.swapBytes();
151 StringRef Data(reinterpret_cast<char *>(&HashData), sizeof(dxbc::ShaderHash));
152
153 Constant *ModuleConstant =
155 Globals.emplace_back(
156 buildContainerGlobal(M, ModuleConstant, "dx.hash", "HASH"));
157
158 if (M.debug_compile_units().empty())
159 return;
160
161 SmallString<40> DebugNameStr;
162 Digest.stringifyResult(MD5, DebugNameStr);
163 DebugNameStr += ".pdb";
164 if (!PdbDebugPath.empty() || PdbInPrivate) {
165 if (!PdbDebugPath.empty()) {
166 StringRef DebugFile = PdbDebugPath.getValue();
167 SmallString<256> AbsoluteDebugName;
168 if (sys::path::is_separator(DebugFile.back())) {
169 // If PDB output path was specified as a directory, put the MD5.pdb file
170 // there.
171 AbsoluteDebugName = DebugFile;
172 sys::path::append(AbsoluteDebugName, DebugNameStr);
173 } else {
174 // Otherwise, use PDB output path as a user-provided PDB file name.
175 DebugNameStr = DebugFile;
176 AbsoluteDebugName = DebugNameStr;
177 }
178
179 // Pass PDB name to DXContainerPDBPass via PDBNAME section.
180 addSection(M, Globals, AbsoluteDebugName, "dx.pdb.name",
182 }
183
184 // Pass module hash to DXContainerPDBPass.
185 Globals.emplace_back(buildContainerGlobal(
186 M, ConstantDataArray::get(M.getContext(), ArrayRef(HashData.Digest)),
187 "dx.pdb.hash", ModuleHashSectionName));
188 }
189
190 // Emit ILDN part in debug info mode.
191 mcdxbc::DebugName DebugName;
192 DebugName.setFilename(DebugNameStr);
193 SmallString<64> ILDNData;
194 raw_svector_ostream OS(ILDNData);
195 DebugName.write(OS);
196 addSection(M, Globals, ILDNData, "dx.ildn", "ILDN");
197}
198
199GlobalVariable *DXContainerGlobals::buildContainerGlobal(
200 Module &M, Constant *Content, StringRef Name, StringRef SectionName) {
201 auto *GV = new llvm::GlobalVariable(
202 M, Content->getType(), true, GlobalValue::PrivateLinkage, Content, Name);
203 GV->setSection(SectionName);
204 GV->setAlignment(Align(4));
205 return GV;
206}
207
208GlobalVariable *DXContainerGlobals::buildSignature(Module &M, Signature &Sig,
209 StringRef Name,
210 StringRef SectionName) {
211 SmallString<256> Data;
212 raw_svector_ostream OS(Data);
213 Sig.write(OS);
215 ConstantDataArray::getString(M.getContext(), Data, /*AddNull*/ false);
216 return buildContainerGlobal(M, Constant, Name, SectionName);
217}
218
219void DXContainerGlobals::addSignature(Module &M,
221 // FIXME: support graphics shader.
222 // see issue https://github.com/llvm/llvm-project/issues/90504.
223
224 Signature InputSig;
225 Globals.emplace_back(buildSignature(M, InputSig, "dx.isg1", "ISG1"));
226
227 Signature OutputSig;
228 Globals.emplace_back(buildSignature(M, OutputSig, "dx.osg1", "OSG1"));
229}
230
231void DXContainerGlobals::addRootSignature(Module &M,
233
234 dxil::ModuleMetadataInfo &MMI =
235 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
236
237 // Root Signature in Library don't compile to DXContainer.
239 return;
240
241 auto &RSA = getAnalysis<RootSignatureAnalysisWrapper>().getRSInfo();
242 const Function *EntryFunction = nullptr;
243
245 assert(MMI.EntryPropertyVec.size() == 1);
246 EntryFunction = MMI.EntryPropertyVec[0].Entry;
247 }
248
249 const mcdxbc::RootSignatureDesc *RS = RSA.getDescForFunction(EntryFunction);
250 if (!RS)
251 return;
252
253 SmallString<256> Data;
254 raw_svector_ostream OS(Data);
255
256 RS->write(OS);
257
258 addSection(M, Globals, Data, "dx.rts0", "RTS0");
259}
260
261void DXContainerGlobals::addResourcesForPSV(Module &M, PSVRuntimeInfo &PSV) {
262 const DXILResourceMap &DRM =
263 getAnalysis<DXILResourceWrapperPass>().getResourceMap();
264 DXILResourceTypeMap &DRTM =
265 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
266
267 auto MakeBinding =
268 [](const dxil::ResourceInfo::ResourceBinding &Binding,
270 const dxbc::PSV::ResourceFlags Flags = dxbc::PSV::ResourceFlags()) {
271 dxbc::PSV::v2::ResourceBindInfo BindInfo;
272 BindInfo.Type = Type;
273 BindInfo.LowerBound = Binding.LowerBound;
274 assert(
275 (Binding.Size == 0 ||
276 (uint64_t)Binding.LowerBound + Binding.Size - 1 <= UINT32_MAX) &&
277 "Resource range is too large");
278 BindInfo.UpperBound = (Binding.Size == 0)
279 ? UINT32_MAX
280 : Binding.LowerBound + Binding.Size - 1;
281 BindInfo.Space = Binding.Space;
282 BindInfo.Kind = static_cast<dxbc::PSV::ResourceKind>(Kind);
283 BindInfo.Flags = Flags;
284 return BindInfo;
285 };
286
287 for (const dxil::ResourceInfo &RI : DRM.cbuffers()) {
288 const dxil::ResourceInfo::ResourceBinding &Binding = RI.getBinding();
289 PSV.Resources.push_back(MakeBinding(Binding, dxbc::PSV::ResourceType::CBV,
290 dxil::ResourceKind::CBuffer));
291 }
292 for (const dxil::ResourceInfo &RI : DRM.samplers()) {
293 const dxil::ResourceInfo::ResourceBinding &Binding = RI.getBinding();
294 PSV.Resources.push_back(MakeBinding(Binding,
295 dxbc::PSV::ResourceType::Sampler,
296 dxil::ResourceKind::Sampler));
297 }
298 for (const dxil::ResourceInfo &RI : DRM.srvs()) {
299 const dxil::ResourceInfo::ResourceBinding &Binding = RI.getBinding();
300
301 dxil::ResourceTypeInfo &TypeInfo = DRTM[RI.getHandleTy()];
303 if (TypeInfo.isStruct())
304 ResType = dxbc::PSV::ResourceType::SRVStructured;
305 else if (TypeInfo.isTyped())
306 ResType = dxbc::PSV::ResourceType::SRVTyped;
307 else
308 ResType = dxbc::PSV::ResourceType::SRVRaw;
309
310 PSV.Resources.push_back(
311 MakeBinding(Binding, ResType, TypeInfo.getResourceKind()));
312 }
313 for (const dxil::ResourceInfo &RI : DRM.uavs()) {
314 const dxil::ResourceInfo::ResourceBinding &Binding = RI.getBinding();
315
316 dxil::ResourceTypeInfo &TypeInfo = DRTM[RI.getHandleTy()];
318 if (RI.hasCounter())
319 ResType = dxbc::PSV::ResourceType::UAVStructuredWithCounter;
320 else if (TypeInfo.isStruct())
321 ResType = dxbc::PSV::ResourceType::UAVStructured;
322 else if (TypeInfo.isTyped())
323 ResType = dxbc::PSV::ResourceType::UAVTyped;
324 else
325 ResType = dxbc::PSV::ResourceType::UAVRaw;
326
327 dxbc::PSV::ResourceFlags Flags;
328 // TODO: Add support for dxbc::PSV::ResourceFlag::UsedByAtomic64, tracking
329 // with https://github.com/llvm/llvm-project/issues/104392
330 Flags.Flags = 0u;
331
332 PSV.Resources.push_back(
333 MakeBinding(Binding, ResType, TypeInfo.getResourceKind(), Flags));
334 }
335}
336
337void DXContainerGlobals::addPipelineStateValidationInfo(
338 Module &M, SmallVector<GlobalValue *> &Globals) {
339 SmallString<256> Data;
340 raw_svector_ostream OS(Data);
341 PSVRuntimeInfo PSV;
343 PSV.BaseData.MaximumWaveLaneCount = std::numeric_limits<uint32_t>::max();
344
345 dxil::ModuleMetadataInfo &MMI =
346 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
347 assert(MMI.EntryPropertyVec.size() == 1 ||
351 static_cast<uint8_t>(MMI.ShaderProfile - Triple::Pixel);
352
353 addResourcesForPSV(M, PSV);
354
355 // Hardcoded values here to unblock loading the shader into D3D.
356 //
357 // TODO: Lots more stuff to do here!
358 //
359 // See issue https://github.com/llvm/llvm-project/issues/96674.
360 switch (MMI.ShaderProfile) {
361 case Triple::Compute:
362 PSV.BaseData.NumThreadsX = MMI.EntryPropertyVec[0].NumThreadsX;
363 PSV.BaseData.NumThreadsY = MMI.EntryPropertyVec[0].NumThreadsY;
364 PSV.BaseData.NumThreadsZ = MMI.EntryPropertyVec[0].NumThreadsZ;
365 if (MMI.EntryPropertyVec[0].WaveSizeMin) {
366 PSV.BaseData.MinimumWaveLaneCount = MMI.EntryPropertyVec[0].WaveSizeMin;
368 MMI.EntryPropertyVec[0].WaveSizeMax
369 ? MMI.EntryPropertyVec[0].WaveSizeMax
370 : MMI.EntryPropertyVec[0].WaveSizeMin;
371 }
372 break;
373 default:
374 break;
375 }
376
377 if (MMI.ShaderProfile != Triple::Library &&
379 PSV.EntryName = MMI.EntryPropertyVec[0].Entry->getName();
380
381 PSV.finalize(MMI.ShaderProfile);
382 PSV.write(OS);
383 addSection(M, Globals, Data, "dx.psv0", "PSV0");
384}
385
386void DXContainerGlobals::addCompilerVersion(
387 Module &M, SmallVector<GlobalValue *> &Globals) {
388 if (M.debug_compile_units().empty())
389 return;
390
391 SmallString<256> Data;
392 raw_svector_ostream OS(Data);
393 mcdxbc::CompilerVersion CompilerVersion;
394 CompilerVersion.write(OS);
395 addSection(M, Globals, Data, "dx.vers", "VERS");
396}
397
398void DXContainerGlobals::addSourceInfo(Module &M,
400 dxil::ModuleMetadataInfo &MMI =
401 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
402
404 return;
405
406 MMI.SourceInfo->computeEntries();
407 MMI.SourceInfo->finalize();
408 SmallString<256> Data;
409 raw_svector_ostream OS(Data);
410 MMI.SourceInfo->write(OS);
411 addSection(M, Globals, Data, "dx.srci", "SRCI");
412}
413
414char DXContainerGlobals::ID = 0;
415INITIALIZE_PASS_BEGIN(DXContainerGlobals, "dxil-globals",
416 "DXContainer Global Emitter", false, true)
421INITIALIZE_PASS_END(DXContainerGlobals, "dxil-globals",
422 "DXContainer Global Emitter", false, true)
423
425 return new DXContainerGlobals();
426}
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< bool > PdbInPrivate("dx-pdb-in-private", cl::desc("Store PDB in private user data"))
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:410
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