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/Frontend/CompilerInstance.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Lex/HeaderSearch.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/TargetRegistry.h"
35 #include <memory>
36 
37 using namespace clang;
38 
39 #define DEBUG_TYPE "pchcontainer"
40 
41 namespace {
42 class PCHContainerGenerator : public ASTConsumer {
43   DiagnosticsEngine &Diags;
44   const std::string MainFileName;
45   ASTContext *Ctx;
46   ModuleMap &MMap;
47   const HeaderSearchOptions &HeaderSearchOpts;
48   const PreprocessorOptions &PreprocessorOpts;
49   CodeGenOptions CodeGenOpts;
50   const TargetOptions TargetOpts;
51   const LangOptions LangOpts;
52   std::unique_ptr<llvm::LLVMContext> VMContext;
53   std::unique_ptr<llvm::Module> M;
54   std::unique_ptr<CodeGen::CodeGenModule> Builder;
55   raw_pwrite_stream *OS;
56   std::shared_ptr<PCHBuffer> Buffer;
57 
58   /// Visit every type and emit debug info for it.
59   struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
60     clang::CodeGen::CGDebugInfo &DI;
61     ASTContext &Ctx;
62     DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
63         : DI(DI), Ctx(Ctx) {}
64 
65     /// Determine whether this type can be represented in DWARF.
66     static bool CanRepresent(const Type *Ty) {
67       return !Ty->isDependentType() && !Ty->isUndeducedType();
68     }
69 
70     bool VisitTypeDecl(TypeDecl *D) {
71       QualType QualTy = Ctx.getTypeDeclType(D);
72       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
73         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
74       return true;
75     }
76 
77     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
78       QualType QualTy(D->getTypeForDecl(), 0);
79       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
80         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
81       return true;
82     }
83 
84     bool VisitFunctionDecl(FunctionDecl *D) {
85       if (isa<CXXMethodDecl>(D))
86         // This is not yet supported. Constructing the `this' argument
87         // mandates a CodeGenFunction.
88         return true;
89 
90       SmallVector<QualType, 16> ArgTypes;
91       for (auto i : D->params())
92         ArgTypes.push_back(i->getType());
93       QualType RetTy = D->getReturnType();
94       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
95                                           FunctionProtoType::ExtProtoInfo());
96       if (CanRepresent(FnTy.getTypePtr()))
97         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
98       return true;
99     }
100 
101     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
102       if (!D->getClassInterface())
103         return true;
104 
105       bool selfIsPseudoStrong, selfIsConsumed;
106       SmallVector<QualType, 16> ArgTypes;
107       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
108                                         selfIsPseudoStrong, selfIsConsumed));
109       ArgTypes.push_back(Ctx.getObjCSelType());
110       for (auto i : D->params())
111         ArgTypes.push_back(i->getType());
112       QualType RetTy = D->getReturnType();
113       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
114                                           FunctionProtoType::ExtProtoInfo());
115       if (CanRepresent(FnTy.getTypePtr()))
116         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
117       return true;
118     }
119   };
120 
121 public:
122   PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
123                         const std::string &OutputFileName,
124                         raw_pwrite_stream *OS,
125                         std::shared_ptr<PCHBuffer> Buffer)
126       : Diags(CI.getDiagnostics()), Ctx(nullptr),
127         MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
128         HeaderSearchOpts(CI.getHeaderSearchOpts()),
129         PreprocessorOpts(CI.getPreprocessorOpts()),
130         TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), OS(OS),
131         Buffer(Buffer) {
132     // The debug info output isn't affected by CodeModel and
133     // ThreadModel, but the backend expects them to be nonempty.
134     CodeGenOpts.CodeModel = "default";
135     CodeGenOpts.ThreadModel = "single";
136     CodeGenOpts.DebugTypeExtRefs = true;
137     CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
138     CodeGenOpts.SplitDwarfFile = OutputFileName;
139   }
140 
141   ~PCHContainerGenerator() override = default;
142 
143   void Initialize(ASTContext &Context) override {
144     assert(!Ctx && "initialized multiple times");
145 
146     Ctx = &Context;
147     VMContext.reset(new llvm::LLVMContext());
148     M.reset(new llvm::Module(MainFileName, *VMContext));
149     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
150     Builder.reset(new CodeGen::CodeGenModule(
151         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
152     Builder->getModuleDebugInfo()->setModuleMap(MMap);
153   }
154 
155   bool HandleTopLevelDecl(DeclGroupRef D) override {
156     if (Diags.hasErrorOccurred() ||
157         (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo))
158       return true;
159 
160     // Collect debug info for all decls in this group.
161     for (auto *I : D)
162       if (!I->isFromASTFile()) {
163         DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
164         DTV.TraverseDecl(I);
165       }
166     return true;
167   }
168 
169   void HandleTagDeclDefinition(TagDecl *D) override {
170     if (Diags.hasErrorOccurred())
171       return;
172 
173     Builder->UpdateCompletedType(D);
174   }
175 
176   void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
177     if (Diags.hasErrorOccurred())
178       return;
179 
180     if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
181       Builder->getModuleDebugInfo()->completeRequiredType(RD);
182   }
183 
184   /// Emit a container holding the serialized AST.
185   void HandleTranslationUnit(ASTContext &Ctx) override {
186     assert(M && VMContext && Builder);
187     // Delete these on function exit.
188     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
189     std::unique_ptr<llvm::Module> M = std::move(this->M);
190     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
191 
192     if (Diags.hasErrorOccurred())
193       return;
194 
195     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
196     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
197 
198     // Finalize the Builder.
199     if (Builder)
200       Builder->Release();
201 
202     // Ensure the target exists.
203     std::string Error;
204     auto Triple = Ctx.getTargetInfo().getTriple();
205     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
206       llvm::report_fatal_error(Error);
207 
208     // Emit the serialized Clang AST into its own section.
209     assert(Buffer->IsComplete && "serialization did not complete");
210     auto &SerializedAST = Buffer->Data;
211     auto Size = SerializedAST.size();
212     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
213     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
214     auto *Data = llvm::ConstantDataArray::getString(
215         *VMContext, StringRef(SerializedAST.data(), Size),
216         /*AddNull=*/false);
217     auto *ASTSym = new llvm::GlobalVariable(
218         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
219         "__clang_ast");
220     // The on-disk hashtable needs to be aligned.
221     ASTSym->setAlignment(8);
222 
223     // Mach-O also needs a segment name.
224     if (Triple.isOSBinFormatMachO())
225       ASTSym->setSection("__CLANG,__clangast");
226     // COFF has an eight character length limit.
227     else if (Triple.isOSBinFormatCOFF())
228       ASTSym->setSection("clangast");
229     else
230       ASTSym->setSection("__clangast");
231 
232     DEBUG({
233       // Print the IR for the PCH container to the debug output.
234       llvm::SmallString<0> Buffer;
235       llvm::raw_svector_ostream OS(Buffer);
236       clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
237                                Ctx.getTargetInfo().getDataLayoutString(),
238                                M.get(), BackendAction::Backend_EmitLL, &OS);
239       llvm::dbgs() << Buffer;
240     });
241 
242     // Use the LLVM backend to emit the pch container.
243     clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
244                              Ctx.getTargetInfo().getDataLayoutString(),
245                              M.get(), BackendAction::Backend_EmitObj, OS);
246 
247     // Make sure the pch container hits disk.
248     OS->flush();
249 
250     // Free the memory for the temporary buffer.
251     llvm::SmallVector<char, 0> Empty;
252     SerializedAST = std::move(Empty);
253   }
254 };
255 
256 } // anonymous namespace
257 
258 std::unique_ptr<ASTConsumer>
259 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
260     CompilerInstance &CI, const std::string &MainFileName,
261     const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
262     std::shared_ptr<PCHBuffer> Buffer) const {
263   return llvm::make_unique<PCHContainerGenerator>(CI, MainFileName,
264                                                   OutputFileName, OS, Buffer);
265 }
266 
267 void ObjectFilePCHContainerReader::ExtractPCH(
268     llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
269   if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
270     auto *Obj = OF.get().get();
271     bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
272     // Find the clang AST section in the container.
273     for (auto &Section : OF->get()->sections()) {
274       StringRef Name;
275       Section.getName(Name);
276       if ((!IsCOFF && Name == "__clangast") ||
277           ( IsCOFF && Name ==   "clangast")) {
278         StringRef Buf;
279         Section.getContents(Buf);
280         StreamFile.init((const unsigned char *)Buf.begin(),
281                         (const unsigned char *)Buf.end());
282         return;
283       }
284     }
285   }
286 
287   // As a fallback, treat the buffer as a raw AST.
288   StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
289                   (const unsigned char *)Buffer.getBufferEnd());
290 }
291