LLVM 24.0.0git
DXILContainerPDB.cpp
Go to the documentation of this file.
1//===- DXILContainerPDB.cpp - DirectX PDB writer 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#include "DirectX.h"
11#include "llvm/ADT/ScopeExit.h"
12#include "llvm/ADT/StringSet.h"
18#include "llvm/IR/Analysis.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/Module.h"
21#include "llvm/IR/PassManager.h"
23#include "llvm/Pass.h"
29
30using namespace llvm;
31
32namespace {
33
34class DXILContainerPDBImpl : MCDXContainerBaseWriter {
35 Module *M = nullptr;
37
38 void reset() {
39 M = nullptr;
40 Parts.clear();
41 }
42
43public:
44 bool shouldSkipSection(StringRef SectionName, size_t SectionSize) override;
45 ArrayRef<MCDXContainerPart> collectParts() override;
46 bool runOnModule(Module &M);
47};
48
49class DXILContainerPDBLegacy : public ModulePass {
50public:
51 static char ID;
52 DXILContainerPDBLegacy() : ModulePass(ID) {}
53
54 StringRef getPassName() const override { return "DirectX PDB Emitter"; }
55
56 bool runOnModule(Module &M) override;
57
58 void getAnalysisUsage(AnalysisUsage &AU) const override {
59 AU.setPreservesAll();
60 }
61};
62
63} // namespace
64
65bool DXILContainerPDBImpl::shouldSkipSection(StringRef SectionName,
66 size_t SectionSize) {
67 if (MCDXContainerBaseWriter::shouldSkipSection(SectionName, SectionSize))
68 return true;
69 if (dxil::SlimDebug && SectionName == "ILDB")
70 return true;
71
72 // Skip sections that are irrelevant for debug info.
73 static const StringSet<> DebugSections{"ILDB", "ILDN", "HASH", "PDBI",
74 "SRCI", "STAT", "RDAT", "VERS"};
75 return !DebugSections.contains(SectionName);
76}
77
79 if (GV.hasInitializer())
80 if (const auto *Data =
82 return Data->getRawDataValues();
83 return {};
84}
85
86ArrayRef<MCDXContainerPart> DXILContainerPDBImpl::collectParts() {
87 Parts.clear();
88 for (const GlobalVariable &GV : M->globals()) {
89 StringRef Name = GV.getSection();
90 StringRef Data = getGlobalData(GV);
91
92 if (Data.empty())
93 continue;
94 if (shouldSkipSection(Name, Data.size()))
95 continue;
96
97 Parts.push_back({Name, Data});
98 }
99 return Parts;
100}
101
103 Constant *Content =
104 ConstantDataArray::getString(M.getContext(), Data, /*AddNull*/ false);
105 auto *GV =
106 new GlobalVariable(M, Content->getType(), true,
107 GlobalValue::PrivateLinkage, Content, "dx.priv");
108 GV->setSection("PRIV");
109 GV->setAlignment(Align(1));
110 return GV;
111}
112
113bool DXILContainerPDBImpl::runOnModule(Module &M) {
114 llvm::scope_exit Cleanup([&]() { reset(); });
115 this->M = &M;
116
117 SmallString<128> DebugFileName;
118 ArrayRef<char> ModuleHash;
119 for (const GlobalVariable &GV : M.globals()) {
120 if (GV.getSection() == PdbFileNameSectionName) {
121 assert(DebugFileName.empty() && "Duplicate PDBNAME section");
122 DebugFileName = getGlobalData(GV);
123 } else if (GV.getSection() == ModuleHashSectionName) {
124 assert(ModuleHash.empty() && "Duplicate PBDHASH section");
125 StringRef Data = getGlobalData(GV);
126 ModuleHash = ArrayRef(Data.data(), Data.size());
127 }
128 }
129
130 // PDB emission was not requested.
131 if (DebugFileName.empty() && !dxil::PdbInPrivate)
132 return false;
133 if (ModuleHash.empty())
134 report_fatal_error("Module hash for PDB not found");
135
136 bool DeleteAfterRead = false;
137 if (DebugFileName.empty()) {
138 if (std::error_code EC =
139 sys::fs::createTemporaryFile("dxil", "pdb", DebugFileName))
140 reportFatalInternalError("Failed to create temporary PDB file");
141 DeleteAfterRead = true;
142 }
143 llvm::scope_exit FileCleanup([&]() {
144 if (DeleteAfterRead)
145 sys::fs::remove(DebugFileName);
146 });
147
149 pdb::PDBFileBuilder Builder(Allocator);
150
151 // DirectXShaderCompiler uses block size 512.
152 if (Error Err = Builder.initialize(512))
153 reportFatalInternalError(std::move(Err));
154
155 // Reserved streams that should be empty.
156 static_assert(pdb::kSpecialStreamCount == 5 &&
157 "First 5 streams should be empty in DirectX PDB file");
158 for (uint32_t I = 0; I < pdb::kSpecialStreamCount; ++I) {
159 if (auto Err = Builder.getMsfBuilder().addStream(0).takeError())
160 reportFatalInternalError(std::move(Err));
161 }
162
163 // Add DXContainer stream.
164 if (auto Err = Builder.getMsfBuilder().addStream(0).takeError())
165 reportFatalInternalError(std::move(Err));
166
167 // InfoStream must be filled. Bitcode hash from HASH part is used for PDB
168 // GUID.
169 codeview::GUID PdbGuid;
170 assert(ModuleHash.size() == std::size(PdbGuid.Guid) &&
171 "Module hash length must be match GUID length");
172 std::copy_n(ModuleHash.begin(), std::size(PdbGuid.Guid), PdbGuid.Guid);
173
174 auto &InfoBuilder = Builder.getInfoBuilder();
175 InfoBuilder.setAge(1);
176 InfoBuilder.setGuid(PdbGuid);
177 InfoBuilder.setSignature(0);
178 InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
179
180 // Write DXContainer.
181 raw_svector_ostream OS(*Builder.getDXContainerData());
182 write(OS, M.getTargetTriple());
183
184 // Write PDB file.
185 codeview::GUID IgnoredOutGuid;
186 {
187 // FIXME(sandboxing): Remove this by routing output through OutputBackend.
188 auto BypassSandbox = sys::sandbox::scopedDisable();
189 if (Error Err = Builder.commit(DebugFileName, &IgnoredOutGuid))
190 reportFatalUsageError("Couldn't write to PDB file: " +
191 Twine(toString(std::move(Err))));
192 }
193
195 return false;
196
197 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
198 M.getContext().getVirtualFileSystem().getBufferForFile(
199 DebugFileName, /*FileSize=*/-1, /*RequiresNullTerminator=*/false,
200 /*IsVolatile=*/false, /*IsText=*/false);
201 if (!Buf)
202 reportFatalInternalError("Failed to read PDB for PRIV embedding");
203
204 appendToCompilerUsed(M, createPrivateDataGlobal(M, (*Buf)->getBuffer()));
205
206 return true;
207}
208
209char DXILContainerPDBLegacy::ID = 0;
210INITIALIZE_PASS(DXILContainerPDBLegacy, "dxil-container-pdb",
211 "DirectX PDB Emitter", false, true)
212
214 return new DXILContainerPDBLegacy();
215}
216
217bool DXILContainerPDBLegacy::runOnModule(Module &M) {
218 DXILContainerPDBImpl Impl;
219 return Impl.runOnModule(M);
220}
221
224 DXILContainerPDBImpl Impl;
225 Impl.runOnModule(M);
226 return PreservedAnalyses::all();
227}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getGlobalData(const GlobalVariable &GV)
static GlobalVariable * createPrivateDataGlobal(Module &M, StringRef Data)
ManagedStatic< HTTPClientCleanup > Cleanup
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
Basic Register Allocator
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
StringSet - A set-like wrapper for the StringMap.
Defines the virtual file system interface vfs::FileSystem.
void setPreservesAll()
Set by analyses that do not transform their input at all.
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.
This is an important base class in LLVM.
Definition Constant.h:44
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
virtual bool shouldSkipSection(StringRef SectionName, size_t SectionSize)
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
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
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool contains(StringRef key) const
Check if the set contains the given key.
Definition StringSet.h:60
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
Pass manager infrastructure for declaring and invalidating analyses.
cl::opt< bool > SlimDebug
cl::opt< bool > PdbInPrivate
@ kSpecialStreamCount
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
LLVM_ABI std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None)
Create a file in the system temporary directory.
Definition Path.cpp:936
ScopedSetting scopedDisable()
Definition IOSandbox.h:36
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
scope_exit(Callable) -> scope_exit< Callable >
ModulePass * createDXILContainerPDBLegacyPass()
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
static constexpr StringLiteral ModuleHashSectionName
Contains module hash.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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 >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
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
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
uint8_t Guid[16]
Definition GUID.h:23