1bc068586SAdrian Prantl //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
2bc068586SAdrian Prantl //
3bc068586SAdrian Prantl //                     The LLVM Compiler Infrastructure
4bc068586SAdrian Prantl //
5bc068586SAdrian Prantl // This file is distributed under the University of Illinois Open Source
6bc068586SAdrian Prantl // License. See LICENSE.TXT for details.
7bc068586SAdrian Prantl //
8bc068586SAdrian Prantl //===----------------------------------------------------------------------===//
9bc068586SAdrian Prantl 
10bc068586SAdrian Prantl #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
11bc068586SAdrian Prantl #include "CGDebugInfo.h"
12bc068586SAdrian Prantl #include "CodeGenModule.h"
13bc068586SAdrian Prantl #include "clang/AST/ASTContext.h"
14bc068586SAdrian Prantl #include "clang/AST/DeclObjC.h"
15bc068586SAdrian Prantl #include "clang/AST/Expr.h"
16bc068586SAdrian Prantl #include "clang/AST/RecursiveASTVisitor.h"
17bc068586SAdrian Prantl #include "clang/Basic/Diagnostic.h"
18bc068586SAdrian Prantl #include "clang/Basic/TargetInfo.h"
19bc068586SAdrian Prantl #include "clang/CodeGen/BackendUtil.h"
2010a4972aSSaleem Abdulrasool #include "clang/Frontend/CodeGenOptions.h"
210391406eSAdrian Prantl #include "clang/Frontend/CompilerInstance.h"
229402cef0SAdrian Prantl #include "clang/Lex/HeaderSearch.h"
233a2d4947SAdrian Prantl #include "clang/Lex/Preprocessor.h"
24bc068586SAdrian Prantl #include "clang/Serialization/ASTWriter.h"
25bc068586SAdrian Prantl #include "llvm/ADT/StringRef.h"
26bc068586SAdrian Prantl #include "llvm/Bitcode/BitstreamReader.h"
27bc068586SAdrian Prantl #include "llvm/DebugInfo/DWARF/DWARFContext.h"
28bc068586SAdrian Prantl #include "llvm/IR/Constants.h"
29bc068586SAdrian Prantl #include "llvm/IR/DataLayout.h"
30bc068586SAdrian Prantl #include "llvm/IR/LLVMContext.h"
31bc068586SAdrian Prantl #include "llvm/IR/Module.h"
32bc068586SAdrian Prantl #include "llvm/Object/COFF.h"
33bc068586SAdrian Prantl #include "llvm/Object/ObjectFile.h"
343a2d4947SAdrian Prantl #include "llvm/Support/Path.h"
35bc068586SAdrian Prantl #include "llvm/Support/TargetRegistry.h"
36bc068586SAdrian Prantl #include <memory>
37cfeacf56SBenjamin Kramer #include <utility>
387eb5464bSHans Wennborg 
39bc068586SAdrian Prantl using namespace clang;
40bc068586SAdrian Prantl 
41bc068586SAdrian Prantl #define DEBUG_TYPE "pchcontainer"
42bc068586SAdrian Prantl 
43bc068586SAdrian Prantl namespace {
445a88e1a8SAdrian Prantl class PCHContainerGenerator : public ASTConsumer {
45bc068586SAdrian Prantl   DiagnosticsEngine &Diags;
46bc068586SAdrian Prantl   const std::string MainFileName;
47aa5d08d0SAdrian Prantl   const std::string OutputFileName;
48bc068586SAdrian Prantl   ASTContext *Ctx;
499402cef0SAdrian Prantl   ModuleMap &MMap;
50bc068586SAdrian Prantl   const HeaderSearchOptions &HeaderSearchOpts;
51bc068586SAdrian Prantl   const PreprocessorOptions &PreprocessorOpts;
52bc068586SAdrian Prantl   CodeGenOptions CodeGenOpts;
53bc068586SAdrian Prantl   const TargetOptions TargetOpts;
54bc068586SAdrian Prantl   const LangOptions LangOpts;
55bc068586SAdrian Prantl   std::unique_ptr<llvm::LLVMContext> VMContext;
56bc068586SAdrian Prantl   std::unique_ptr<llvm::Module> M;
57bc068586SAdrian Prantl   std::unique_ptr<CodeGen::CodeGenModule> Builder;
5803f8907fSPeter Collingbourne   std::unique_ptr<raw_pwrite_stream> OS;
59bc068586SAdrian Prantl   std::shared_ptr<PCHBuffer> Buffer;
60bc068586SAdrian Prantl 
614aa2b3a3SAdrian Prantl   /// Visit every type and emit debug info for it.
624aa2b3a3SAdrian Prantl   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
634aa2b3a3SAdrian Prantl     clang::CodeGen::CGDebugInfo &DI;
644aa2b3a3SAdrian Prantl     ASTContext &Ctx;
65cd975018SAdrian Prantl     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
66cd975018SAdrian Prantl         : DI(DI), Ctx(Ctx) {}
674aa2b3a3SAdrian Prantl 
684aa2b3a3SAdrian Prantl     /// Determine whether this type can be represented in DWARF.
694aa2b3a3SAdrian Prantl     static bool CanRepresent(const Type *Ty) {
704aa2b3a3SAdrian Prantl       return !Ty->isDependentType() && !Ty->isUndeducedType();
714aa2b3a3SAdrian Prantl     }
724aa2b3a3SAdrian Prantl 
7385d938aaSAdrian Prantl     bool VisitImportDecl(ImportDecl *D) {
7485d938aaSAdrian Prantl       auto *Import = cast<ImportDecl>(D);
7585d938aaSAdrian Prantl       if (!Import->getImportedOwningModule())
7685d938aaSAdrian Prantl         DI.EmitImportDecl(*Import);
7785d938aaSAdrian Prantl       return true;
7885d938aaSAdrian Prantl     }
7985d938aaSAdrian Prantl 
804aa2b3a3SAdrian Prantl     bool VisitTypeDecl(TypeDecl *D) {
81b3b821f1SAdrian Prantl       // TagDecls may be deferred until after all decls have been merged and we
82b3b821f1SAdrian Prantl       // know the complete type. Pure forward declarations will be skipped, but
83b3b821f1SAdrian Prantl       // they don't need to be emitted into the module anyway.
84cd975018SAdrian Prantl       if (auto *TD = dyn_cast<TagDecl>(D))
85cd975018SAdrian Prantl         if (!TD->isCompleteDefinition())
86b3b821f1SAdrian Prantl           return true;
87b3b821f1SAdrian Prantl 
884aa2b3a3SAdrian Prantl       QualType QualTy = Ctx.getTypeDeclType(D);
894aa2b3a3SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
904aa2b3a3SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
914aa2b3a3SAdrian Prantl       return true;
924aa2b3a3SAdrian Prantl     }
934aa2b3a3SAdrian Prantl 
94748a6cd1SAdrian Prantl     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
95748a6cd1SAdrian Prantl       QualType QualTy(D->getTypeForDecl(), 0);
96748a6cd1SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
97748a6cd1SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
98748a6cd1SAdrian Prantl       return true;
99748a6cd1SAdrian Prantl     }
100748a6cd1SAdrian Prantl 
101748a6cd1SAdrian Prantl     bool VisitFunctionDecl(FunctionDecl *D) {
102748a6cd1SAdrian Prantl       if (isa<CXXMethodDecl>(D))
103748a6cd1SAdrian Prantl         // This is not yet supported. Constructing the `this' argument
104748a6cd1SAdrian Prantl         // mandates a CodeGenFunction.
105748a6cd1SAdrian Prantl         return true;
106748a6cd1SAdrian Prantl 
107748a6cd1SAdrian Prantl       SmallVector<QualType, 16> ArgTypes;
10859f77921SDavid Majnemer       for (auto i : D->parameters())
109748a6cd1SAdrian Prantl         ArgTypes.push_back(i->getType());
110748a6cd1SAdrian Prantl       QualType RetTy = D->getReturnType();
111748a6cd1SAdrian Prantl       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
112748a6cd1SAdrian Prantl                                           FunctionProtoType::ExtProtoInfo());
113748a6cd1SAdrian Prantl       if (CanRepresent(FnTy.getTypePtr()))
114748a6cd1SAdrian Prantl         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
115748a6cd1SAdrian Prantl       return true;
116748a6cd1SAdrian Prantl     }
117748a6cd1SAdrian Prantl 
118748a6cd1SAdrian Prantl     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
119748a6cd1SAdrian Prantl       if (!D->getClassInterface())
120748a6cd1SAdrian Prantl         return true;
121748a6cd1SAdrian Prantl 
122748a6cd1SAdrian Prantl       bool selfIsPseudoStrong, selfIsConsumed;
123748a6cd1SAdrian Prantl       SmallVector<QualType, 16> ArgTypes;
124748a6cd1SAdrian Prantl       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
125748a6cd1SAdrian Prantl                                         selfIsPseudoStrong, selfIsConsumed));
126748a6cd1SAdrian Prantl       ArgTypes.push_back(Ctx.getObjCSelType());
12759f77921SDavid Majnemer       for (auto i : D->parameters())
128748a6cd1SAdrian Prantl         ArgTypes.push_back(i->getType());
129748a6cd1SAdrian Prantl       QualType RetTy = D->getReturnType();
130748a6cd1SAdrian Prantl       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
131748a6cd1SAdrian Prantl                                           FunctionProtoType::ExtProtoInfo());
132748a6cd1SAdrian Prantl       if (CanRepresent(FnTy.getTypePtr()))
133748a6cd1SAdrian Prantl         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
134748a6cd1SAdrian Prantl       return true;
135748a6cd1SAdrian Prantl     }
1364aa2b3a3SAdrian Prantl   };
1374aa2b3a3SAdrian Prantl 
138bc068586SAdrian Prantl public:
1391e63b2bdSAdrian Prantl   PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
1405a88e1a8SAdrian Prantl                         const std::string &OutputFileName,
14103f8907fSPeter Collingbourne                         std::unique_ptr<raw_pwrite_stream> OS,
1425a88e1a8SAdrian Prantl                         std::shared_ptr<PCHBuffer> Buffer)
143aa5d08d0SAdrian Prantl       : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
144aa5d08d0SAdrian Prantl         OutputFileName(OutputFileName), Ctx(nullptr),
1459402cef0SAdrian Prantl         MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
1461e63b2bdSAdrian Prantl         HeaderSearchOpts(CI.getHeaderSearchOpts()),
1470391406eSAdrian Prantl         PreprocessorOpts(CI.getPreprocessorOpts()),
14803f8907fSPeter Collingbourne         TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
14903f8907fSPeter Collingbourne         OS(std::move(OS)), Buffer(std::move(Buffer)) {
150bc068586SAdrian Prantl     // The debug info output isn't affected by CodeModel and
151bc068586SAdrian Prantl     // ThreadModel, but the backend expects them to be nonempty.
152bc068586SAdrian Prantl     CodeGenOpts.CodeModel = "default";
153bc068586SAdrian Prantl     CodeGenOpts.ThreadModel = "single";
1546b21ab21SAdrian Prantl     CodeGenOpts.DebugTypeExtRefs = true;
155*9a1a1aa2SAdrian Prantl     // When building a module MainFileName is the name of the modulemap file.
156*9a1a1aa2SAdrian Prantl     CodeGenOpts.MainFileName =
157*9a1a1aa2SAdrian Prantl         LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule;
1588c30592eSBenjamin Kramer     CodeGenOpts.setDebugInfo(codegenoptions::FullDebugInfo);
159af09f4acSDavid Blaikie     CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
160bc068586SAdrian Prantl   }
161bc068586SAdrian Prantl 
1627eb5464bSHans Wennborg   ~PCHContainerGenerator() override = default;
163bc068586SAdrian Prantl 
164bc068586SAdrian Prantl   void Initialize(ASTContext &Context) override {
165293534b1SRichard Smith     assert(!Ctx && "initialized multiple times");
1660f99d6a4SRichard Smith 
167bc068586SAdrian Prantl     Ctx = &Context;
168bc068586SAdrian Prantl     VMContext.reset(new llvm::LLVMContext());
169bc068586SAdrian Prantl     M.reset(new llvm::Module(MainFileName, *VMContext));
170b214cbc7SJames Y Knight     M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
171ca3cf9e6SMehdi Amini     Builder.reset(new CodeGen::CodeGenModule(
172ca3cf9e6SMehdi Amini         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
1733a2d4947SAdrian Prantl 
1743a2d4947SAdrian Prantl     // Prepare CGDebugInfo to emit debug info for a clang module.
1753a2d4947SAdrian Prantl     auto *DI = Builder->getModuleDebugInfo();
1763a2d4947SAdrian Prantl     StringRef ModuleName = llvm::sys::path::filename(MainFileName);
17760fa2888SDuncan P. N. Exon Smith     DI->setPCHDescriptor({ModuleName, "", OutputFileName,
17860fa2888SDuncan P. N. Exon Smith                           ASTFileSignature{{{~0U, ~0U, ~0U, ~0U, ~1U}}}});
1793a2d4947SAdrian Prantl     DI->setModuleMap(MMap);
180bc068586SAdrian Prantl   }
181bc068586SAdrian Prantl 
1824aa2b3a3SAdrian Prantl   bool HandleTopLevelDecl(DeclGroupRef D) override {
183abdd6fc4SAdrian Prantl     if (Diags.hasErrorOccurred())
1844aa2b3a3SAdrian Prantl       return true;
1854aa2b3a3SAdrian Prantl 
1864aa2b3a3SAdrian Prantl     // Collect debug info for all decls in this group.
1874aa2b3a3SAdrian Prantl     for (auto *I : D)
1884aa2b3a3SAdrian Prantl       if (!I->isFromASTFile()) {
189cd975018SAdrian Prantl         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
1904aa2b3a3SAdrian Prantl         DTV.TraverseDecl(I);
1914aa2b3a3SAdrian Prantl       }
1924aa2b3a3SAdrian Prantl     return true;
1934aa2b3a3SAdrian Prantl   }
1944aa2b3a3SAdrian Prantl 
195d43fe0bdSAdrian Prantl   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
196d43fe0bdSAdrian Prantl     HandleTopLevelDecl(D);
197d43fe0bdSAdrian Prantl   }
198d43fe0bdSAdrian Prantl 
1994aa2b3a3SAdrian Prantl   void HandleTagDeclDefinition(TagDecl *D) override {
2004aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
2014aa2b3a3SAdrian Prantl       return;
2024aa2b3a3SAdrian Prantl 
203b3b821f1SAdrian Prantl     if (D->isFromASTFile())
204b3b821f1SAdrian Prantl       return;
205b3b821f1SAdrian Prantl 
206e5238d2aSAdrian Prantl     // Anonymous tag decls are deferred until we are building their declcontext.
207e5238d2aSAdrian Prantl     if (D->getName().empty())
208e5238d2aSAdrian Prantl       return;
209e5238d2aSAdrian Prantl 
2105a9a4277SAdrian Prantl     // Defer tag decls until their declcontext is complete.
2115a9a4277SAdrian Prantl     auto *DeclCtx = D->getDeclContext();
2125a9a4277SAdrian Prantl     while (DeclCtx) {
2135a9a4277SAdrian Prantl       if (auto *D = dyn_cast<TagDecl>(DeclCtx))
2145a9a4277SAdrian Prantl         if (!D->isCompleteDefinition())
2155a9a4277SAdrian Prantl           return;
2165a9a4277SAdrian Prantl       DeclCtx = DeclCtx->getParent();
2175a9a4277SAdrian Prantl     }
2185a9a4277SAdrian Prantl 
219cd975018SAdrian Prantl     DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
220b3b821f1SAdrian Prantl     DTV.TraverseDecl(D);
2214aa2b3a3SAdrian Prantl     Builder->UpdateCompletedType(D);
2224aa2b3a3SAdrian Prantl   }
2234aa2b3a3SAdrian Prantl 
2244aa2b3a3SAdrian Prantl   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
2254aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
2264aa2b3a3SAdrian Prantl       return;
2274aa2b3a3SAdrian Prantl 
2284aa2b3a3SAdrian Prantl     if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
2298bd4c13fSAdrian Prantl       Builder->getModuleDebugInfo()->completeRequiredType(RD);
2304aa2b3a3SAdrian Prantl   }
2314aa2b3a3SAdrian Prantl 
232bc068586SAdrian Prantl   /// Emit a container holding the serialized AST.
233bc068586SAdrian Prantl   void HandleTranslationUnit(ASTContext &Ctx) override {
234bc068586SAdrian Prantl     assert(M && VMContext && Builder);
235bc068586SAdrian Prantl     // Delete these on function exit.
236bc068586SAdrian Prantl     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
237bc068586SAdrian Prantl     std::unique_ptr<llvm::Module> M = std::move(this->M);
238bc068586SAdrian Prantl     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
239bc068586SAdrian Prantl 
240bc068586SAdrian Prantl     if (Diags.hasErrorOccurred())
241bc068586SAdrian Prantl       return;
242bc068586SAdrian Prantl 
243bc068586SAdrian Prantl     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
244b214cbc7SJames Y Knight     M->setDataLayout(Ctx.getTargetInfo().getDataLayout());
245c96da8faSAdrian Prantl 
246c96da8faSAdrian Prantl     // PCH files don't have a signature field in the control block,
247c96da8faSAdrian Prantl     // but LLVM detects DWO CUs by looking for a non-zero DWO id.
24860fa2888SDuncan P. N. Exon Smith     // We use the lower 64 bits for debug info.
24960fa2888SDuncan P. N. Exon Smith     uint64_t Signature =
25060fa2888SDuncan P. N. Exon Smith         Buffer->Signature
25160fa2888SDuncan P. N. Exon Smith             ? (uint64_t)Buffer->Signature[1] << 32 | Buffer->Signature[0]
25260fa2888SDuncan P. N. Exon Smith             : ~1ULL;
253c96da8faSAdrian Prantl     Builder->getModuleDebugInfo()->setDwoId(Signature);
254bc068586SAdrian Prantl 
255bc068586SAdrian Prantl     // Finalize the Builder.
256bc068586SAdrian Prantl     if (Builder)
257bc068586SAdrian Prantl       Builder->Release();
258bc068586SAdrian Prantl 
259bc068586SAdrian Prantl     // Ensure the target exists.
260bc068586SAdrian Prantl     std::string Error;
261bc068586SAdrian Prantl     auto Triple = Ctx.getTargetInfo().getTriple();
262bc068586SAdrian Prantl     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
263bc068586SAdrian Prantl       llvm::report_fatal_error(Error);
264bc068586SAdrian Prantl 
265bc068586SAdrian Prantl     // Emit the serialized Clang AST into its own section.
266bc068586SAdrian Prantl     assert(Buffer->IsComplete && "serialization did not complete");
267bc068586SAdrian Prantl     auto &SerializedAST = Buffer->Data;
268bc068586SAdrian Prantl     auto Size = SerializedAST.size();
269bc068586SAdrian Prantl     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
270bc068586SAdrian Prantl     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
2715a88e1a8SAdrian Prantl     auto *Data = llvm::ConstantDataArray::getString(
2725a88e1a8SAdrian Prantl         *VMContext, StringRef(SerializedAST.data(), Size),
273bc068586SAdrian Prantl         /*AddNull=*/false);
274bc068586SAdrian Prantl     auto *ASTSym = new llvm::GlobalVariable(
275bc068586SAdrian Prantl         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
276bc068586SAdrian Prantl         "__clang_ast");
277bc068586SAdrian Prantl     // The on-disk hashtable needs to be aligned.
278bc068586SAdrian Prantl     ASTSym->setAlignment(8);
279bc068586SAdrian Prantl 
280bc068586SAdrian Prantl     // Mach-O also needs a segment name.
281bc068586SAdrian Prantl     if (Triple.isOSBinFormatMachO())
282bc068586SAdrian Prantl       ASTSym->setSection("__CLANG,__clangast");
283bc068586SAdrian Prantl     // COFF has an eight character length limit.
284bc068586SAdrian Prantl     else if (Triple.isOSBinFormatCOFF())
285bc068586SAdrian Prantl       ASTSym->setSection("clangast");
286bc068586SAdrian Prantl     else
287bc068586SAdrian Prantl       ASTSym->setSection("__clangast");
288bc068586SAdrian Prantl 
289bc068586SAdrian Prantl     DEBUG({
290bc068586SAdrian Prantl       // Print the IR for the PCH container to the debug output.
291bc068586SAdrian Prantl       llvm::SmallString<0> Buffer;
29203f8907fSPeter Collingbourne       clang::EmitBackendOutput(
293888e289eSSaleem Abdulrasool           Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
294b214cbc7SJames Y Knight           Ctx.getTargetInfo().getDataLayout(), M.get(),
29503f8907fSPeter Collingbourne           BackendAction::Backend_EmitLL,
29603f8907fSPeter Collingbourne           llvm::make_unique<llvm::raw_svector_ostream>(Buffer));
297bc068586SAdrian Prantl       llvm::dbgs() << Buffer;
298bc068586SAdrian Prantl     });
299bc068586SAdrian Prantl 
300bc068586SAdrian Prantl     // Use the LLVM backend to emit the pch container.
301888e289eSSaleem Abdulrasool     clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
302888e289eSSaleem Abdulrasool                              LangOpts, Ctx.getTargetInfo().getDataLayout(),
303888e289eSSaleem Abdulrasool                              M.get(), BackendAction::Backend_EmitObj,
304888e289eSSaleem Abdulrasool                              std::move(OS));
305bc068586SAdrian Prantl 
306bc068586SAdrian Prantl     // Free the memory for the temporary buffer.
307bc068586SAdrian Prantl     llvm::SmallVector<char, 0> Empty;
308bc068586SAdrian Prantl     SerializedAST = std::move(Empty);
309bc068586SAdrian Prantl   }
310bc068586SAdrian Prantl };
3115a88e1a8SAdrian Prantl 
3127eb5464bSHans Wennborg } // anonymous namespace
313bc068586SAdrian Prantl 
314bc068586SAdrian Prantl std::unique_ptr<ASTConsumer>
315fb2398d0SAdrian Prantl ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
3161e63b2bdSAdrian Prantl     CompilerInstance &CI, const std::string &MainFileName,
31703f8907fSPeter Collingbourne     const std::string &OutputFileName,
31803f8907fSPeter Collingbourne     std::unique_ptr<llvm::raw_pwrite_stream> OS,
3191e63b2bdSAdrian Prantl     std::shared_ptr<PCHBuffer> Buffer) const {
32003f8907fSPeter Collingbourne   return llvm::make_unique<PCHContainerGenerator>(
32103f8907fSPeter Collingbourne       CI, MainFileName, OutputFileName, std::move(OS), Buffer);
322bc068586SAdrian Prantl }
323bc068586SAdrian Prantl 
32477c89b69SPeter Collingbourne StringRef
32577c89b69SPeter Collingbourne ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
32677c89b69SPeter Collingbourne   StringRef PCH;
327576b2dbeSAdrian Prantl   auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
328576b2dbeSAdrian Prantl   if (OFOrErr) {
329576b2dbeSAdrian Prantl     auto &OF = OFOrErr.get();
330576b2dbeSAdrian Prantl     bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF);
331bc068586SAdrian Prantl     // Find the clang AST section in the container.
332576b2dbeSAdrian Prantl     for (auto &Section : OF->sections()) {
333bc068586SAdrian Prantl       StringRef Name;
334bc068586SAdrian Prantl       Section.getName(Name);
335576b2dbeSAdrian Prantl       if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) {
33677c89b69SPeter Collingbourne         Section.getContents(PCH);
33777c89b69SPeter Collingbourne         return PCH;
338bc068586SAdrian Prantl       }
339bc068586SAdrian Prantl     }
340bc068586SAdrian Prantl   }
341576b2dbeSAdrian Prantl   handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
342576b2dbeSAdrian Prantl     if (EIB.convertToErrorCode() ==
343576b2dbeSAdrian Prantl         llvm::object::object_error::invalid_file_type)
344bc068586SAdrian Prantl       // As a fallback, treat the buffer as a raw AST.
34577c89b69SPeter Collingbourne       PCH = Buffer.getBuffer();
346576b2dbeSAdrian Prantl     else
347576b2dbeSAdrian Prantl       EIB.log(llvm::errs());
348576b2dbeSAdrian Prantl   });
34977c89b69SPeter Collingbourne   return PCH;
350bc068586SAdrian Prantl }
351