LLVM 24.0.0git
DXILTranslateMetadata.cpp
Go to the documentation of this file.
1//===- DXILTranslateMetadata.cpp - Pass to emit DXIL metadata -------------===//
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 "DXILRootSignature.h"
10#include "DXILShaderFlags.h"
12#include "DirectX.h"
13#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/Twine.h"
18#include "llvm/IR/BasicBlock.h"
19#include "llvm/IR/Constants.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/MDBuilder.h"
26#include "llvm/IR/Metadata.h"
27#include "llvm/IR/Module.h"
29#include "llvm/Pass.h"
33#include <cstdint>
34
35using namespace llvm;
36using namespace llvm::dxil;
37
38namespace {
39
40/// A simple wrapper of DiagnosticInfo that generates module-level diagnostic
41/// for the DXILValidateMetadata pass
42class DiagnosticInfoValidateMD : public DiagnosticInfo {
43private:
44 const Twine &Msg;
45 const Module &Mod;
46
47public:
48 /// \p M is the module for which the diagnostic is being emitted. \p Msg is
49 /// the message to show. Note that this class does not copy this message, so
50 /// this reference must be valid for the whole life time of the diagnostic.
51 DiagnosticInfoValidateMD(const Module &M,
52 const Twine &Msg LLVM_LIFETIME_BOUND,
54 : DiagnosticInfo(DK_Unsupported, Severity), Msg(Msg), Mod(M) {}
55
56 void print(DiagnosticPrinter &DP) const override {
57 DP << Mod.getName() << ": " << Msg << '\n';
58 }
59};
60
61static void reportError(Module &M, Twine Message,
62 DiagnosticSeverity Severity = DS_Error) {
63 M.getContext().diagnose(DiagnosticInfoValidateMD(M, Message, Severity));
64}
65
66static void reportLoopError(Module &M, Twine Message,
67 DiagnosticSeverity Severity = DS_Error) {
68 reportError(M, Twine("Invalid \"llvm.loop\" metadata: ") + Message, Severity);
69}
70
71enum class EntryPropsTag {
72 ShaderFlags = 0,
73 GSState,
74 DSState,
75 HSState,
76 NumThreads,
77 AutoBindingSpace,
78 RayPayloadSize,
79 RayAttribSize,
80 ShaderKind,
81 MSState,
82 ASStateTag,
83 WaveSize,
84 EntryRootSig,
85 WaveRange = 23,
86};
87
88} // namespace
89
91 DXILResourceTypeMap &DRTM) {
92 LLVMContext &Context = M.getContext();
93
94 for (ResourceInfo &RI : DRM)
95 if (RI.hasBinding() && !RI.hasSymbol())
96 RI.createSymbol(M,
97 DRTM[RI.getHandleTy()].createElementStruct(RI.getName()));
98
99 SmallVector<Metadata *> SRVs, UAVs, CBufs, Smps;
100 for (const ResourceInfo &RI : DRM.srvs())
101 if (RI.hasBinding())
102 SRVs.push_back(RI.getAsMetadata(M, DRTM[RI.getHandleTy()]));
103 for (const ResourceInfo &RI : DRM.uavs())
104 if (RI.hasBinding())
105 UAVs.push_back(RI.getAsMetadata(M, DRTM[RI.getHandleTy()]));
106 for (const ResourceInfo &RI : DRM.cbuffers())
107 if (RI.hasBinding())
108 CBufs.push_back(RI.getAsMetadata(M, DRTM[RI.getHandleTy()]));
109 for (const ResourceInfo &RI : DRM.samplers())
110 if (RI.hasBinding())
111 Smps.push_back(RI.getAsMetadata(M, DRTM[RI.getHandleTy()]));
112
113 Metadata *SRVMD = SRVs.empty() ? nullptr : MDNode::get(Context, SRVs);
114 Metadata *UAVMD = UAVs.empty() ? nullptr : MDNode::get(Context, UAVs);
115 Metadata *CBufMD = CBufs.empty() ? nullptr : MDNode::get(Context, CBufs);
116 Metadata *SmpMD = Smps.empty() ? nullptr : MDNode::get(Context, Smps);
117
118 if (DRM.empty())
119 return nullptr;
120
121 NamedMDNode *ResourceMD = M.getOrInsertNamedMetadata("dx.resources");
122 ResourceMD->addOperand(
123 MDNode::get(M.getContext(), {SRVMD, UAVMD, CBufMD, SmpMD}));
124
125 return ResourceMD;
126}
127
129 switch (Env) {
130 case Triple::Pixel:
131 return "ps";
132 case Triple::Vertex:
133 return "vs";
134 case Triple::Geometry:
135 return "gs";
136 case Triple::Hull:
137 return "hs";
138 case Triple::Domain:
139 return "ds";
140 case Triple::Compute:
141 return "cs";
142 case Triple::Library:
143 return "lib";
144 case Triple::Mesh:
145 return "ms";
147 return "as";
149 return "rootsig";
150 default:
151 break;
152 }
153 llvm_unreachable("Unsupported environment for DXIL generation.");
154}
155
159
164 ConstantInt::get(Type::getInt32Ty(Ctx), static_cast<int>(Tag))));
165 switch (Tag) {
166 case EntryPropsTag::ShaderFlags:
168 ConstantInt::get(Type::getInt64Ty(Ctx), Value)));
169 break;
170 case EntryPropsTag::ShaderKind:
172 ConstantInt::get(Type::getInt32Ty(Ctx), Value)));
173 break;
174 case EntryPropsTag::GSState:
175 case EntryPropsTag::DSState:
176 case EntryPropsTag::HSState:
177 case EntryPropsTag::NumThreads:
178 case EntryPropsTag::AutoBindingSpace:
179 case EntryPropsTag::RayPayloadSize:
180 case EntryPropsTag::RayAttribSize:
181 case EntryPropsTag::MSState:
182 case EntryPropsTag::ASStateTag:
183 case EntryPropsTag::WaveSize:
184 case EntryPropsTag::EntryRootSig:
185 case EntryPropsTag::WaveRange:
186 llvm_unreachable("NYI: Unhandled entry property tag");
187 }
188 return MDVals;
189}
190
192 uint64_t EntryShaderFlags,
193 const ModuleMetadataInfo &MMDI) {
195 LLVMContext &Ctx = EP.Entry->getContext();
196 if (EntryShaderFlags != 0)
197 MDVals.append(getTagValueAsMetadata(EntryPropsTag::ShaderFlags,
198 EntryShaderFlags, Ctx));
199
200 if (EP.Entry != nullptr) {
201 // FIXME: support more props.
202 // See https://github.com/llvm/llvm-project/issues/57948.
203 // Add shader kind for lib entries.
206 MDVals.append(getTagValueAsMetadata(EntryPropsTag::ShaderKind,
207 getShaderStage(EP.ShaderStage), Ctx));
208
210 // Handle mandatory "hlsl.numthreads"
211 MDVals.emplace_back(ConstantAsMetadata::get(ConstantInt::get(
212 Type::getInt32Ty(Ctx), static_cast<int>(EntryPropsTag::NumThreads))));
213 Metadata *NumThreadVals[] = {ConstantAsMetadata::get(ConstantInt::get(
214 Type::getInt32Ty(Ctx), EP.NumThreadsX)),
215 ConstantAsMetadata::get(ConstantInt::get(
216 Type::getInt32Ty(Ctx), EP.NumThreadsY)),
217 ConstantAsMetadata::get(ConstantInt::get(
218 Type::getInt32Ty(Ctx), EP.NumThreadsZ))};
219 MDVals.emplace_back(MDNode::get(Ctx, NumThreadVals));
220
221 // Handle optional "hlsl.wavesize". The fields are optionally represented
222 // if they are non-zero.
223 if (EP.WaveSizeMin != 0) {
224 bool IsWaveRange = VersionTuple(6, 8) <= MMDI.ShaderModelVersion;
225 bool IsWaveSize =
226 !IsWaveRange && VersionTuple(6, 6) <= MMDI.ShaderModelVersion;
227
228 if (!IsWaveRange && !IsWaveSize) {
229 reportError(M, "Shader model 6.6 or greater is required to specify "
230 "the \"hlsl.wavesize\" function attribute");
231 return nullptr;
232 }
233
234 // A range is being specified if EP.WaveSizeMax != 0
235 if (EP.WaveSizeMax && !IsWaveRange) {
237 M, "Shader model 6.8 or greater is required to specify "
238 "wave size range values of the \"hlsl.wavesize\" function "
239 "attribute");
240 return nullptr;
241 }
242
243 EntryPropsTag Tag =
244 IsWaveSize ? EntryPropsTag::WaveSize : EntryPropsTag::WaveRange;
246 ConstantInt::get(Type::getInt32Ty(Ctx), static_cast<int>(Tag))));
247
249 ConstantInt::get(Type::getInt32Ty(Ctx), EP.WaveSizeMin))};
250 if (IsWaveRange) {
252 ConstantInt::get(Type::getInt32Ty(Ctx), EP.WaveSizeMax)));
254 ConstantInt::get(Type::getInt32Ty(Ctx), EP.WaveSizePref)));
255 }
256
257 MDVals.emplace_back(MDNode::get(Ctx, WaveSizeVals));
258 }
259 }
260 }
261
262 if (MDVals.empty())
263 return nullptr;
264 return MDNode::get(Ctx, MDVals);
265}
266
268 MDTuple *Signatures, MDNode *Resources,
269 MDTuple *Properties, LLVMContext &Ctx) {
270 // Each entry point metadata record specifies:
271 // * reference to the entry point function global symbol
272 // * unmangled name
273 // * list of signatures
274 // * list of resources
275 // * list of tag-value pairs of shader capabilities and other properties
276 Metadata *MDVals[5];
277 MDVals[0] =
278 EntryFn ? ValueAsMetadata::get(const_cast<Function *>(EntryFn)) : nullptr;
279 MDVals[1] = MDString::get(Ctx, EntryFn ? EntryFn->getName() : "");
280 MDVals[2] = Signatures;
281 MDVals[3] = Resources;
282 MDVals[4] = Properties;
283 return MDNode::get(Ctx, MDVals);
284}
285
287 MDTuple *Signatures, MDNode *MDResources,
288 const uint64_t EntryShaderFlags,
289 const ModuleMetadataInfo &MMDI) {
290 MDTuple *Properties = getEntryPropAsMetadata(M, EP, EntryShaderFlags, MMDI);
291 return constructEntryMetadata(EP.Entry, Signatures, MDResources, Properties,
292 EP.Entry->getContext());
293}
294
296 if (MMDI.ValidatorVersion.empty())
297 return;
298
299 LLVMContext &Ctx = M.getContext();
300 IRBuilder<> IRB(M);
301 Metadata *MDVals[2];
302 MDVals[0] =
304 MDVals[1] = ConstantAsMetadata::get(
305 IRB.getInt32(MMDI.ValidatorVersion.getMinor().value_or(0)));
306 NamedMDNode *ValVerNode = M.getOrInsertNamedMetadata("dx.valver");
307 // Set validator version obtained from DXIL Metadata Analysis pass
308 ValVerNode->clearOperands();
309 ValVerNode->addOperand(MDNode::get(Ctx, MDVals));
310}
311
313 const ModuleMetadataInfo &MMDI) {
314 LLVMContext &Ctx = M.getContext();
315 IRBuilder<> IRB(M);
316 Metadata *SMVals[3];
318 SMVals[0] = MDString::get(Ctx, getShortShaderStage(MMDI.ShaderProfile));
319 SMVals[1] = ConstantAsMetadata::get(IRB.getInt32(SM.getMajor()));
320 SMVals[2] = ConstantAsMetadata::get(IRB.getInt32(SM.getMinor().value_or(0)));
321 NamedMDNode *SMMDNode = M.getOrInsertNamedMetadata("dx.shaderModel");
322 SMMDNode->addOperand(MDNode::get(Ctx, SMVals));
323}
324
326 LLVMContext &Ctx = M.getContext();
327 IRBuilder<> IRB(M);
328 VersionTuple DXILVer = MMDI.DXILVersion;
329 Metadata *DXILVals[2];
330 DXILVals[0] = ConstantAsMetadata::get(IRB.getInt32(DXILVer.getMajor()));
331 DXILVals[1] =
332 ConstantAsMetadata::get(IRB.getInt32(DXILVer.getMinor().value_or(0)));
333 NamedMDNode *DXILVerMDNode = M.getOrInsertNamedMetadata("dx.version");
334 DXILVerMDNode->addOperand(MDNode::get(Ctx, DXILVals));
335}
336
338 uint64_t ShaderFlags) {
339 LLVMContext &Ctx = M.getContext();
340 MDTuple *Properties = nullptr;
341 if (ShaderFlags != 0) {
343 MDVals.append(
344 getTagValueAsMetadata(EntryPropsTag::ShaderFlags, ShaderFlags, Ctx));
345 Properties = MDNode::get(Ctx, MDVals);
346 }
347 // Library has an entry metadata with resource table metadata and all other
348 // MDNodes as null.
349 return constructEntryMetadata(nullptr, nullptr, RMD, Properties, Ctx);
350}
351
352static void translateBranchMetadata(Module &M, Instruction *BBTerminatorInst) {
353 MDNode *HlslControlFlowMD =
354 BBTerminatorInst->getMetadata("hlsl.controlflow.hint");
355
356 if (!HlslControlFlowMD)
357 return;
358
359 assert(HlslControlFlowMD->getNumOperands() == 2 &&
360 "invalid operands for hlsl.controlflow.hint");
361
362 MDBuilder MDHelper(M.getContext());
363
364 llvm::Metadata *HintsStr = MDHelper.createString("dx.controlflow.hints");
365 llvm::Metadata *HintsValue = MDHelper.createConstant(
366 mdconst::extract<ConstantInt>(HlslControlFlowMD->getOperand(1)));
367
368 MDNode *MDNode = llvm::MDNode::get(M.getContext(), {HintsStr, HintsValue});
369
370 BBTerminatorInst->setMetadata("dx.controlflow.hints", MDNode);
371 BBTerminatorInst->setMetadata("hlsl.controlflow.hint", nullptr);
372}
373
374// Determines if the metadata node will be compatible with DXIL's loop metadata
375// representation.
376//
377// Reports an error for compatible metadata that is ill-formed.
378static bool isLoopMDCompatible(Module &M, Metadata *MD) {
379 // DXIL only accepts the following loop hints:
380 std::array<StringLiteral, 3> ValidHintNames = {"llvm.loop.unroll.count",
381 "llvm.loop.unroll.disable",
382 "llvm.loop.unroll.full"};
383
384 MDNode *HintMD = dyn_cast<MDNode>(MD);
385 if (!HintMD || HintMD->getNumOperands() == 0)
386 return false;
387
388 auto *HintStr = dyn_cast<MDString>(HintMD->getOperand(0));
389 if (!HintStr)
390 return false;
391
392 if (!llvm::is_contained(ValidHintNames, HintStr->getString()))
393 return false;
394
395 auto ValidCountNode = [](MDNode *CountMD) -> bool {
396 if (CountMD->getNumOperands() == 2)
397 if (auto *Count = dyn_cast<ConstantAsMetadata>(CountMD->getOperand(1)))
398 if (isa<ConstantInt>(Count->getValue()))
399 return true;
400 return false;
401 };
402
403 if (HintStr->getString() == "llvm.loop.unroll.count") {
404 if (!ValidCountNode(HintMD)) {
405 reportLoopError(M, "\"llvm.loop.unroll.count\" must have 2 operands and "
406 "the second must be a constant integer");
407 return false;
408 }
409 } else if (HintMD->getNumOperands() != 1) {
410 reportLoopError(
411 M, "\"llvm.loop.unroll.disable\" and \"llvm.loop.unroll.full\" "
412 "must be provided as a single operand");
413 return false;
414 }
415
416 return true;
417}
418
419static void translateLoopMetadata(Module &M, Instruction *I, MDNode *BaseMD) {
420 // A distinct node has the self-referential form: !0 = !{ !0, ... }
421 auto IsDistinctNode = [](MDNode *Node) -> bool {
422 return Node && Node->getNumOperands() != 0 && Node == Node->getOperand(0);
423 };
424
425 // Set metadata to null to remove empty/ill-formed metadata from instruction
426 if (BaseMD->getNumOperands() == 0 || !IsDistinctNode(BaseMD))
427 return I->setMetadata("llvm.loop", nullptr);
428
429 // It is valid to have a chain of self-refential loop metadata nodes, as
430 // below. We will collapse these into just one when we reconstruct the
431 // metadata.
432 //
433 // Eg:
434 // !0 = !{!0, !1}
435 // !1 = !{!1, !2}
436 // !2 = !{!"llvm.loop.unroll.disable"}
437 //
438 // So, traverse down a potential self-referential chain
439 while (1 < BaseMD->getNumOperands() &&
440 IsDistinctNode(dyn_cast<MDNode>(BaseMD->getOperand(1))))
441 BaseMD = dyn_cast<MDNode>(BaseMD->getOperand(1));
442
443 // To reconstruct a distinct node we create a temporary node that we will
444 // then update to create a self-reference.
445 llvm::TempMDTuple TempNode = llvm::MDNode::getTemporary(M.getContext(), {});
446 SmallVector<Metadata *> CompatibleOperands = {TempNode.get()};
447
448 // Iterate and reconstruct the metadata nodes that contains any hints,
449 // stripping any unrecognized metadata.
451 for (auto &Op : Operands.drop_front())
452 if (isLoopMDCompatible(M, Op.get()))
453 CompatibleOperands.push_back(Op.get());
454
455 if (2 < CompatibleOperands.size())
456 reportLoopError(M, "Provided conflicting hints");
457
458 MDNode *CompatibleLoopMD = MDNode::get(M.getContext(), CompatibleOperands);
459 TempNode->replaceAllUsesWith(CompatibleLoopMD);
460
461 I->setMetadata("llvm.loop", CompatibleLoopMD);
462}
463
464using InstructionMDList = std::array<unsigned, 7>;
465
467 return {
468 M.getMDKindID("dx.nonuniform"), M.getMDKindID("dx.controlflow.hints"),
469 M.getMDKindID("dx.precise"), llvm::LLVMContext::MD_range,
470 llvm::LLVMContext::MD_alias_scope, llvm::LLVMContext::MD_noalias,
471 M.getMDKindID("llvm.loop")};
472}
473
475 // construct allowlist of valid metadata node kinds
476 InstructionMDList DXILCompatibleMDs = getCompatibleInstructionMDs(M);
477 unsigned char MDLoopKind = M.getContext().getMDKindID("llvm.loop");
478
479 for (Function &F : M) {
480 for (BasicBlock &BB : F) {
481 // This needs to be done first so that "hlsl.controlflow.hints" isn't
482 // removed in the allow-list below
483 translateBranchMetadata(M, BB.getTerminator());
484
485 for (auto &I : make_early_inc_range(BB)) {
487 if (MDNode *LoopMD = I.getMetadata(MDLoopKind))
488 translateLoopMetadata(M, &I, LoopMD);
489 I.dropUnknownNonDebugMetadata(DXILCompatibleMDs);
490 }
491 }
492 }
493}
494
495static void cleanModuleFlags(Module &M) {
496 NamedMDNode *MDFlags = M.getModuleFlagsMetadata();
497 if (!MDFlags)
498 return;
499
501 M.getModuleFlagsMetadata(FlagEntries);
502 bool Updated = false;
503 for (auto &Flag : FlagEntries) {
504 // llvm 3.7 only supports behavior up to AppendUnique.
505 if (Flag.Behavior <= Module::ModFlagBehavior::AppendUnique)
506 continue;
507 Flag.Behavior = Module::ModFlagBehavior::Warning;
508 Updated = true;
509 }
510
511 if (!Updated)
512 return;
513
514 MDFlags->eraseFromParent();
515
516 for (auto &Flag : FlagEntries)
517 M.addModuleFlag(Flag.Behavior, Flag.Key->getString(), Flag.Val);
518}
519
520using GlobalMDList = std::array<StringLiteral, 12>;
521
522// The following are compatible with DXIL but not emit with clang, they can
523// be added when applicable:
524// dx.typeAnnotations, dx.dxrPayloadAnnotations
526 "llvm.ident", "llvm.module.flags",
527 "dx.resources", "dx.valver",
528 "dx.shaderModel", "dx.version",
529 "dx.entryPoints", "dx.source.contents",
530 "dx.source.defines", "dx.source.mainFileName",
531 "dx.source.args", "dx.viewIdState"};
532
535 const ModuleShaderFlags &ShaderFlags,
536 const ModuleMetadataInfo &MMDI,
537 const ModuleSignatureInfo &SignatureInfo) {
538 LLVMContext &Ctx = M.getContext();
539 IRBuilder<> IRB(M);
540 SmallVector<MDNode *> EntryFnMDNodes;
541
542 emitValidatorVersionMD(M, MMDI);
544 emitDXILVersionTupleMD(M, MMDI);
545 NamedMDNode *NamedResourceMD = emitResourceMetadata(M, DRM, DRTM);
546 auto *ResourceMD =
547 (NamedResourceMD != nullptr) ? NamedResourceMD->getOperand(0) : nullptr;
548
550 // Get the combined shader flag mask of all functions in the library to be
551 // used as shader flags mask value associated with top-level library entry
552 // metadata.
553 uint64_t CombinedMask = ShaderFlags.getCombinedFlags();
554 EntryFnMDNodes.emplace_back(
555 emitTopLevelLibraryNode(M, ResourceMD, CombinedMask));
556 } else if (1 < MMDI.EntryPropertyVec.size())
557 reportError(M, "Non-library shader: One and only one entry expected");
558
559 for (const EntryProperties &EntryProp : MMDI.EntryPropertyVec) {
560 uint64_t EntryShaderFlags = 0;
562 EntryShaderFlags = ShaderFlags.getFunctionFlags(EntryProp.Entry);
563 if (EntryProp.ShaderStage != MMDI.ShaderProfile)
565 M, "Shader stage '" +
567 "' for entry '" + Twine(EntryProp.Entry->getName()) +
568 "' different from specified target profile '" +
570 "'"));
571 }
572 MDTuple *Signatures = nullptr;
573 if (const EntrySignature *Sig = SignatureInfo.get(EntryProp.Entry)) {
574 Signatures = Sig->getAsMetadata(Ctx, MMDI.ValidatorVersion);
575 // This module-level dependency state describes a single shader, not a
576 // concatenation of the independent signatures in a library.
577 if (MMDI.ShaderProfile != Triple::Library &&
578 (MMDI.ValidatorVersion.empty() ||
579 MMDI.ValidatorVersion == VersionTuple(0, 0) ||
580 MMDI.ValidatorVersion >= VersionTuple(1, 1)) &&
581 (Sig->InputVectors || Sig->OutputVectors)) {
582 auto State = Sig->getDependencyState(
583 ShaderFlags.getFunctionFlags(EntryProp.Entry).ViewID);
584 auto *StateMD = M.getOrInsertNamedMetadata("dx.viewIdState");
585 StateMD->clearOperands();
586 StateMD->addOperand(MDNode::get(
588 }
589 }
590 EntryFnMDNodes.emplace_back(emitEntryMD(
591 M, EntryProp, Signatures, ResourceMD, EntryShaderFlags, MMDI));
592 }
593
594 NamedMDNode *EntryPointsNamedMD =
595 M.getOrInsertNamedMetadata("dx.entryPoints");
596 for (auto *Entry : EntryFnMDNodes)
597 EntryPointsNamedMD->addOperand(Entry);
598
600
601 // Finally, strip all module metadata that is not explicitly specified in the
602 // allow-list
604
605 for (NamedMDNode &NamedMD : M.named_metadata())
606 if (!NamedMD.getName().starts_with("llvm.dbg.") &&
607 !llvm::is_contained(CompatibleNamedModuleMDs, NamedMD.getName()))
608 ToStrip.push_back(&NamedMD);
609
610 for (NamedMDNode *NamedMD : ToStrip)
611 NamedMD->eraseFromParent();
612}
613
616 DXILResourceMap &DRM = MAM.getResult<DXILResourceAnalysis>(M);
618 const ModuleShaderFlags &ShaderFlags = MAM.getResult<ShaderFlagsAnalysis>(M);
619 const dxil::ModuleMetadataInfo MMDI = MAM.getResult<DXILMetadataAnalysis>(M);
620
621 const auto &SignatureInfo = MAM.getResult<SignatureAnalysis>(M);
622 translateGlobalMetadata(M, DRM, DRTM, ShaderFlags, MMDI, SignatureInfo);
624
625 return PreservedAnalyses::all();
626}
627
628namespace {
629class DXILTranslateMetadataLegacy : public ModulePass {
630public:
631 static char ID; // Pass identification, replacement for typeid
632 explicit DXILTranslateMetadataLegacy() : ModulePass(ID) {}
633
634 StringRef getPassName() const override { return "DXIL Translate Metadata"; }
635
636 void getAnalysisUsage(AnalysisUsage &AU) const override;
637
638 bool runOnModule(Module &M) override;
639};
640} // namespace
641
642void DXILTranslateMetadataLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
645 AU.addRequired<ShaderFlagsAnalysisWrapper>();
647 AU.addRequired<RootSignatureAnalysisWrapper>();
648 AU.addRequired<SignatureAnalysisWrapper>();
649
653 AU.addPreserved<RootSignatureAnalysisWrapper>();
654 AU.addPreserved<SignatureAnalysisWrapper>();
655 AU.addPreserved<ShaderFlagsAnalysisWrapper>();
656}
657
658bool DXILTranslateMetadataLegacy::runOnModule(Module &M) {
659 DXILResourceMap &DRM =
660 getAnalysis<DXILResourceWrapperPass>().getResourceMap();
661 DXILResourceTypeMap &DRTM =
662 getAnalysis<DXILResourceTypeWrapperPass>().getResourceTypeMap();
663 const ModuleShaderFlags &ShaderFlags =
664 getAnalysis<ShaderFlagsAnalysisWrapper>().getShaderFlags();
666 getAnalysis<DXILMetadataAnalysisWrapperPass>().getModuleMetadata();
667
668 const auto &SignatureInfo =
669 getAnalysis<SignatureAnalysisWrapper>().getSignatureInfo();
670 translateGlobalMetadata(M, DRM, DRTM, ShaderFlags, MMDI, SignatureInfo);
672 return true;
673}
674
675char DXILTranslateMetadataLegacy::ID = 0;
676
678 return new DXILTranslateMetadataLegacy();
679}
680
681INITIALIZE_PASS_BEGIN(DXILTranslateMetadataLegacy, "dxil-translate-metadata",
682 "DXIL Translate Metadata", false, false)
688INITIALIZE_PASS_END(DXILTranslateMetadataLegacy, "dxil-translate-metadata",
689 "DXIL Translate Metadata", false, false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static Error reportError(StringRef Message)
#define LLVM_LIFETIME_BOUND
Definition Compiler.h:464
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Remove Unused Resources
static void translateLoopMetadata(Module &M, Instruction *I, MDNode *BaseMD)
static InstructionMDList getCompatibleInstructionMDs(llvm::Module &M)
static bool isLoopMDCompatible(Module &M, Metadata *MD)
static void emitDXILVersionTupleMD(Module &M, const ModuleMetadataInfo &MMDI)
static void emitValidatorVersionMD(Module &M, const ModuleMetadataInfo &MMDI)
static MDTuple * emitTopLevelLibraryNode(Module &M, MDNode *RMD, uint64_t ShaderFlags)
static MDTuple * getEntryPropAsMetadata(Module &M, const EntryProperties &EP, uint64_t EntryShaderFlags, const ModuleMetadataInfo &MMDI)
static void translateBranchMetadata(Module &M, Instruction *BBTerminatorInst)
static void translateGlobalMetadata(Module &M, DXILResourceMap &DRM, DXILResourceTypeMap &DRTM, const ModuleShaderFlags &ShaderFlags, const ModuleMetadataInfo &MMDI, const ModuleSignatureInfo &SignatureInfo)
static MDTuple * constructEntryMetadata(const Function *EntryFn, MDTuple *Signatures, MDNode *Resources, MDTuple *Properties, LLVMContext &Ctx)
static SmallVector< Metadata * > getTagValueAsMetadata(EntryPropsTag Tag, uint64_t Value, LLVMContext &Ctx)
static void translateInstructionMetadata(Module &M)
static GlobalMDList CompatibleNamedModuleMDs
static void cleanModuleFlags(Module &M)
static StringRef getShortShaderStage(Triple::EnvironmentType Env)
std::array< StringLiteral, 12 > GlobalMDList
static NamedMDNode * emitResourceMetadata(Module &M, DXILResourceMap &DRM, DXILResourceTypeMap &DRTM)
static uint32_t getShaderStage(Triple::EnvironmentType Env)
static MDTuple * emitEntryMD(Module &M, const EntryProperties &EP, MDTuple *Signatures, MDNode *MDResources, const uint64_t EntryShaderFlags, const ModuleMetadataInfo &MMDI)
std::array< unsigned, 7 > InstructionMDList
static void emitShaderModelVersionMD(Module &M, const ModuleMetadataInfo &MMDI)
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
ModuleAnalysisManager MAM
#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
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
Defines the llvm::VersionTuple class, which represents a version in the form major[....
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
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
iterator_range< iterator > samplers()
iterator_range< iterator > srvs()
iterator_range< iterator > cbuffers()
iterator_range< iterator > uavs()
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
This is the base abstract class for diagnostic reporting in the backend.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:465
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2947
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition MDBuilder.cpp:25
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
Definition MDBuilder.cpp:21
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1591
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
Tuple of metadata.
Definition Metadata.h:1496
Root of the metadata hierarchy.
Definition Metadata.h:64
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
@ AppendUnique
Appends the two values, which are required to be metadata nodes.
Definition Module.h:147
@ Warning
Emits a warning if two values disagree.
Definition Module.h:125
A tuple of MDNodes.
Definition Metadata.h:1797
LLVM_ABI void eraseFromParent()
Drop all references and remove the node from parent module.
LLVM_ABI MDNode * getOperand(unsigned i) const
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
LLVM_ABI void addOperand(MDNode *M)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
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
@ RootSignature
Definition Triple.h:413
@ Amplification
Definition Triple.h:412
static LLVM_ABI StringRef getEnvironmentTypeName(EnvironmentType Kind)
Get the canonical name for the Kind environment.
Definition Triple.cpp:405
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:514
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
Represents a version number in the form major[.minor[.subminor[.build]]].
unsigned getMajor() const
Retrieve the major version number.
bool empty() const
Determine whether this version information is empty (e.g., all version components are zero).
std::optional< unsigned > getMinor() const
Retrieve the minor version number, if provided.
const EntrySignature * get(const Function *F) const
Wrapper pass for the legacy pass manager.
Wrapper pass for the legacy pass manager.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
ModulePass * createDXILTranslateMetadataLegacyPass()
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...
Definition STLExtras.h:649
@ DK_Unsupported
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...
Definition Casting.h:547
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Triple::EnvironmentType ShaderStage
Triple::EnvironmentType ShaderProfile
SmallVector< EntryProperties > EntryPropertyVec