1 //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
11 #include "CGDebugInfo.h"
12 #include "CodeGenModule.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/RecursiveASTVisitor.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/CodeGen/BackendUtil.h"
20 #include "clang/Frontend/CodeGenOptions.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Lex/HeaderSearch.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Serialization/ASTWriter.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Bitcode/BitstreamReader.h"
27 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Object/COFF.h"
33 #include "llvm/Object/ObjectFile.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/TargetRegistry.h"
39 using namespace clang;
41 #define DEBUG_TYPE "pchcontainer"
44 class PCHContainerGenerator : public ASTConsumer {
45 DiagnosticsEngine &Diags;
46 const std::string MainFileName;
47 const std::string OutputFileName;
50 const HeaderSearchOptions &HeaderSearchOpts;
51 const PreprocessorOptions &PreprocessorOpts;
52 CodeGenOptions CodeGenOpts;
53 const TargetOptions TargetOpts;
54 const LangOptions LangOpts;
55 std::unique_ptr<llvm::LLVMContext> VMContext;
56 std::unique_ptr<llvm::Module> M;
57 std::unique_ptr<CodeGen::CodeGenModule> Builder;
58 std::unique_ptr<raw_pwrite_stream> OS;
59 std::shared_ptr<PCHBuffer> Buffer;
61 /// Visit every type and emit debug info for it.
62 struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
63 clang::CodeGen::CGDebugInfo &DI;
65 DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
68 /// Determine whether this type can be represented in DWARF.
69 static bool CanRepresent(const Type *Ty) {
70 return !Ty->isDependentType() && !Ty->isUndeducedType();
73 bool VisitImportDecl(ImportDecl *D) {
74 auto *Import = cast<ImportDecl>(D);
75 if (!Import->getImportedOwningModule())
76 DI.EmitImportDecl(*Import);
80 bool VisitTypeDecl(TypeDecl *D) {
81 // TagDecls may be deferred until after all decls have been merged and we
82 // know the complete type. Pure forward declarations will be skipped, but
83 // they don't need to be emitted into the module anyway.
84 if (auto *TD = dyn_cast<TagDecl>(D))
85 if (!TD->isCompleteDefinition())
88 QualType QualTy = Ctx.getTypeDeclType(D);
89 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
90 DI.getOrCreateStandaloneType(QualTy, D->getLocation());
94 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
95 QualType QualTy(D->getTypeForDecl(), 0);
96 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
97 DI.getOrCreateStandaloneType(QualTy, D->getLocation());
101 bool VisitFunctionDecl(FunctionDecl *D) {
102 if (isa<CXXMethodDecl>(D))
103 // This is not yet supported. Constructing the `this' argument
104 // mandates a CodeGenFunction.
107 SmallVector<QualType, 16> ArgTypes;
108 for (auto i : D->parameters())
109 ArgTypes.push_back(i->getType());
110 QualType RetTy = D->getReturnType();
111 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
112 FunctionProtoType::ExtProtoInfo());
113 if (CanRepresent(FnTy.getTypePtr()))
114 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
118 bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
119 if (!D->getClassInterface())
122 bool selfIsPseudoStrong, selfIsConsumed;
123 SmallVector<QualType, 16> ArgTypes;
124 ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
125 selfIsPseudoStrong, selfIsConsumed));
126 ArgTypes.push_back(Ctx.getObjCSelType());
127 for (auto i : D->parameters())
128 ArgTypes.push_back(i->getType());
129 QualType RetTy = D->getReturnType();
130 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
131 FunctionProtoType::ExtProtoInfo());
132 if (CanRepresent(FnTy.getTypePtr()))
133 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
139 PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
140 const std::string &OutputFileName,
141 std::unique_ptr<raw_pwrite_stream> OS,
142 std::shared_ptr<PCHBuffer> Buffer)
143 : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
144 OutputFileName(OutputFileName), Ctx(nullptr),
145 MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
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 CodeGenOpts.ThreadModel = "single";
154 CodeGenOpts.DebugTypeExtRefs = true;
155 CodeGenOpts.setDebugInfo(codegenoptions::FullDebugInfo);
156 CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
159 ~PCHContainerGenerator() override = default;
161 void Initialize(ASTContext &Context) override {
162 assert(!Ctx && "initialized multiple times");
165 VMContext.reset(new llvm::LLVMContext());
166 M.reset(new llvm::Module(MainFileName, *VMContext));
167 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
168 Builder.reset(new CodeGen::CodeGenModule(
169 *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
171 // Prepare CGDebugInfo to emit debug info for a clang module.
172 auto *DI = Builder->getModuleDebugInfo();
173 StringRef ModuleName = llvm::sys::path::filename(MainFileName);
174 DI->setPCHDescriptor({ModuleName, "", OutputFileName,
175 ASTFileSignature{{{~0U, ~0U, ~0U, ~0U, ~1U}}}});
176 DI->setModuleMap(MMap);
179 bool HandleTopLevelDecl(DeclGroupRef D) override {
180 if (Diags.hasErrorOccurred())
183 // Collect debug info for all decls in this group.
185 if (!I->isFromASTFile()) {
186 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
192 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
193 HandleTopLevelDecl(D);
196 void HandleTagDeclDefinition(TagDecl *D) override {
197 if (Diags.hasErrorOccurred())
200 if (D->isFromASTFile())
203 // Anonymous tag decls are deferred until we are building their declcontext.
204 if (D->getName().empty())
207 // Defer tag decls until their declcontext is complete.
208 auto *DeclCtx = D->getDeclContext();
210 if (auto *D = dyn_cast<TagDecl>(DeclCtx))
211 if (!D->isCompleteDefinition())
213 DeclCtx = DeclCtx->getParent();
216 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
218 Builder->UpdateCompletedType(D);
221 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
222 if (Diags.hasErrorOccurred())
225 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
226 Builder->getModuleDebugInfo()->completeRequiredType(RD);
229 /// Emit a container holding the serialized AST.
230 void HandleTranslationUnit(ASTContext &Ctx) override {
231 assert(M && VMContext && Builder);
232 // Delete these on function exit.
233 std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
234 std::unique_ptr<llvm::Module> M = std::move(this->M);
235 std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
237 if (Diags.hasErrorOccurred())
240 M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
241 M->setDataLayout(Ctx.getTargetInfo().getDataLayout());
243 // PCH files don't have a signature field in the control block,
244 // but LLVM detects DWO CUs by looking for a non-zero DWO id.
245 // We use the lower 64 bits for debug info.
248 ? (uint64_t)Buffer->Signature[1] << 32 | Buffer->Signature[0]
250 Builder->getModuleDebugInfo()->setDwoId(Signature);
252 // Finalize the Builder.
256 // Ensure the target exists.
258 auto Triple = Ctx.getTargetInfo().getTriple();
259 if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
260 llvm::report_fatal_error(Error);
262 // Emit the serialized Clang AST into its own section.
263 assert(Buffer->IsComplete && "serialization did not complete");
264 auto &SerializedAST = Buffer->Data;
265 auto Size = SerializedAST.size();
266 auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
267 auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
268 auto *Data = llvm::ConstantDataArray::getString(
269 *VMContext, StringRef(SerializedAST.data(), Size),
271 auto *ASTSym = new llvm::GlobalVariable(
272 *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
274 // The on-disk hashtable needs to be aligned.
275 ASTSym->setAlignment(8);
277 // Mach-O also needs a segment name.
278 if (Triple.isOSBinFormatMachO())
279 ASTSym->setSection("__CLANG,__clangast");
280 // COFF has an eight character length limit.
281 else if (Triple.isOSBinFormatCOFF())
282 ASTSym->setSection("clangast");
284 ASTSym->setSection("__clangast");
287 // Print the IR for the PCH container to the debug output.
288 llvm::SmallString<0> Buffer;
289 clang::EmitBackendOutput(
290 Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
291 Ctx.getTargetInfo().getDataLayout(), M.get(),
292 BackendAction::Backend_EmitLL,
293 llvm::make_unique<llvm::raw_svector_ostream>(Buffer));
294 llvm::dbgs() << Buffer;
297 // Use the LLVM backend to emit the pch container.
298 clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
299 LangOpts, Ctx.getTargetInfo().getDataLayout(),
300 M.get(), BackendAction::Backend_EmitObj,
303 // Free the memory for the temporary buffer.
304 llvm::SmallVector<char, 0> Empty;
305 SerializedAST = std::move(Empty);
309 } // anonymous namespace
311 std::unique_ptr<ASTConsumer>
312 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
313 CompilerInstance &CI, const std::string &MainFileName,
314 const std::string &OutputFileName,
315 std::unique_ptr<llvm::raw_pwrite_stream> OS,
316 std::shared_ptr<PCHBuffer> Buffer) const {
317 return llvm::make_unique<PCHContainerGenerator>(
318 CI, MainFileName, OutputFileName, std::move(OS), Buffer);
322 ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
324 auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
326 auto &OF = OFOrErr.get();
327 bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF);
328 // Find the clang AST section in the container.
329 for (auto &Section : OF->sections()) {
331 Section.getName(Name);
332 if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) {
333 Section.getContents(PCH);
338 handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
339 if (EIB.convertToErrorCode() ==
340 llvm::object::object_error::invalid_file_type)
341 // As a fallback, treat the buffer as a raw AST.
342 PCH = Buffer.getBuffer();
344 EIB.log(llvm::errs());