clang 20.0.0git
ObjectFilePCHContainerWriter.cpp
Go to the documentation of this file.
1//===--- ObjectFilePCHContainerWriter.cpp -----------------------------===//
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
10#include "CGDebugInfo.h"
11#include "CodeGenModule.h"
13#include "clang/AST/DeclObjC.h"
14#include "clang/AST/Expr.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
28#include "llvm/MC/TargetRegistry.h"
29#include "llvm/Object/COFF.h"
30#include "llvm/Support/Path.h"
31#include <memory>
32#include <utility>
33
34using namespace clang;
35
36#define DEBUG_TYPE "pchcontainer"
37
38namespace {
39class PCHContainerGenerator : public ASTConsumer {
40 DiagnosticsEngine &Diags;
41 const std::string MainFileName;
42 const std::string OutputFileName;
43 ASTContext *Ctx;
44 ModuleMap &MMap;
46 const HeaderSearchOptions &HeaderSearchOpts;
47 const PreprocessorOptions &PreprocessorOpts;
48 CodeGenOptions CodeGenOpts;
49 const TargetOptions TargetOpts;
50 LangOptions LangOpts;
51 std::unique_ptr<llvm::LLVMContext> VMContext;
52 std::unique_ptr<llvm::Module> M;
53 std::unique_ptr<CodeGen::CodeGenModule> Builder;
54 std::unique_ptr<raw_pwrite_stream> OS;
55 std::shared_ptr<PCHBuffer> Buffer;
56
57 /// Visit every type and emit debug info for it.
58 struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
60 ASTContext &Ctx;
61 DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
62 : DI(DI), Ctx(Ctx) {}
63
64 /// Determine whether this type can be represented in DWARF.
65 static bool CanRepresent(const Type *Ty) {
66 return !Ty->isDependentType() && !Ty->isUndeducedType();
67 }
68
69 bool VisitImportDecl(ImportDecl *D) {
71 DI.EmitImportDecl(*D);
72 return true;
73 }
74
75 bool VisitTypeDecl(TypeDecl *D) {
76 // TagDecls may be deferred until after all decls have been merged and we
77 // know the complete type. Pure forward declarations will be skipped, but
78 // they don't need to be emitted into the module anyway.
79 if (auto *TD = dyn_cast<TagDecl>(D))
80 if (!TD->isCompleteDefinition())
81 return true;
82
83 QualType QualTy = Ctx.getTypeDeclType(D);
84 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
86 return true;
87 }
88
89 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
90 QualType QualTy(D->getTypeForDecl(), 0);
91 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
93 return true;
94 }
95
96 bool VisitFunctionDecl(FunctionDecl *D) {
97 // Skip deduction guides.
98 if (isa<CXXDeductionGuideDecl>(D))
99 return true;
100
101 if (isa<CXXMethodDecl>(D))
102 // This is not yet supported. Constructing the `this' argument
103 // mandates a CodeGenFunction.
104 return true;
105
107 for (auto *i : D->parameters())
108 ArgTypes.push_back(i->getType());
109 QualType RetTy = D->getReturnType();
110 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
112 if (CanRepresent(FnTy.getTypePtr()))
113 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
114 return true;
115 }
116
117 bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
118 if (!D->getClassInterface())
119 return true;
120
121 bool selfIsPseudoStrong, selfIsConsumed;
123 ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
124 selfIsPseudoStrong, selfIsConsumed));
125 ArgTypes.push_back(Ctx.getObjCSelType());
126 for (auto *i : D->parameters())
127 ArgTypes.push_back(i->getType());
128 QualType RetTy = D->getReturnType();
129 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
131 if (CanRepresent(FnTy.getTypePtr()))
132 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
133 return true;
134 }
135 };
136
137public:
138 PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
139 const std::string &OutputFileName,
140 std::unique_ptr<raw_pwrite_stream> OS,
141 std::shared_ptr<PCHBuffer> Buffer)
142 : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
143 OutputFileName(OutputFileName), Ctx(nullptr),
145 FS(&CI.getVirtualFileSystem()),
146 HeaderSearchOpts(CI.getHeaderSearchOpts()),
147 PreprocessorOpts(CI.getPreprocessorOpts()),
148 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
149 OS(std::move(OS)), Buffer(std::move(Buffer)) {
150 // The debug info output isn't affected by CodeModel and
151 // ThreadModel, but the backend expects them to be nonempty.
152 CodeGenOpts.CodeModel = "default";
153 LangOpts.setThreadModel(LangOptions::ThreadModelKind::Single);
154 CodeGenOpts.DebugTypeExtRefs = true;
155 // When building a module MainFileName is the name of the modulemap file.
156 CodeGenOpts.MainFileName =
157 LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule;
158 CodeGenOpts.setDebugInfo(llvm::codegenoptions::FullDebugInfo);
159 CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
160 CodeGenOpts.DwarfVersion = CI.getCodeGenOpts().DwarfVersion;
161 CodeGenOpts.DebugCompilationDir =
163 CodeGenOpts.DebugPrefixMap =
165 CodeGenOpts.DebugStrictDwarf = CI.getCodeGenOpts().DebugStrictDwarf;
166 }
167
168 ~PCHContainerGenerator() override = default;
169
170 void Initialize(ASTContext &Context) override {
171 assert(!Ctx && "initialized multiple times");
172
173 Ctx = &Context;
174 VMContext.reset(new llvm::LLVMContext());
175 M.reset(new llvm::Module(MainFileName, *VMContext));
176 M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
177 Builder.reset(new CodeGen::CodeGenModule(
178 *Ctx, FS, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
179
180 // Prepare CGDebugInfo to emit debug info for a clang module.
181 auto *DI = Builder->getModuleDebugInfo();
182 StringRef ModuleName = llvm::sys::path::filename(MainFileName);
183 DI->setPCHDescriptor(
184 {ModuleName, "", OutputFileName, ASTFileSignature::createDISentinel()});
185 DI->setModuleMap(MMap);
186 }
187
188 bool HandleTopLevelDecl(DeclGroupRef D) override {
189 if (Diags.hasErrorOccurred())
190 return true;
191
192 // Collect debug info for all decls in this group.
193 for (auto *I : D)
194 if (!I->isFromASTFile()) {
195 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
196 DTV.TraverseDecl(I);
197 }
198 return true;
199 }
200
203 }
204
205 void HandleTagDeclDefinition(TagDecl *D) override {
206 if (Diags.hasErrorOccurred())
207 return;
208
209 if (D->isFromASTFile())
210 return;
211
212 // Anonymous tag decls are deferred until we are building their declcontext.
213 if (D->getName().empty())
214 return;
215
216 // Defer tag decls until their declcontext is complete.
217 auto *DeclCtx = D->getDeclContext();
218 while (DeclCtx) {
219 if (auto *D = dyn_cast<TagDecl>(DeclCtx))
220 if (!D->isCompleteDefinition())
221 return;
222 DeclCtx = DeclCtx->getParent();
223 }
224
225 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
226 DTV.TraverseDecl(D);
227 Builder->UpdateCompletedType(D);
228 }
229
230 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
231 if (Diags.hasErrorOccurred())
232 return;
233
234 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
235 Builder->getModuleDebugInfo()->completeRequiredType(RD);
236 }
237
238 void HandleImplicitImportDecl(ImportDecl *D) override {
240 Builder->getModuleDebugInfo()->EmitImportDecl(*D);
241 }
242
243 /// Emit a container holding the serialized AST.
244 void HandleTranslationUnit(ASTContext &Ctx) override {
245 assert(M && VMContext && Builder);
246 // Delete these on function exit.
247 std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
248 std::unique_ptr<llvm::Module> M = std::move(this->M);
249 std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
250
251 if (Diags.hasErrorOccurred())
252 return;
253
254 M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
255 M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
256
257 // PCH files don't have a signature field in the control block,
258 // but LLVM detects DWO CUs by looking for a non-zero DWO id.
259 // We use the lower 64 bits for debug info.
260
261 uint64_t Signature =
262 Buffer->Signature ? Buffer->Signature.truncatedValue() : ~1ULL;
263
264 Builder->getModuleDebugInfo()->setDwoId(Signature);
265
266 // Finalize the Builder.
267 if (Builder)
268 Builder->Release();
269
270 // Ensure the target exists.
271 std::string Error;
272 auto Triple = Ctx.getTargetInfo().getTriple();
273 if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
274 llvm::report_fatal_error(llvm::Twine(Error));
275
276 // Emit the serialized Clang AST into its own section.
277 assert(Buffer->IsComplete && "serialization did not complete");
278 auto &SerializedAST = Buffer->Data;
279 auto Size = SerializedAST.size();
280
281 if (Triple.isOSBinFormatWasm()) {
282 // Emit __clangast in custom section instead of named data segment
283 // to find it while iterating sections.
284 // This could be avoided if all data segements (the wasm sense) were
285 // represented as their own sections (in the llvm sense).
286 // TODO: https://github.com/WebAssembly/tool-conventions/issues/138
287 llvm::NamedMDNode *MD =
288 M->getOrInsertNamedMetadata("wasm.custom_sections");
289 llvm::Metadata *Ops[2] = {
290 llvm::MDString::get(*VMContext, "__clangast"),
291 llvm::MDString::get(*VMContext,
292 StringRef(SerializedAST.data(), Size))};
293 auto *NameAndContent = llvm::MDTuple::get(*VMContext, Ops);
294 MD->addOperand(NameAndContent);
295 } else {
296 auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
297 auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
298 auto *Data = llvm::ConstantDataArray::getString(
299 *VMContext, StringRef(SerializedAST.data(), Size),
300 /*AddNull=*/false);
301 auto *ASTSym = new llvm::GlobalVariable(
302 *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage,
303 Data, "__clang_ast");
304 // The on-disk hashtable needs to be aligned.
305 ASTSym->setAlignment(llvm::Align(8));
306
307 // Mach-O also needs a segment name.
308 if (Triple.isOSBinFormatMachO())
309 ASTSym->setSection("__CLANG,__clangast");
310 // COFF has an eight character length limit.
311 else if (Triple.isOSBinFormatCOFF())
312 ASTSym->setSection("clangast");
313 else
314 ASTSym->setSection("__clangast");
315 }
316
317 LLVM_DEBUG({
318 // Print the IR for the PCH container to the debug output.
321 Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
322 Ctx.getTargetInfo().getDataLayoutString(), M.get(),
323 BackendAction::Backend_EmitLL, FS,
324 std::make_unique<llvm::raw_svector_ostream>(Buffer));
325 llvm::dbgs() << Buffer;
326 });
327
328 // Use the LLVM backend to emit the pch container.
329 clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
330 LangOpts,
331 Ctx.getTargetInfo().getDataLayoutString(), M.get(),
332 BackendAction::Backend_EmitObj, FS, std::move(OS));
333
334 // Free the memory for the temporary buffer.
336 SerializedAST = std::move(Empty);
337 }
338};
339
340} // anonymous namespace
341
342std::unique_ptr<ASTConsumer>
343ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
344 CompilerInstance &CI, const std::string &MainFileName,
345 const std::string &OutputFileName,
346 std::unique_ptr<llvm::raw_pwrite_stream> OS,
347 std::shared_ptr<PCHBuffer> Buffer) const {
348 return std::make_unique<PCHContainerGenerator>(
349 CI, MainFileName, OutputFileName, std::move(OS), Buffer);
350}
Defines the clang::ASTContext interface.
Defines the Diagnostic-related interfaces.
const Decl * D
Defines the clang::Preprocessor interface.
const char * Data
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:73
virtual void HandleTranslationUnit(ASTContext &Ctx)
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
Definition: ASTConsumer.h:67
virtual void HandleTagDeclRequiredDefinition(const TagDecl *D)
This callback is invoked the first time each TagDecl is required to be complete.
Definition: ASTConsumer.h:77
virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D)
Handle the specified top-level declaration that occurred inside and ObjC container.
Definition: ASTConsumer.cpp:26
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void Initialize(ASTContext &Context)
Initialize - This is called to initialize the consumer, providing the ASTContext.
Definition: ASTConsumer.h:48
virtual void HandleImplicitImportDecl(ImportDecl *D)
Handle an ImportDecl that was implicitly created due to an inclusion directive.
Definition: ASTConsumer.cpp:28
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2206
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
llvm::SmallVector< std::pair< std::string, std::string >, 0 > DebugPrefixMap
std::string CodeModel
The code model to use (-mcmodel).
std::string DebugCompilationDir
The string to embed in debug information as the current working directory.
std::string MainFileName
The user provided name for the "main file", if non-empty.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:58
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
void EmitImportDecl(const ImportDecl &ID)
Emit an @import declaration.
This class organizes the cross-function state that is used while generating LLVM code.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TargetOptions & getTargetOpts()
HeaderSearchOptions & getHeaderSearchOpts()
CompilerInvocation & getInvocation()
PreprocessorOptions & getPreprocessorOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
CodeGenOptions & getCodeGenOpts()
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:805
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:786
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
bool hasErrorOccurred() const
Definition: Diagnostic.h:866
Represents a function declaration or definition.
Definition: Decl.h:1935
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:821
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4786
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:554
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
HeaderSearch & getHeaderSearchInfo() const
A (possibly-)qualified type.
Definition: Type.h:929
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
Represents a struct/union/class.
Definition: Decl.h:4148
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
const char * getDataLayoutString() const
Definition: TargetInfo.h:1271
Options for controlling the target.
Definition: TargetOptions.h:26
Represents a declaration of a type.
Definition: Decl.h:3370
The base class of the type hierarchy.
Definition: Type.h:1828
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8644
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
static ASTFileSignature createDISentinel()
Definition: Module.h:80
Extra information about a function prototype.
Definition: Type.h:5187