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"
20bc068586SAdrian Prantl #include "clang/Frontend/CodeGenOptions.h"
210391406eSAdrian Prantl #include "clang/Frontend/CompilerInstance.h"
22*9402cef0SAdrian Prantl #include "clang/Lex/Preprocessor.h"
23*9402cef0SAdrian Prantl #include "clang/Lex/HeaderSearch.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"
34bc068586SAdrian Prantl #include "llvm/Support/TargetRegistry.h"
35bc068586SAdrian Prantl #include <memory>
367eb5464bSHans Wennborg 
37bc068586SAdrian Prantl using namespace clang;
38bc068586SAdrian Prantl 
39bc068586SAdrian Prantl #define DEBUG_TYPE "pchcontainer"
40bc068586SAdrian Prantl 
41bc068586SAdrian Prantl namespace {
425a88e1a8SAdrian Prantl class PCHContainerGenerator : public ASTConsumer {
43bc068586SAdrian Prantl   DiagnosticsEngine &Diags;
44bc068586SAdrian Prantl   const std::string MainFileName;
45bc068586SAdrian Prantl   ASTContext *Ctx;
46*9402cef0SAdrian Prantl   ModuleMap &MMap;
47bc068586SAdrian Prantl   const HeaderSearchOptions &HeaderSearchOpts;
48bc068586SAdrian Prantl   const PreprocessorOptions &PreprocessorOpts;
49bc068586SAdrian Prantl   CodeGenOptions CodeGenOpts;
50bc068586SAdrian Prantl   const TargetOptions TargetOpts;
51bc068586SAdrian Prantl   const LangOptions LangOpts;
52bc068586SAdrian Prantl   std::unique_ptr<llvm::LLVMContext> VMContext;
53bc068586SAdrian Prantl   std::unique_ptr<llvm::Module> M;
54bc068586SAdrian Prantl   std::unique_ptr<CodeGen::CodeGenModule> Builder;
55bc068586SAdrian Prantl   raw_pwrite_stream *OS;
56bc068586SAdrian Prantl   std::shared_ptr<PCHBuffer> Buffer;
57bc068586SAdrian Prantl 
584aa2b3a3SAdrian Prantl   /// Visit every type and emit debug info for it.
594aa2b3a3SAdrian Prantl   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
604aa2b3a3SAdrian Prantl     clang::CodeGen::CGDebugInfo &DI;
614aa2b3a3SAdrian Prantl     ASTContext &Ctx;
624aa2b3a3SAdrian Prantl     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
634aa2b3a3SAdrian Prantl         : DI(DI), Ctx(Ctx) {}
644aa2b3a3SAdrian Prantl 
654aa2b3a3SAdrian Prantl     /// Determine whether this type can be represented in DWARF.
664aa2b3a3SAdrian Prantl     static bool CanRepresent(const Type *Ty) {
674aa2b3a3SAdrian Prantl       return !Ty->isDependentType() && !Ty->isUndeducedType();
684aa2b3a3SAdrian Prantl     }
694aa2b3a3SAdrian Prantl 
704aa2b3a3SAdrian Prantl     bool VisitTypeDecl(TypeDecl *D) {
714aa2b3a3SAdrian Prantl       QualType QualTy = Ctx.getTypeDeclType(D);
724aa2b3a3SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
734aa2b3a3SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
744aa2b3a3SAdrian Prantl       return true;
754aa2b3a3SAdrian Prantl     }
764aa2b3a3SAdrian Prantl 
77748a6cd1SAdrian Prantl     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
78748a6cd1SAdrian Prantl       QualType QualTy(D->getTypeForDecl(), 0);
79748a6cd1SAdrian Prantl       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
80748a6cd1SAdrian Prantl         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
81748a6cd1SAdrian Prantl       return true;
82748a6cd1SAdrian Prantl     }
83748a6cd1SAdrian Prantl 
84748a6cd1SAdrian Prantl     bool VisitFunctionDecl(FunctionDecl *D) {
85748a6cd1SAdrian Prantl       if (isa<CXXMethodDecl>(D))
86748a6cd1SAdrian Prantl         // This is not yet supported. Constructing the `this' argument
87748a6cd1SAdrian Prantl         // mandates a CodeGenFunction.
88748a6cd1SAdrian Prantl         return true;
89748a6cd1SAdrian Prantl 
90748a6cd1SAdrian Prantl       SmallVector<QualType, 16> ArgTypes;
91748a6cd1SAdrian Prantl       for (auto i : D->params())
92748a6cd1SAdrian Prantl         ArgTypes.push_back(i->getType());
93748a6cd1SAdrian Prantl       QualType RetTy = D->getReturnType();
94748a6cd1SAdrian Prantl       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
95748a6cd1SAdrian Prantl                                           FunctionProtoType::ExtProtoInfo());
96748a6cd1SAdrian Prantl       if (CanRepresent(FnTy.getTypePtr()))
97748a6cd1SAdrian Prantl         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
98748a6cd1SAdrian Prantl       return true;
99748a6cd1SAdrian Prantl     }
100748a6cd1SAdrian Prantl 
101748a6cd1SAdrian Prantl     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
102748a6cd1SAdrian Prantl       if (!D->getClassInterface())
103748a6cd1SAdrian Prantl         return true;
104748a6cd1SAdrian Prantl 
105748a6cd1SAdrian Prantl       bool selfIsPseudoStrong, selfIsConsumed;
106748a6cd1SAdrian Prantl       SmallVector<QualType, 16> ArgTypes;
107748a6cd1SAdrian Prantl       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
108748a6cd1SAdrian Prantl                                         selfIsPseudoStrong, selfIsConsumed));
109748a6cd1SAdrian Prantl       ArgTypes.push_back(Ctx.getObjCSelType());
110748a6cd1SAdrian Prantl       for (auto i : D->params())
111748a6cd1SAdrian Prantl         ArgTypes.push_back(i->getType());
112748a6cd1SAdrian Prantl       QualType RetTy = D->getReturnType();
113748a6cd1SAdrian Prantl       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
114748a6cd1SAdrian Prantl                                           FunctionProtoType::ExtProtoInfo());
115748a6cd1SAdrian Prantl       if (CanRepresent(FnTy.getTypePtr()))
116748a6cd1SAdrian Prantl         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
117748a6cd1SAdrian Prantl       return true;
118748a6cd1SAdrian Prantl     }
1194aa2b3a3SAdrian Prantl   };
1204aa2b3a3SAdrian Prantl 
121bc068586SAdrian Prantl public:
1221e63b2bdSAdrian Prantl   PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
1235a88e1a8SAdrian Prantl                         const std::string &OutputFileName,
1245a88e1a8SAdrian Prantl                         raw_pwrite_stream *OS,
1255a88e1a8SAdrian Prantl                         std::shared_ptr<PCHBuffer> Buffer)
1261e63b2bdSAdrian Prantl       : Diags(CI.getDiagnostics()), Ctx(nullptr),
127*9402cef0SAdrian Prantl         MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
1281e63b2bdSAdrian Prantl         HeaderSearchOpts(CI.getHeaderSearchOpts()),
1290391406eSAdrian Prantl         PreprocessorOpts(CI.getPreprocessorOpts()),
1300391406eSAdrian Prantl         TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), OS(OS),
1310391406eSAdrian Prantl         Buffer(Buffer) {
132bc068586SAdrian Prantl     // The debug info output isn't affected by CodeModel and
133bc068586SAdrian Prantl     // ThreadModel, but the backend expects them to be nonempty.
134bc068586SAdrian Prantl     CodeGenOpts.CodeModel = "default";
135bc068586SAdrian Prantl     CodeGenOpts.ThreadModel = "single";
1366b21ab21SAdrian Prantl     CodeGenOpts.DebugTypeExtRefs = true;
137bc068586SAdrian Prantl     CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
138bc068586SAdrian Prantl     CodeGenOpts.SplitDwarfFile = OutputFileName;
139bc068586SAdrian Prantl   }
140bc068586SAdrian Prantl 
1417eb5464bSHans Wennborg   ~PCHContainerGenerator() override = default;
142bc068586SAdrian Prantl 
143bc068586SAdrian Prantl   void Initialize(ASTContext &Context) override {
144293534b1SRichard Smith     assert(!Ctx && "initialized multiple times");
1450f99d6a4SRichard Smith 
146bc068586SAdrian Prantl     Ctx = &Context;
147bc068586SAdrian Prantl     VMContext.reset(new llvm::LLVMContext());
148bc068586SAdrian Prantl     M.reset(new llvm::Module(MainFileName, *VMContext));
149964a5f3bSEric Christopher     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
150ca3cf9e6SMehdi Amini     Builder.reset(new CodeGen::CodeGenModule(
151ca3cf9e6SMehdi Amini         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
152*9402cef0SAdrian Prantl     Builder->getModuleDebugInfo()->setModuleMap(MMap);
153bc068586SAdrian Prantl   }
154bc068586SAdrian Prantl 
1554aa2b3a3SAdrian Prantl   bool HandleTopLevelDecl(DeclGroupRef D) override {
1564aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred() ||
1574aa2b3a3SAdrian Prantl         (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo))
1584aa2b3a3SAdrian Prantl       return true;
1594aa2b3a3SAdrian Prantl 
1604aa2b3a3SAdrian Prantl     // Collect debug info for all decls in this group.
1614aa2b3a3SAdrian Prantl     for (auto *I : D)
1624aa2b3a3SAdrian Prantl       if (!I->isFromASTFile()) {
1634aa2b3a3SAdrian Prantl         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
1644aa2b3a3SAdrian Prantl         DTV.TraverseDecl(I);
1654aa2b3a3SAdrian Prantl       }
1664aa2b3a3SAdrian Prantl     return true;
1674aa2b3a3SAdrian Prantl   }
1684aa2b3a3SAdrian Prantl 
1694aa2b3a3SAdrian Prantl   void HandleTagDeclDefinition(TagDecl *D) override {
1704aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
1714aa2b3a3SAdrian Prantl       return;
1724aa2b3a3SAdrian Prantl 
1734aa2b3a3SAdrian Prantl     Builder->UpdateCompletedType(D);
1744aa2b3a3SAdrian Prantl   }
1754aa2b3a3SAdrian Prantl 
1764aa2b3a3SAdrian Prantl   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
1774aa2b3a3SAdrian Prantl     if (Diags.hasErrorOccurred())
1784aa2b3a3SAdrian Prantl       return;
1794aa2b3a3SAdrian Prantl 
1804aa2b3a3SAdrian Prantl     if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1818bd4c13fSAdrian Prantl       Builder->getModuleDebugInfo()->completeRequiredType(RD);
1824aa2b3a3SAdrian Prantl   }
1834aa2b3a3SAdrian Prantl 
184bc068586SAdrian Prantl   /// Emit a container holding the serialized AST.
185bc068586SAdrian Prantl   void HandleTranslationUnit(ASTContext &Ctx) override {
186bc068586SAdrian Prantl     assert(M && VMContext && Builder);
187bc068586SAdrian Prantl     // Delete these on function exit.
188bc068586SAdrian Prantl     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
189bc068586SAdrian Prantl     std::unique_ptr<llvm::Module> M = std::move(this->M);
190bc068586SAdrian Prantl     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
191bc068586SAdrian Prantl 
192bc068586SAdrian Prantl     if (Diags.hasErrorOccurred())
193bc068586SAdrian Prantl       return;
194bc068586SAdrian Prantl 
195bc068586SAdrian Prantl     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
196964a5f3bSEric Christopher     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
197bc068586SAdrian Prantl 
198bc068586SAdrian Prantl     // Finalize the Builder.
199bc068586SAdrian Prantl     if (Builder)
200bc068586SAdrian Prantl       Builder->Release();
201bc068586SAdrian Prantl 
202bc068586SAdrian Prantl     // Ensure the target exists.
203bc068586SAdrian Prantl     std::string Error;
204bc068586SAdrian Prantl     auto Triple = Ctx.getTargetInfo().getTriple();
205bc068586SAdrian Prantl     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
206bc068586SAdrian Prantl       llvm::report_fatal_error(Error);
207bc068586SAdrian Prantl 
208bc068586SAdrian Prantl     // Emit the serialized Clang AST into its own section.
209bc068586SAdrian Prantl     assert(Buffer->IsComplete && "serialization did not complete");
210bc068586SAdrian Prantl     auto &SerializedAST = Buffer->Data;
211bc068586SAdrian Prantl     auto Size = SerializedAST.size();
212bc068586SAdrian Prantl     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
213bc068586SAdrian Prantl     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
2145a88e1a8SAdrian Prantl     auto *Data = llvm::ConstantDataArray::getString(
2155a88e1a8SAdrian Prantl         *VMContext, StringRef(SerializedAST.data(), Size),
216bc068586SAdrian Prantl         /*AddNull=*/false);
217bc068586SAdrian Prantl     auto *ASTSym = new llvm::GlobalVariable(
218bc068586SAdrian Prantl         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
219bc068586SAdrian Prantl         "__clang_ast");
220bc068586SAdrian Prantl     // The on-disk hashtable needs to be aligned.
221bc068586SAdrian Prantl     ASTSym->setAlignment(8);
222bc068586SAdrian Prantl 
223bc068586SAdrian Prantl     // Mach-O also needs a segment name.
224bc068586SAdrian Prantl     if (Triple.isOSBinFormatMachO())
225bc068586SAdrian Prantl       ASTSym->setSection("__CLANG,__clangast");
226bc068586SAdrian Prantl     // COFF has an eight character length limit.
227bc068586SAdrian Prantl     else if (Triple.isOSBinFormatCOFF())
228bc068586SAdrian Prantl       ASTSym->setSection("clangast");
229bc068586SAdrian Prantl     else
230bc068586SAdrian Prantl       ASTSym->setSection("__clangast");
231bc068586SAdrian Prantl 
232bc068586SAdrian Prantl     DEBUG({
233bc068586SAdrian Prantl       // Print the IR for the PCH container to the debug output.
234bc068586SAdrian Prantl       llvm::SmallString<0> Buffer;
235bc068586SAdrian Prantl       llvm::raw_svector_ostream OS(Buffer);
236bc068586SAdrian Prantl       clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
237964a5f3bSEric Christopher                                Ctx.getTargetInfo().getDataLayoutString(),
238bc068586SAdrian Prantl                                M.get(), BackendAction::Backend_EmitLL, &OS);
239bc068586SAdrian Prantl       llvm::dbgs() << Buffer;
240bc068586SAdrian Prantl     });
241bc068586SAdrian Prantl 
242bc068586SAdrian Prantl     // Use the LLVM backend to emit the pch container.
243bc068586SAdrian Prantl     clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
244964a5f3bSEric Christopher                              Ctx.getTargetInfo().getDataLayoutString(),
245bc068586SAdrian Prantl                              M.get(), BackendAction::Backend_EmitObj, OS);
246bc068586SAdrian Prantl 
247bc068586SAdrian Prantl     // Make sure the pch container hits disk.
248bc068586SAdrian Prantl     OS->flush();
249bc068586SAdrian Prantl 
250bc068586SAdrian Prantl     // Free the memory for the temporary buffer.
251bc068586SAdrian Prantl     llvm::SmallVector<char, 0> Empty;
252bc068586SAdrian Prantl     SerializedAST = std::move(Empty);
253bc068586SAdrian Prantl   }
254bc068586SAdrian Prantl };
2555a88e1a8SAdrian Prantl 
2567eb5464bSHans Wennborg } // anonymous namespace
257bc068586SAdrian Prantl 
258bc068586SAdrian Prantl std::unique_ptr<ASTConsumer>
259fb2398d0SAdrian Prantl ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
2601e63b2bdSAdrian Prantl     CompilerInstance &CI, const std::string &MainFileName,
2611e63b2bdSAdrian Prantl     const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
2621e63b2bdSAdrian Prantl     std::shared_ptr<PCHBuffer> Buffer) const {
2631e63b2bdSAdrian Prantl   return llvm::make_unique<PCHContainerGenerator>(CI, MainFileName,
2640391406eSAdrian Prantl                                                   OutputFileName, OS, Buffer);
265bc068586SAdrian Prantl }
266bc068586SAdrian Prantl 
267fb2398d0SAdrian Prantl void ObjectFilePCHContainerReader::ExtractPCH(
268bc068586SAdrian Prantl     llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
269bc068586SAdrian Prantl   if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
270bc068586SAdrian Prantl     auto *Obj = OF.get().get();
271bc068586SAdrian Prantl     bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
272bc068586SAdrian Prantl     // Find the clang AST section in the container.
273bc068586SAdrian Prantl     for (auto &Section : OF->get()->sections()) {
274bc068586SAdrian Prantl       StringRef Name;
275bc068586SAdrian Prantl       Section.getName(Name);
276bc068586SAdrian Prantl       if ((!IsCOFF && Name == "__clangast") ||
277bc068586SAdrian Prantl           ( IsCOFF && Name ==   "clangast")) {
278bc068586SAdrian Prantl         StringRef Buf;
279bc068586SAdrian Prantl         Section.getContents(Buf);
280bc068586SAdrian Prantl         StreamFile.init((const unsigned char *)Buf.begin(),
281bc068586SAdrian Prantl                         (const unsigned char *)Buf.end());
282bc068586SAdrian Prantl         return;
283bc068586SAdrian Prantl       }
284bc068586SAdrian Prantl     }
285bc068586SAdrian Prantl   }
286bc068586SAdrian Prantl 
287bc068586SAdrian Prantl   // As a fallback, treat the buffer as a raw AST.
288bc068586SAdrian Prantl   StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
289bc068586SAdrian Prantl                   (const unsigned char *)Buffer.getBufferEnd());
290bc068586SAdrian Prantl }
291