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