1 //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
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/Serialization/ASTWriter.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/Bitcode/BitstreamReader.h"
24 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Object/COFF.h"
30 #include "llvm/Object/ObjectFile.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include <memory>
33 using namespace clang;
34 
35 #define DEBUG_TYPE "pchcontainer"
36 
37 namespace {
38 class PCHContainerGenerator : public ASTConsumer {
39   DiagnosticsEngine &Diags;
40   const std::string MainFileName;
41   ASTContext *Ctx;
42   const HeaderSearchOptions &HeaderSearchOpts;
43   const PreprocessorOptions &PreprocessorOpts;
44   CodeGenOptions CodeGenOpts;
45   const TargetOptions TargetOpts;
46   const LangOptions LangOpts;
47   std::unique_ptr<llvm::LLVMContext> VMContext;
48   std::unique_ptr<llvm::Module> M;
49   std::unique_ptr<CodeGen::CodeGenModule> Builder;
50   raw_pwrite_stream *OS;
51   std::shared_ptr<PCHBuffer> Buffer;
52 
53   /// Visit every type and emit debug info for it.
54   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
55     clang::CodeGen::CGDebugInfo &DI;
56     ASTContext &Ctx;
57     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
58         : DI(DI), Ctx(Ctx) {}
59 
60     /// Determine whether this type can be represented in DWARF.
61     static bool CanRepresent(const Type *Ty) {
62       return !Ty->isDependentType() && !Ty->isUndeducedType();
63     }
64 
65     bool VisitTypeDecl(TypeDecl *D) {
66       QualType QualTy = Ctx.getTypeDeclType(D);
67       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
68         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
69       return true;
70     }
71 
72     bool VisitValueDecl(ValueDecl *D) {
73       QualType QualTy = D->getType();
74       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
75         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
76       return true;
77     }
78 
79   };
80 
81 public:
82   PCHContainerGenerator(DiagnosticsEngine &diags,
83                         const HeaderSearchOptions &HSO,
84                         const PreprocessorOptions &PPO, const TargetOptions &TO,
85                         const LangOptions &LO, const std::string &MainFileName,
86                         const std::string &OutputFileName,
87                         raw_pwrite_stream *OS,
88                         std::shared_ptr<PCHBuffer> Buffer)
89       : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO), PreprocessorOpts(PPO),
90         TargetOpts(TO), LangOpts(LO), OS(OS), Buffer(Buffer) {
91     // The debug info output isn't affected by CodeModel and
92     // ThreadModel, but the backend expects them to be nonempty.
93     CodeGenOpts.CodeModel = "default";
94     CodeGenOpts.ThreadModel = "single";
95     CodeGenOpts.DebugTypeExtRefs = true;
96     CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
97     CodeGenOpts.SplitDwarfFile = OutputFileName;
98   }
99 
100   virtual ~PCHContainerGenerator() {}
101 
102   void Initialize(ASTContext &Context) override {
103     assert(!Ctx && "initialized multiple times");
104 
105     Ctx = &Context;
106     VMContext.reset(new llvm::LLVMContext());
107     M.reset(new llvm::Module(MainFileName, *VMContext));
108     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
109     Builder.reset(new CodeGen::CodeGenModule(
110         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
111   }
112 
113   bool HandleTopLevelDecl(DeclGroupRef D) override {
114     if (Diags.hasErrorOccurred() ||
115         (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo))
116       return true;
117 
118     // Collect debug info for all decls in this group.
119     for (auto *I : D)
120       if (!I->isFromASTFile()) {
121         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
122         DTV.TraverseDecl(I);
123       }
124     return true;
125   }
126 
127   void HandleTagDeclDefinition(TagDecl *D) override {
128     if (Diags.hasErrorOccurred())
129       return;
130 
131     Builder->UpdateCompletedType(D);
132   }
133 
134   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
135     if (Diags.hasErrorOccurred())
136       return;
137 
138     if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
139       if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
140         DI->completeRequiredType(RD);
141   }
142 
143   /// Emit a container holding the serialized AST.
144   void HandleTranslationUnit(ASTContext &Ctx) override {
145     assert(M && VMContext && Builder);
146     // Delete these on function exit.
147     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
148     std::unique_ptr<llvm::Module> M = std::move(this->M);
149     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
150 
151     if (Diags.hasErrorOccurred())
152       return;
153 
154     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
155     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
156 
157     // Finalize the Builder.
158     if (Builder)
159       Builder->Release();
160 
161     // Ensure the target exists.
162     std::string Error;
163     auto Triple = Ctx.getTargetInfo().getTriple();
164     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
165       llvm::report_fatal_error(Error);
166 
167     // Emit the serialized Clang AST into its own section.
168     assert(Buffer->IsComplete && "serialization did not complete");
169     auto &SerializedAST = Buffer->Data;
170     auto Size = SerializedAST.size();
171     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
172     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
173     auto *Data = llvm::ConstantDataArray::getString(
174         *VMContext, StringRef(SerializedAST.data(), Size),
175         /*AddNull=*/false);
176     auto *ASTSym = new llvm::GlobalVariable(
177         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
178         "__clang_ast");
179     // The on-disk hashtable needs to be aligned.
180     ASTSym->setAlignment(8);
181 
182     // Mach-O also needs a segment name.
183     if (Triple.isOSBinFormatMachO())
184       ASTSym->setSection("__CLANG,__clangast");
185     // COFF has an eight character length limit.
186     else if (Triple.isOSBinFormatCOFF())
187       ASTSym->setSection("clangast");
188     else
189       ASTSym->setSection("__clangast");
190 
191     DEBUG({
192       // Print the IR for the PCH container to the debug output.
193       llvm::SmallString<0> Buffer;
194       llvm::raw_svector_ostream OS(Buffer);
195       clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
196                                Ctx.getTargetInfo().getDataLayoutString(),
197                                M.get(), BackendAction::Backend_EmitLL, &OS);
198       llvm::dbgs() << Buffer;
199     });
200 
201     // Use the LLVM backend to emit the pch container.
202     clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
203                              Ctx.getTargetInfo().getDataLayoutString(),
204                              M.get(), BackendAction::Backend_EmitObj, OS);
205 
206     // Make sure the pch container hits disk.
207     OS->flush();
208 
209     // Free the memory for the temporary buffer.
210     llvm::SmallVector<char, 0> Empty;
211     SerializedAST = std::move(Empty);
212   }
213 };
214 
215 } // namespace
216 
217 std::unique_ptr<ASTConsumer>
218 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
219     DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
220     const PreprocessorOptions &PPO, const TargetOptions &TO,
221     const LangOptions &LO, const std::string &MainFileName,
222     const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
223     std::shared_ptr<PCHBuffer> Buffer) const {
224   return llvm::make_unique<PCHContainerGenerator>(
225       Diags, HSO, PPO, TO, LO, MainFileName, OutputFileName, OS, Buffer);
226 }
227 
228 void ObjectFilePCHContainerReader::ExtractPCH(
229     llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
230   if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
231     auto *Obj = OF.get().get();
232     bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
233     // Find the clang AST section in the container.
234     for (auto &Section : OF->get()->sections()) {
235       StringRef Name;
236       Section.getName(Name);
237       if ((!IsCOFF && Name == "__clangast") ||
238           ( IsCOFF && Name ==   "clangast")) {
239         StringRef Buf;
240         Section.getContents(Buf);
241         StreamFile.init((const unsigned char *)Buf.begin(),
242                         (const unsigned char *)Buf.end());
243         return;
244       }
245     }
246   }
247 
248   // As a fallback, treat the buffer as a raw AST.
249   StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
250                   (const unsigned char *)Buffer.getBufferEnd());
251   return;
252 }
253