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     bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
80       QualType QualTy(D->getTypeForDecl(), 0);
81       if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
82         DI.getOrCreateStandaloneType(QualTy, D->getLocation());
83       return true;
84     }
85 
86     bool VisitFunctionDecl(FunctionDecl *D) {
87       if (isa<CXXMethodDecl>(D))
88         // This is not yet supported. Constructing the `this' argument
89         // mandates a CodeGenFunction.
90         return true;
91 
92       SmallVector<QualType, 16> ArgTypes;
93       for (auto i : D->params())
94         ArgTypes.push_back(i->getType());
95       QualType RetTy = D->getReturnType();
96       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
97                                           FunctionProtoType::ExtProtoInfo());
98       if (CanRepresent(FnTy.getTypePtr()))
99         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
100       return true;
101     }
102 
103     bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
104       if (!D->getClassInterface())
105         return true;
106 
107       bool selfIsPseudoStrong, selfIsConsumed;
108       SmallVector<QualType, 16> ArgTypes;
109       ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
110                                         selfIsPseudoStrong, selfIsConsumed));
111       ArgTypes.push_back(Ctx.getObjCSelType());
112       for (auto i : D->params())
113         ArgTypes.push_back(i->getType());
114       QualType RetTy = D->getReturnType();
115       QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
116                                           FunctionProtoType::ExtProtoInfo());
117       if (CanRepresent(FnTy.getTypePtr()))
118         DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
119       return true;
120     }
121   };
122 
123 public:
124   PCHContainerGenerator(DiagnosticsEngine &diags,
125                         const HeaderSearchOptions &HSO,
126                         const PreprocessorOptions &PPO, const TargetOptions &TO,
127                         const LangOptions &LO, const std::string &MainFileName,
128                         const std::string &OutputFileName,
129                         raw_pwrite_stream *OS,
130                         std::shared_ptr<PCHBuffer> Buffer)
131       : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO), PreprocessorOpts(PPO),
132         TargetOpts(TO), LangOpts(LO), OS(OS), Buffer(Buffer) {
133     // The debug info output isn't affected by CodeModel and
134     // ThreadModel, but the backend expects them to be nonempty.
135     CodeGenOpts.CodeModel = "default";
136     CodeGenOpts.ThreadModel = "single";
137     CodeGenOpts.DebugTypeExtRefs = true;
138     CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
139     CodeGenOpts.SplitDwarfFile = OutputFileName;
140   }
141 
142   virtual ~PCHContainerGenerator() {}
143 
144   void Initialize(ASTContext &Context) override {
145     assert(!Ctx && "initialized multiple times");
146 
147     Ctx = &Context;
148     VMContext.reset(new llvm::LLVMContext());
149     M.reset(new llvm::Module(MainFileName, *VMContext));
150     M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
151     Builder.reset(new CodeGen::CodeGenModule(
152         *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
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 (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
181       if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
182         DI->completeRequiredType(RD);
183   }
184 
185   /// Emit a container holding the serialized AST.
186   void HandleTranslationUnit(ASTContext &Ctx) override {
187     assert(M && VMContext && Builder);
188     // Delete these on function exit.
189     std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
190     std::unique_ptr<llvm::Module> M = std::move(this->M);
191     std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
192 
193     if (Diags.hasErrorOccurred())
194       return;
195 
196     M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
197     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
198 
199     // Finalize the Builder.
200     if (Builder)
201       Builder->Release();
202 
203     // Ensure the target exists.
204     std::string Error;
205     auto Triple = Ctx.getTargetInfo().getTriple();
206     if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
207       llvm::report_fatal_error(Error);
208 
209     // Emit the serialized Clang AST into its own section.
210     assert(Buffer->IsComplete && "serialization did not complete");
211     auto &SerializedAST = Buffer->Data;
212     auto Size = SerializedAST.size();
213     auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
214     auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
215     auto *Data = llvm::ConstantDataArray::getString(
216         *VMContext, StringRef(SerializedAST.data(), Size),
217         /*AddNull=*/false);
218     auto *ASTSym = new llvm::GlobalVariable(
219         *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
220         "__clang_ast");
221     // The on-disk hashtable needs to be aligned.
222     ASTSym->setAlignment(8);
223 
224     // Mach-O also needs a segment name.
225     if (Triple.isOSBinFormatMachO())
226       ASTSym->setSection("__CLANG,__clangast");
227     // COFF has an eight character length limit.
228     else if (Triple.isOSBinFormatCOFF())
229       ASTSym->setSection("clangast");
230     else
231       ASTSym->setSection("__clangast");
232 
233     DEBUG({
234       // Print the IR for the PCH container to the debug output.
235       llvm::SmallString<0> Buffer;
236       llvm::raw_svector_ostream OS(Buffer);
237       clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
238                                Ctx.getTargetInfo().getDataLayoutString(),
239                                M.get(), BackendAction::Backend_EmitLL, &OS);
240       llvm::dbgs() << Buffer;
241     });
242 
243     // Use the LLVM backend to emit the pch container.
244     clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
245                              Ctx.getTargetInfo().getDataLayoutString(),
246                              M.get(), BackendAction::Backend_EmitObj, OS);
247 
248     // Make sure the pch container hits disk.
249     OS->flush();
250 
251     // Free the memory for the temporary buffer.
252     llvm::SmallVector<char, 0> Empty;
253     SerializedAST = std::move(Empty);
254   }
255 };
256 
257 } // namespace
258 
259 std::unique_ptr<ASTConsumer>
260 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
261     DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
262     const PreprocessorOptions &PPO, const TargetOptions &TO,
263     const LangOptions &LO, const std::string &MainFileName,
264     const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
265     std::shared_ptr<PCHBuffer> Buffer) const {
266   return llvm::make_unique<PCHContainerGenerator>(
267       Diags, HSO, PPO, TO, LO, MainFileName, OutputFileName, OS, Buffer);
268 }
269 
270 void ObjectFilePCHContainerReader::ExtractPCH(
271     llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
272   if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
273     auto *Obj = OF.get().get();
274     bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
275     // Find the clang AST section in the container.
276     for (auto &Section : OF->get()->sections()) {
277       StringRef Name;
278       Section.getName(Name);
279       if ((!IsCOFF && Name == "__clangast") ||
280           ( IsCOFF && Name ==   "clangast")) {
281         StringRef Buf;
282         Section.getContents(Buf);
283         StreamFile.init((const unsigned char *)Buf.begin(),
284                         (const unsigned char *)Buf.end());
285         return;
286       }
287     }
288   }
289 
290   // As a fallback, treat the buffer as a raw AST.
291   StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
292                   (const unsigned char *)Buffer.getBufferEnd());
293   return;
294 }
295