1//===- DXILPrettyPrinter.cpp - Print resources for textual DXIL -----------===//
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#include "DXILWriter/DXILDebugInfoMap.h"
10#include "DirectX.h"
11#include "llvm/ADT/DenseSet.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/SmallVector.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Analysis/DXILResource.h"
16#include "llvm/IR/AssemblyAnnotationWriter.h"
17#include "llvm/IR/DebugInfo.h"
18#include "llvm/IR/Metadata.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/ModuleSlotTracker.h"
21#include "llvm/IR/PassManager.h"
22#include "llvm/InitializePasses.h"
23#include "llvm/Pass.h"
24#include "llvm/Support/FormatAdapters.h"
25#include "llvm/Support/FormatVariadic.h"
26#include "llvm/Support/FormattedStream.h"
27#include "llvm/Support/raw_ostream.h"
28
29using namespace llvm;
30using namespace llvm::dxil;
31
32static StringRef getRCName(dxil::ResourceClass RC) {
33 switch (RC) {
34 case dxil::ResourceClass::SRV:
35 return "texture";
36 case dxil::ResourceClass::UAV:
37 return "UAV";
38 case dxil::ResourceClass::CBuffer:
39 return "cbuffer";
40 case dxil::ResourceClass::Sampler:
41 return "sampler";
42 }
43 llvm_unreachable("covered switch");
44}
45
46static StringRef getRCPrefix(dxil::ResourceClass RC) {
47 switch (RC) {
48 case dxil::ResourceClass::SRV:
49 return "t";
50 case dxil::ResourceClass::UAV:
51 return "u";
52 case dxil::ResourceClass::CBuffer:
53 return "cb";
54 case dxil::ResourceClass::Sampler:
55 return "s";
56 }
57 llvm_unreachable("covered switch");
58}
59
60static StringRef getFormatName(const dxil::ResourceTypeInfo &RI) {
61 if (RI.isTyped()) {
62 switch (RI.getTyped().DXILStorageTy) {
63 case dxil::ElementType::I1:
64 return "i1";
65 case dxil::ElementType::I16:
66 return "i16";
67 case dxil::ElementType::U16:
68 return "u16";
69 case dxil::ElementType::I32:
70 return "i32";
71 case dxil::ElementType::U32:
72 return "u32";
73 case dxil::ElementType::I64:
74 return "i64";
75 case dxil::ElementType::U64:
76 return "u64";
77 case dxil::ElementType::F16:
78 return "f16";
79 case dxil::ElementType::F32:
80 return "f32";
81 case dxil::ElementType::F64:
82 return "f64";
83 case dxil::ElementType::SNormF16:
84 return "snorm_f16";
85 case dxil::ElementType::UNormF16:
86 return "unorm_f16";
87 case dxil::ElementType::SNormF32:
88 return "snorm_f32";
89 case dxil::ElementType::UNormF32:
90 return "unorm_f32";
91 case dxil::ElementType::SNormF64:
92 return "snorm_f64";
93 case dxil::ElementType::UNormF64:
94 return "unorm_f64";
95 case dxil::ElementType::PackedS8x32:
96 return "p32i8";
97 case dxil::ElementType::PackedU8x32:
98 return "p32u8";
99 case dxil::ElementType::Invalid:
100 llvm_unreachable("Invalid ElementType");
101 }
102 llvm_unreachable("Unhandled ElementType");
103 } else if (RI.isStruct())
104 return "struct";
105 else if (RI.isCBuffer() || RI.isSampler())
106 return "NA";
107 return "byte";
108}
109
110static StringRef getTextureDimName(dxil::ResourceKind RK) {
111 switch (RK) {
112 case dxil::ResourceKind::Texture1D:
113 return "1d";
114 case dxil::ResourceKind::Texture2D:
115 return "2d";
116 case dxil::ResourceKind::Texture3D:
117 return "3d";
118 case dxil::ResourceKind::TextureCube:
119 return "cube";
120 case dxil::ResourceKind::Texture1DArray:
121 return "1darray";
122 case dxil::ResourceKind::Texture2DArray:
123 return "2darray";
124 case dxil::ResourceKind::TextureCubeArray:
125 return "cubearray";
126 case dxil::ResourceKind::TBuffer:
127 return "tbuffer";
128 case dxil::ResourceKind::FeedbackTexture2D:
129 return "fbtex2d";
130 case dxil::ResourceKind::FeedbackTexture2DArray:
131 return "fbtex2darray";
132 case dxil::ResourceKind::Texture2DMS:
133 return "2dMS";
134 case dxil::ResourceKind::Texture2DMSArray:
135 return "2darrayMS";
136 case dxil::ResourceKind::Invalid:
137 case dxil::ResourceKind::NumEntries:
138 case dxil::ResourceKind::CBuffer:
139 case dxil::ResourceKind::RawBuffer:
140 case dxil::ResourceKind::Sampler:
141 case dxil::ResourceKind::StructuredBuffer:
142 case dxil::ResourceKind::TypedBuffer:
143 case dxil::ResourceKind::RTAccelerationStructure:
144 llvm_unreachable("Invalid ResourceKind for texture");
145 }
146 llvm_unreachable("Unhandled ResourceKind");
147}
148
149namespace {
150struct FormatResourceDimension
151 : public llvm::FormatAdapter<const dxil::ResourceTypeInfo &> {
152 FormatResourceDimension(const dxil::ResourceTypeInfo &RI, bool HasCounter)
153 : llvm::FormatAdapter<const dxil::ResourceTypeInfo &>(RI),
154 HasCounter(HasCounter) {}
155
156 bool HasCounter;
157
158 void format(llvm::raw_ostream &OS, StringRef Style) {
159 dxil::ResourceKind RK = Item.getResourceKind();
160 switch (RK) {
161 default: {
162 OS << getTextureDimName(RK);
163 if (Item.isMultiSample())
164 OS << Item.getMultiSampleCount();
165 break;
166 }
167 case dxil::ResourceKind::RawBuffer:
168 case dxil::ResourceKind::StructuredBuffer:
169 if (!Item.isUAV())
170 OS << "r/o";
171 else if (HasCounter)
172 OS << "r/w+cnt";
173 else
174 OS << "r/w";
175 break;
176 case dxil::ResourceKind::TypedBuffer:
177 OS << "buf";
178 break;
179 case dxil::ResourceKind::CBuffer:
180 OS << "NA";
181 break;
182 case dxil::ResourceKind::RTAccelerationStructure:
183 // TODO: dxc would print "ras" here. Can/should this happen?
184 llvm_unreachable("RTAccelerationStructure printing is not implemented");
185 }
186 }
187};
188
189struct FormatBindingID
190 : public llvm::FormatAdapter<const dxil::ResourceInfo &> {
191 dxil::ResourceClass RC;
192
193 explicit FormatBindingID(const dxil::ResourceInfo &RI,
194 const dxil::ResourceTypeInfo &RTI)
195 : llvm::FormatAdapter<const dxil::ResourceInfo &>(RI),
196 RC(RTI.getResourceClass()) {}
197
198 void format(llvm::raw_ostream &OS, StringRef Style) {
199 OS << getRCPrefix(RC).upper() << Item.getBinding().BindingID;
200 }
201};
202
203struct FormatBindingLocation
204 : public llvm::FormatAdapter<const dxil::ResourceInfo &> {
205 dxil::ResourceClass RC;
206
207 explicit FormatBindingLocation(const dxil::ResourceInfo &RI,
208 const dxil::ResourceTypeInfo &RTI)
209 : llvm::FormatAdapter<const dxil::ResourceInfo &>(RI),
210 RC(RTI.getResourceClass()) {}
211
212 void format(llvm::raw_ostream &OS, StringRef Style) {
213 const auto &Binding = Item.getBinding();
214 OS << getRCPrefix(RC) << Binding.LowerBound;
215 if (Binding.Space)
216 OS << ",space" << Binding.Space;
217 }
218};
219
220struct FormatBindingSize
221 : public llvm::FormatAdapter<const dxil::ResourceInfo &> {
222 explicit FormatBindingSize(const dxil::ResourceInfo &RI)
223 : llvm::FormatAdapter<const dxil::ResourceInfo &>(RI) {}
224
225 void format(llvm::raw_ostream &OS, StringRef Style) {
226 uint32_t Size = Item.getBinding().Size;
227 if (Size == 0)
228 OS << "unbounded";
229 else
230 OS << Size;
231 }
232};
233
234} // namespace
235
236static void prettyPrintResources(raw_ostream &OS, const DXILResourceMap &DRM,
237 DXILResourceTypeMap &DRTM) {
238 // Column widths are arbitrary but match the widths DXC uses.
239 OS << ";\n; Resource Bindings:\n;\n";
240 OS << formatv(Fmt: "; {0,-30} {1,10} {2,7} {3,11} {4,7} {5,14} {6,9}\n", Vals: "Name",
241 Vals: "Type", Vals: "Format", Vals: "Dim", Vals: "ID", Vals: "HLSL Bind", Vals: "Count");
242 OS << formatv(
243 Fmt: "; {0,-+30} {1,-+10} {2,-+7} {3,-+11} {4,-+7} {5,-+14} {6,-+9}\n", Vals: "", Vals: "",
244 Vals: "", Vals: "", Vals: "", Vals: "", Vals: "");
245
246 // TODO: Do we want to sort these by binding or something like that?
247 for (const dxil::ResourceInfo &RI : DRM) {
248 if (!RI.hasBinding())
249 continue;
250 const dxil::ResourceTypeInfo &RTI = DRTM[RI.getHandleTy()];
251
252 dxil::ResourceClass RC = RTI.getResourceClass();
253 StringRef Name(RI.getName());
254 StringRef Type(getRCName(RC));
255 StringRef Format(getFormatName(RI: RTI));
256 FormatResourceDimension Dim(RTI, RI.hasCounter());
257 FormatBindingID ID(RI, RTI);
258 FormatBindingLocation Bind(RI, RTI);
259 FormatBindingSize Count(RI);
260 OS << formatv(Fmt: "; {0,-30} {1,10} {2,7} {3,11} {4,7} {5,14} {6,9}\n", Vals&: Name,
261 Vals&: Type, Vals&: Format, Vals&: Dim, Vals&: ID, Vals&: Bind, Vals&: Count);
262 }
263 OS << ";\n";
264}
265
266namespace {
267class DXILModuleSlotTracker : public ModuleSlotTracker {
268public:
269 using ModuleSlotTracker::ModuleSlotTracker;
270 using ModuleSlotTracker::renumberMetadataForAssembly;
271};
272
273class DXILAssemblyAnnotationWriter : public llvm::AssemblyAnnotationWriter {
274private:
275 ModuleSlotTracker &MST;
276 AbstractSlotTrackerStorage &STS;
277 const DXILDebugInfoMap &DI;
278 DenseSet<const MDNode *> &EmittedMDNodes;
279
280public:
281 DXILAssemblyAnnotationWriter(ModuleSlotTracker &MST,
282 AbstractSlotTrackerStorage &STS,
283 const DXILDebugInfoMap &DI,
284 DenseSet<const MDNode *> &EmittedMDNodes)
285 : MST(MST), STS(STS), DI(DI), EmittedMDNodes(EmittedMDNodes) {}
286
287 void emitInstructionAnnot(const Instruction *OrigI,
288 formatted_raw_ostream &os) override {
289 if (const Instruction *I = &DI.getDXILInstruction(I: *OrigI); I != OrigI) {
290 os << "; DXIL: to be replaced with: ";
291 I->print(O&: os, MST);
292 os << "\n";
293 }
294 }
295
296 void emitMDNodeAnnot(const MDNode *N, formatted_raw_ostream &os) override {
297 EmittedMDNodes.insert(V: N);
298
299 if (const Metadata *NewMD = DI.MDReplace.lookup(Val: N)) {
300 if (const auto *NewN = dyn_cast<MDNode>(Val: NewMD))
301 STS.createMetadataSlot(NewN);
302
303 os << "; DXIL: ";
304 N->printAsOperand(OS&: os, MST);
305 os << ": to be replaced by: ";
306 NewMD->printAsOperand(OS&: os, MST);
307 os << "\n";
308 return;
309 }
310
311 if (const Metadata *ExtraMD = DI.MDExtra.lookup(Val: N)) {
312 if (const auto *ExtraN = dyn_cast<MDNode>(Val: ExtraMD))
313 STS.createMetadataSlot(ExtraN);
314
315 os << "; DXIL: ";
316 N->printAsOperand(OS&: os, MST);
317 os << ": additional data: ";
318 ExtraMD->printAsOperand(OS&: os, MST);
319 os << "\n";
320 return;
321 }
322 }
323};
324} // namespace
325
326static SmallVector<const MDNode *>
327collectAdditionalMetadata(Module &M, const DXILDebugInfoMap &DI) {
328 // Annotation metadata follows module metadata in the order its keys print.
329 // Follow replacement graphs to preserve that order in canonical output.
330 M.renumberMetadataForAssembly();
331
332 ModuleSlotTracker MST(&M);
333 AbstractSlotTrackerStorage *STS = nullptr;
334 MST.setProcessHook(
335 [&](AbstractSlotTrackerStorage *STS_, const Module *) { STS = STS_; });
336 MDNode::get(Context&: M.getContext(), MDs: {})->print(OS&: llvm::nulls(), MST);
337 assert(STS && "Slot tracker storage should have been initialised");
338
339 DenseSet<const Metadata *> ReplacementMetadata;
340 for (auto [_, Replacement] : DI.MDReplace)
341 ReplacementMetadata.insert(V: Replacement);
342
343 SmallVector<std::pair<unsigned, const MDNode *>> OriginalNodes;
344 DenseSet<const MDNode *> Queued;
345 auto AddOriginal = [&](const Metadata *MD) {
346 const auto *N = dyn_cast<MDNode>(Val: MD);
347 if (!N || ReplacementMetadata.contains(V: N) || !Queued.insert(V: N).second)
348 return;
349 OriginalNodes.emplace_back(Args: STS->getMetadataSlot(N), Args&: N);
350 };
351 for (auto [Original, _] : DI.MDReplace)
352 AddOriginal(Original);
353 for (auto [Original, _] : DI.MDExtra)
354 AddOriginal(Original);
355 llvm::sort(C&: OriginalNodes);
356
357 SmallVector<const MDNode *> Worklist;
358 for (auto [_, N] : OriginalNodes)
359 Worklist.push_back(Elt: N);
360
361 SmallVector<const MDNode *> AdditionalMetadata;
362 auto AddAdditional = [&](const Metadata *MD) {
363 const auto *Root = dyn_cast_or_null<MDNode>(Val: MD);
364 if (!Root || Queued.contains(V: Root))
365 return;
366
367 AdditionalMetadata.push_back(Elt: Root);
368 SmallVector<const MDNode *> Nodes = {Root};
369 while (!Nodes.empty()) {
370 const MDNode *N = Nodes.pop_back_val();
371 if (!Queued.insert(V: N).second)
372 continue;
373 Worklist.push_back(Elt: N);
374 for (const MDOperand &Op : llvm::reverse(C: N->operands()))
375 if (const auto *OpNode = dyn_cast_or_null<MDNode>(Val: Op.get()))
376 Nodes.push_back(Elt: OpNode);
377 }
378 };
379
380 for (size_t I = 0; I != Worklist.size(); ++I) {
381 const MDNode *N = Worklist[I];
382 if (const Metadata *Replacement = DI.MDReplace.lookup(Val: N)) {
383 AddAdditional(Replacement);
384 continue;
385 }
386 AddAdditional(DI.MDExtra.lookup(Val: N));
387 }
388 return AdditionalMetadata;
389}
390
391static void prettyPrint(raw_ostream &OS, Module &M, const DXILResourceMap &DRM,
392 DXILResourceTypeMap &DRTM) {
393 formatted_raw_ostream FOS(OS);
394
395 prettyPrintResources(OS&: FOS, DRM, DRTM);
396
397 const DXILDebugInfoMap DI = collectDXILDebugInfo(M);
398 SmallVector<const MDNode *> AdditionalMetadata =
399 collectAdditionalMetadata(M, DI);
400 DXILModuleSlotTracker MST(&M);
401 MST.renumberMetadataForAssembly(AdditionalMetadata);
402 AbstractSlotTrackerStorage *STS = nullptr;
403 MST.setProcessHook(
404 [&](AbstractSlotTrackerStorage *STS_, const Module *) { STS = STS_; });
405 // Force initialisation. ModuleSlotTracker does not have a dedicated function
406 // for this so trigger it through a dummy print.
407 MDNode::get(Context&: M.getContext(), MDs: {})->print(OS&: llvm::nulls(), MST);
408 assert(STS && "Slot tracker storage should have been initialised");
409
410 DenseSet<const MDNode *> EmittedMDNodes;
411 DXILAssemblyAnnotationWriter DAAW(MST, *STS, DI, EmittedMDNodes);
412 M.print(OS&: FOS, AAW: &DAAW);
413
414 ModuleSlotTracker::MachineMDNodeListType MDNodes;
415 MST.collectMDNodes(L&: MDNodes);
416 std::sort(first: MDNodes.begin(), last: MDNodes.end(),
417 comp: [](const std::pair<unsigned, const MDNode *> &A,
418 const std::pair<unsigned, const MDNode *> &B) {
419 return A.first < B.first;
420 });
421 for (auto [_, MDNode] : MDNodes) {
422 if (EmittedMDNodes.contains(V: MDNode))
423 continue;
424 DAAW.emitMDNodeAnnot(N: MDNode, os&: FOS);
425 MDNode->print(OS&: FOS, MST);
426 FOS << "\n";
427 }
428}
429
430PreservedAnalyses DXILPrettyPrinterPass::run(Module &M,
431 ModuleAnalysisManager &MAM) {
432 const DXILResourceMap &DRM = MAM.getResult<DXILResourceAnalysis>(IR&: M);
433 DXILResourceTypeMap &DRTM = MAM.getResult<DXILResourceTypeAnalysis>(IR&: M);
434 prettyPrint(OS, M, DRM, DRTM);
435 return PreservedAnalyses::all();
436}
437
438namespace {
439class DXILPrettyPrinterLegacy : public llvm::ModulePass {
440 raw_ostream &OS; // raw_ostream to print to.
441
442public:
443 static char ID;
444
445 explicit DXILPrettyPrinterLegacy(raw_ostream &O) : ModulePass(ID), OS(O) {}
446
447 StringRef getPassName() const override { return "DXIL Pretty Printer"; }
448
449 bool runOnModule(Module &M) override;
450 void getAnalysisUsage(AnalysisUsage &AU) const override {
451 AU.addRequired<DXILResourceTypeWrapperPass>();
452 AU.addRequired<DXILResourceWrapperPass>();
453 }
454};
455} // namespace
456
457char DXILPrettyPrinterLegacy::ID = 0;
458INITIALIZE_PASS_BEGIN(DXILPrettyPrinterLegacy, "dxil-pretty-printer",
459 "DXIL Pretty Printer", true, false)
460INITIALIZE_PASS_DEPENDENCY(DXILResourceTypeWrapperPass)
461INITIALIZE_PASS_DEPENDENCY(DXILResourceWrapperPass)
462INITIALIZE_PASS_END(DXILPrettyPrinterLegacy, "dxil-pretty-printer",
463 "DXIL Pretty Printer", true, false)
464
465bool DXILPrettyPrinterLegacy::runOnModule(Module &M) {
466 const DXILResourceMap &DRM =
467 getAnalysis<DXILResourceWrapperPass>().getResourceMap();
468 DXILResourceTypeMap &DRTM =
469 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
470 prettyPrint(OS, M, DRM, DRTM);
471 return false;
472}
473
474ModulePass *llvm::createDXILPrettyPrinterLegacyPass(raw_ostream &OS) {
475 return new DXILPrettyPrinterLegacy(OS);
476}
477