LLVM 23.0.0git
DXILWriterPass.cpp
Go to the documentation of this file.
1//===- DXILWriterPass.cpp - Bitcode writing 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// DXILWriterPass implementation.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DXILWriterPass.h"
14#include "DXILBitcodeWriter.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DebugInfo.h"
25#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/PassManager.h"
30#include "llvm/Pass.h"
34
35using namespace llvm;
36using namespace llvm::dxil;
37
40
41namespace {
42class WriteDXILPass : public llvm::ModulePass {
43 raw_ostream &OS; // raw_ostream to print on
44
45public:
46 static char ID; // Pass identification, replacement for typeid
47 WriteDXILPass() : ModulePass(ID), OS(dbgs()) {
49 }
50
51 explicit WriteDXILPass(raw_ostream &o) : ModulePass(ID), OS(o) {
53 }
54
55 StringRef getPassName() const override { return "Bitcode Writer"; }
56
57 bool runOnModule(Module &M) override {
58 const auto DIMap = DXILDebugInfoPass::run(M);
59 WriteDXILToFile(M, OS, DIMap);
60 return false;
61 }
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
63 AU.setPreservesAll();
64 }
65};
66
67static void legalizeLifetimeIntrinsics(Module &M) {
68 LLVMContext &Ctx = M.getContext();
69 Type *I64Ty = IntegerType::get(Ctx, 64);
70 Type *PtrTy = PointerType::get(Ctx, 0);
71 Intrinsic::ID LifetimeIIDs[2] = {Intrinsic::lifetime_start,
72 Intrinsic::lifetime_end};
73 for (Intrinsic::ID &IID : LifetimeIIDs) {
74 Function *F = M.getFunction(Intrinsic::getName(IID, {PtrTy}, &M));
75 if (!F)
76 continue;
77
78 // Get or insert an LLVM 3.7-compliant lifetime intrinsic function of the
79 // form `void @llvm.lifetime.[start/end](i64, ptr)` with the NoUnwind
80 // attribute
81 AttributeList Attr;
82 Attr = Attr.addFnAttribute(Ctx, Attribute::NoUnwind);
83 FunctionCallee LifetimeCallee = M.getOrInsertFunction(
84 Intrinsic::getBaseName(IID), Attr, Type::getVoidTy(Ctx), I64Ty, PtrTy);
85
86 // Replace all calls to lifetime intrinsics with calls to the
87 // LLVM 3.7-compliant version of the lifetime intrinsic
88 for (User *U : make_early_inc_range(F->users())) {
90 assert(CI &&
91 "Expected user of a lifetime intrinsic function to be a CallInst");
92
93 // LLVM 3.7 lifetime intrinics require an i8* operand, so we insert
94 // a bitcast to ensure that is the case
95 Value *PtrOperand = CI->getArgOperand(0);
96 PointerType *PtrOpPtrTy = cast<PointerType>(PtrOperand->getType());
97 Value *NoOpBitCast = CastInst::Create(Instruction::BitCast, PtrOperand,
98 PtrOpPtrTy, "", CI->getIterator());
99
100 // LLVM 3.7 lifetime intrinsics have an explicit size operand, whose value
101 // we can obtain from the pointer operand which must be an AllocaInst (as
102 // of https://github.com/llvm/llvm-project/pull/149310)
103 AllocaInst *AI = dyn_cast<AllocaInst>(PtrOperand);
104 assert(AI &&
105 "The pointer operand of a lifetime intrinsic call must be an "
106 "AllocaInst");
107 std::optional<TypeSize> AllocSize =
109 assert(AllocSize.has_value() &&
110 "Expected the allocation size of AllocaInst to be known");
111 CallInst *NewCI = CallInst::Create(
112 LifetimeCallee,
113 {ConstantInt::get(I64Ty, AllocSize.value().getFixedValue()),
114 NoOpBitCast},
115 "", CI->getIterator());
117 NewCI->addParamAttr(1, ParamAttr);
118
119 CI->eraseFromParent();
120 }
121
122 F->eraseFromParent();
123 }
124}
125
126static void removeLifetimeIntrinsics(Module &M) {
127 Intrinsic::ID LifetimeIIDs[2] = {Intrinsic::lifetime_start,
128 Intrinsic::lifetime_end};
129 for (Intrinsic::ID &IID : LifetimeIIDs) {
130 Function *F = M.getFunction(Intrinsic::getBaseName(IID));
131 if (!F)
132 continue;
133
134 for (User *U : make_early_inc_range(F->users())) {
136 assert(CI && "Expected user of lifetime function to be a CallInst");
138 assert(BCI && "Expected pointer operand of CallInst to be a BitCastInst");
139 CI->eraseFromParent();
140 BCI->eraseFromParent();
141 }
142 F->eraseFromParent();
143 }
144}
145
146static void replaceNamedMetadataArray(Module &M, StringRef Name,
147 ArrayRef<Metadata *> NewOps) {
148 NamedMDNode *NMD = M.getNamedMetadata(Name);
149 if (!NMD)
150 return;
151 NMD->eraseFromParent();
152 M.getOrInsertNamedMetadata(Name)->addOperand(
153 MDTuple::get(M.getContext(), NewOps));
154}
155
156class EmbedDXILPass : public llvm::ModulePass {
157 std::string writeModule(Module &M, bool HasDebugInfo, bool WriteDebug) {
158 std::string Data;
159 llvm::raw_string_ostream OS(Data);
160
161 if (HasDebugInfo) {
162 if (WriteDebug) {
163 // Replace dx.source metadata nodes with stubs.
164 // TODO: Add /Qsource_in_debug_module flag to enable/disable this.
165 LLVMContext &Ctx = M.getContext();
166 MDString *EmptyString = MDString::get(Ctx, "");
167 replaceNamedMetadataArray(M, "dx.source.contents",
168 {EmptyString, EmptyString});
169 replaceNamedMetadataArray(M, "dx.source.defines", {});
170 replaceNamedMetadataArray(M, "dx.source.mainFileName", {EmptyString});
171 replaceNamedMetadataArray(M, "dx.source.args", {});
172 } else {
173 // If we have an ILDB part, strip DXIL from all debug info.
175
176 // Also, manually remove debug version flags and dx.source nodes.
177 if (NamedMDNode *Flags = M.getModuleFlagsMetadata()) {
179 M.getModuleFlagsMetadata(FlagEntries);
180 Flags->eraseFromParent();
181 for (llvm::Module::ModuleFlagEntry &Entry : FlagEntries) {
182 if (Entry.Key->getString() == "Dwarf Version" ||
183 Entry.Key->getString() == "Debug Info Version") {
184 continue;
185 }
186 M.addModuleFlag(Entry.Behavior, Entry.Key->getString(), Entry.Val);
187 }
188 }
189 for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata()))
190 if (NMD.getName().starts_with("dx.source"))
191 NMD.eraseFromParent();
192 }
193 } else {
194#ifdef EXPENSIVE_CHECKS
195 assert(
196 StripDebugInfo(M) == false &&
197 "The module must not contain any debug info here."
198 "Shader modules with debug info must have !DICompileUnit metadata.");
199#endif
200 }
201 const auto DIMap = DXILDebugInfoPass::run(M);
202 WriteDXILToFile(M, OS, DIMap);
203 return Data;
204 }
205
206 GlobalVariable *createSectionGlobal(Module &M, StringRef Data,
207 StringRef GlobalName,
208 StringRef SectionName) {
209 Constant *ModuleConstant =
211 auto *GV = new llvm::GlobalVariable(M, ModuleConstant->getType(), true,
213 ModuleConstant, GlobalName);
214 GV->setSection(SectionName);
215 GV->setAlignment(Align(4));
216 return GV;
217 }
218
219public:
220 static char ID; // Pass identification, replacement for typeid
221 EmbedDXILPass() : ModulePass(ID) {
223 }
224
225 StringRef getPassName() const override { return "DXIL Embedder"; }
226
227 bool runOnModule(Module &M) override {
228 // Perform late legalization of lifetime intrinsics that would otherwise
229 // fail the Module Verifier if performed in an earlier pass
230 legalizeLifetimeIntrinsics(M);
231
232 bool HasDebugInfo = !M.debug_compile_units().empty();
233
234 // Enable EmbedDebug if there is debug info, but it is not being written
235 // to a PDB file.
236 if (HasDebugInfo && !EmbedDebug && PdbDebugPath.empty())
237 EmbedDebug = true;
238 if (!HasDebugInfo && EmbedDebug)
240 "Missing debug info for embedding into the container");
241 // TODO: move this check to DXContainerPDB.cpp when /Zs is implemented.
242 if (!HasDebugInfo && !PdbDebugPath.empty())
243 reportFatalUsageError("Missing debug info for writing to the PDB file");
244
245 std::string ILDBData;
246 if (HasDebugInfo) {
247 // Write DXIL with debug info to ILDB part.
248 // Clone the module to avoid alternating it with DebugInfoPass
249 // before stripping the debug info later.
250 ILDBData =
251 writeModule(*llvm::CloneModule(M), HasDebugInfo, /*WriteDebug=*/true);
252 }
253
254 // Clone the module to save dx.source metadata nodes from stripping, as they
255 // are needed for DXILMetadataAnalysisWrapperPass.
256 std::string DXILData =
257 writeModule(*llvm::CloneModule(M), HasDebugInfo, /*WriteDebug=*/false);
258
259 // We no longer need lifetime intrinsics after bitcode serialization, so we
260 // simply remove them to keep the Module Verifier happy after our
261 // not-so-legal legalizations
262 removeLifetimeIntrinsics(M);
263
265 if (HasDebugInfo) {
266 // Create a GV after both parts are written, otherwise it gets
267 // added to DXIL when `writeModule` is called the second time.
268 Globals.emplace_back(createSectionGlobal(M, ILDBData, "dx.ildb", "ILDB"));
269 }
270 Globals.emplace_back(createSectionGlobal(M, DXILData, "dx.dxil", "DXIL"));
271 appendToCompilerUsed(M, Globals);
272 return true;
273 }
274
275 void getAnalysisUsage(AnalysisUsage &AU) const override {
276 AU.setPreservesAll();
277 }
278};
279} // namespace
280
281char WriteDXILPass::ID = 0;
282INITIALIZE_PASS_BEGIN(WriteDXILPass, "dxil-write-bitcode", "Write Bitcode",
283 false, true)
285INITIALIZE_PASS_END(WriteDXILPass, "dxil-write-bitcode", "Write Bitcode", false,
286 true)
287
289 return new WriteDXILPass(Str);
290}
291
292char EmbedDXILPass::ID = 0;
293INITIALIZE_PASS(EmbedDXILPass, "dxil-embed", "Embed DXIL", false, true)
294
295ModulePass *llvm::createDXILEmbedderPass() { return new EmbedDXILPass(); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
@ ParamAttr
This file contains the declarations for the subclasses of Constant, which represent the different fla...
cl::opt< std::string > PdbDebugPath("dx-pdb-path", cl::desc("Write debug information to the given file, or automatically " "named file in directory when ending in '/'"), cl::value_desc("filename"))
cl::opt< std::string > PdbDebugPath
cl::opt< bool > EmbedDebug
This file provides a bitcode writing pass.
This file defines the DenseMap class.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
cl::opt< bool > EmbedDebug("dx-embed-debug", cl::desc("Embed PDB in shader container"))
#define F(x, y, z)
Definition MD5.cpp:54
Machine Check Debug Module
This is the interface to build a ModuleSummaryIndex for a 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
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some templates that are useful if you are working with the STL at all.
an instruction to allocate memory on the stack
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
This class represents a no-op cast from one type to another.
AttributeSet getParamAttributes(unsigned ArgNo) const
Return the param attributes for this call.
Value * getArgOperand(unsigned i) const
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
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
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1511
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
Legacy wrapper pass to provide the ModuleSummaryIndex object.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A tuple of MDNodes.
Definition Metadata.h:1753
LLVM_ABI StringRef getName() const
LLVM_ABI void eraseFromParent()
Drop all references and remove the node from parent module.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
reference emplace_back(ArgTypes &&... Args)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
DXILDebugInfoMap run(Module &M)
void WriteDXILToFile(const Module &M, raw_ostream &Out, const DXILDebugInfoMap &DebugInfo)
Write the specified module to the specified raw output stream.
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
ModulePass * createDXILWriterPass(raw_ostream &Str)
Create and return a pass that writes the module to the specified ostream.
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:633
LLVM_ABI size_t writeModule(const Module &M, uint8_t *Dest, size_t MaxSize)
Fuzzer friendly interface for the llvm bitcode printer.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
void initializeEmbedDXILPassPass(PassRegistry &)
Initializer for dxil embedder pass.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
ModulePass * createDXILEmbedderPass()
Create and return a pass that writes the module to a global variable in the module for later emission...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void initializeWriteDXILPassPass(PassRegistry &)
Initializer for dxil writer pass.
LLVM_ABI std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177