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