blob: 2178ec21c7a27ea63cb8cabcbc8cf0b3c44a4468 [file] [log] [blame]
Adrian Prantlbc068582015-07-08 01:00:30 +00001//===--- 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"
Adrian Prantl03914062015-09-18 22:10:59 +000021#include "clang/Frontend/CompilerInstance.h"
Adrian Prantl9402cef2015-09-20 16:51:35 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Lex/HeaderSearch.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000024#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>
Hans Wennborg7eb54642015-09-10 17:07:54 +000036
Adrian Prantlbc068582015-07-08 01:00:30 +000037using namespace clang;
38
39#define DEBUG_TYPE "pchcontainer"
40
41namespace {
Adrian Prantl5a88e1a2015-07-09 19:46:39 +000042class PCHContainerGenerator : public ASTConsumer {
Adrian Prantlbc068582015-07-08 01:00:30 +000043 DiagnosticsEngine &Diags;
44 const std::string MainFileName;
45 ASTContext *Ctx;
Adrian Prantl9402cef2015-09-20 16:51:35 +000046 ModuleMap &MMap;
Adrian Prantlbc068582015-07-08 01:00:30 +000047 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
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +000058 /// Visit every type and emit debug info for it.
59 struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
60 clang::CodeGen::CGDebugInfo &DI;
61 ASTContext &Ctx;
Adrian Prantlcd975012016-01-19 23:42:44 +000062 DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
63 : DI(DI), Ctx(Ctx) {}
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +000064
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
Adrian Prantl85d938a2015-09-21 17:48:37 +000070 bool VisitImportDecl(ImportDecl *D) {
71 auto *Import = cast<ImportDecl>(D);
72 if (!Import->getImportedOwningModule())
73 DI.EmitImportDecl(*Import);
74 return true;
75 }
76
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +000077 bool VisitTypeDecl(TypeDecl *D) {
Adrian Prantlb3b821f2016-01-06 19:22:19 +000078 // TagDecls may be deferred until after all decls have been merged and we
79 // know the complete type. Pure forward declarations will be skipped, but
80 // they don't need to be emitted into the module anyway.
Adrian Prantlcd975012016-01-19 23:42:44 +000081 if (auto *TD = dyn_cast<TagDecl>(D))
82 if (!TD->isCompleteDefinition())
Adrian Prantlb3b821f2016-01-06 19:22:19 +000083 return true;
84
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +000085 QualType QualTy = Ctx.getTypeDeclType(D);
86 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
87 DI.getOrCreateStandaloneType(QualTy, D->getLocation());
88 return true;
89 }
90
Adrian Prantl748a6cd2015-09-08 20:41:52 +000091 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
92 QualType QualTy(D->getTypeForDecl(), 0);
93 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
94 DI.getOrCreateStandaloneType(QualTy, D->getLocation());
95 return true;
96 }
97
98 bool VisitFunctionDecl(FunctionDecl *D) {
99 if (isa<CXXMethodDecl>(D))
100 // This is not yet supported. Constructing the `this' argument
101 // mandates a CodeGenFunction.
102 return true;
103
104 SmallVector<QualType, 16> ArgTypes;
105 for (auto i : D->params())
106 ArgTypes.push_back(i->getType());
107 QualType RetTy = D->getReturnType();
108 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
109 FunctionProtoType::ExtProtoInfo());
110 if (CanRepresent(FnTy.getTypePtr()))
111 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
112 return true;
113 }
114
115 bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
116 if (!D->getClassInterface())
117 return true;
118
119 bool selfIsPseudoStrong, selfIsConsumed;
120 SmallVector<QualType, 16> ArgTypes;
121 ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
122 selfIsPseudoStrong, selfIsConsumed));
123 ArgTypes.push_back(Ctx.getObjCSelType());
124 for (auto i : D->params())
125 ArgTypes.push_back(i->getType());
126 QualType RetTy = D->getReturnType();
127 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
128 FunctionProtoType::ExtProtoInfo());
129 if (CanRepresent(FnTy.getTypePtr()))
130 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
131 return true;
132 }
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000133 };
134
Adrian Prantlbc068582015-07-08 01:00:30 +0000135public:
Adrian Prantl1e63b2b2015-09-19 21:42:52 +0000136 PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000137 const std::string &OutputFileName,
138 raw_pwrite_stream *OS,
139 std::shared_ptr<PCHBuffer> Buffer)
Adrian Prantl1e63b2b2015-09-19 21:42:52 +0000140 : Diags(CI.getDiagnostics()), Ctx(nullptr),
Adrian Prantl9402cef2015-09-20 16:51:35 +0000141 MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
Adrian Prantl1e63b2b2015-09-19 21:42:52 +0000142 HeaderSearchOpts(CI.getHeaderSearchOpts()),
Adrian Prantl03914062015-09-18 22:10:59 +0000143 PreprocessorOpts(CI.getPreprocessorOpts()),
144 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), OS(OS),
145 Buffer(Buffer) {
Adrian Prantlbc068582015-07-08 01:00:30 +0000146 // The debug info output isn't affected by CodeModel and
147 // ThreadModel, but the backend expects them to be nonempty.
148 CodeGenOpts.CodeModel = "default";
149 CodeGenOpts.ThreadModel = "single";
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000150 CodeGenOpts.DebugTypeExtRefs = true;
Adrian Prantlbc068582015-07-08 01:00:30 +0000151 CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
Adrian Prantlbc068582015-07-08 01:00:30 +0000152 }
153
Hans Wennborg7eb54642015-09-10 17:07:54 +0000154 ~PCHContainerGenerator() override = default;
Adrian Prantlbc068582015-07-08 01:00:30 +0000155
156 void Initialize(ASTContext &Context) override {
Richard Smith293534b2015-08-18 20:39:29 +0000157 assert(!Ctx && "initialized multiple times");
Richard Smith0f99d6a2015-08-09 08:48:41 +0000158
Adrian Prantlbc068582015-07-08 01:00:30 +0000159 Ctx = &Context;
160 VMContext.reset(new llvm::LLVMContext());
161 M.reset(new llvm::Module(MainFileName, *VMContext));
Eric Christopher964a5f32015-08-05 23:48:05 +0000162 M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000163 Builder.reset(new CodeGen::CodeGenModule(
164 *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
Adrian Prantl9402cef2015-09-20 16:51:35 +0000165 Builder->getModuleDebugInfo()->setModuleMap(MMap);
Adrian Prantlbc068582015-07-08 01:00:30 +0000166 }
167
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000168 bool HandleTopLevelDecl(DeclGroupRef D) override {
Adrian Prantlabdd6fc2015-10-23 16:51:32 +0000169 if (Diags.hasErrorOccurred())
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000170 return true;
171
172 // Collect debug info for all decls in this group.
173 for (auto *I : D)
174 if (!I->isFromASTFile()) {
Adrian Prantlcd975012016-01-19 23:42:44 +0000175 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000176 DTV.TraverseDecl(I);
177 }
178 return true;
179 }
180
Adrian Prantld43fe0b2015-10-23 17:02:22 +0000181 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
182 HandleTopLevelDecl(D);
183 }
184
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000185 void HandleTagDeclDefinition(TagDecl *D) override {
186 if (Diags.hasErrorOccurred())
187 return;
188
Adrian Prantlb3b821f2016-01-06 19:22:19 +0000189 if (D->isFromASTFile())
190 return;
191
Adrian Prantle5238d22016-01-19 18:02:47 +0000192 // Anonymous tag decls are deferred until we are building their declcontext.
193 if (D->getName().empty())
194 return;
195
Adrian Prantlcd975012016-01-19 23:42:44 +0000196 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
Adrian Prantlb3b821f2016-01-06 19:22:19 +0000197 DTV.TraverseDecl(D);
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000198 Builder->UpdateCompletedType(D);
199 }
200
201 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
202 if (Diags.hasErrorOccurred())
203 return;
204
Adrian Prantl8bd4c132015-09-19 00:10:25 +0000205 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
206 Builder->getModuleDebugInfo()->completeRequiredType(RD);
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000207 }
208
Adrian Prantlbc068582015-07-08 01:00:30 +0000209 /// Emit a container holding the serialized AST.
210 void HandleTranslationUnit(ASTContext &Ctx) override {
211 assert(M && VMContext && Builder);
212 // Delete these on function exit.
213 std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
214 std::unique_ptr<llvm::Module> M = std::move(this->M);
215 std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
216
217 if (Diags.hasErrorOccurred())
218 return;
219
220 M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
Eric Christopher964a5f32015-08-05 23:48:05 +0000221 M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
Adrian Prantlc96da8f2016-01-22 17:43:43 +0000222
223 // PCH files don't have a signature field in the control block,
224 // but LLVM detects DWO CUs by looking for a non-zero DWO id.
225 uint64_t Signature = Buffer->Signature ? Buffer->Signature : ~1U;
226 Builder->getModuleDebugInfo()->setDwoId(Signature);
Adrian Prantlbc068582015-07-08 01:00:30 +0000227
228 // Finalize the Builder.
229 if (Builder)
230 Builder->Release();
231
232 // Ensure the target exists.
233 std::string Error;
234 auto Triple = Ctx.getTargetInfo().getTriple();
235 if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
236 llvm::report_fatal_error(Error);
237
238 // Emit the serialized Clang AST into its own section.
239 assert(Buffer->IsComplete && "serialization did not complete");
240 auto &SerializedAST = Buffer->Data;
241 auto Size = SerializedAST.size();
242 auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
243 auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000244 auto *Data = llvm::ConstantDataArray::getString(
245 *VMContext, StringRef(SerializedAST.data(), Size),
246 /*AddNull=*/false);
Adrian Prantlbc068582015-07-08 01:00:30 +0000247 auto *ASTSym = new llvm::GlobalVariable(
248 *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
249 "__clang_ast");
250 // The on-disk hashtable needs to be aligned.
251 ASTSym->setAlignment(8);
252
253 // Mach-O also needs a segment name.
254 if (Triple.isOSBinFormatMachO())
255 ASTSym->setSection("__CLANG,__clangast");
256 // COFF has an eight character length limit.
257 else if (Triple.isOSBinFormatCOFF())
258 ASTSym->setSection("clangast");
259 else
260 ASTSym->setSection("__clangast");
261
262 DEBUG({
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000263 // Print the IR for the PCH container to the debug output.
264 llvm::SmallString<0> Buffer;
265 llvm::raw_svector_ostream OS(Buffer);
266 clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
Eric Christopher964a5f32015-08-05 23:48:05 +0000267 Ctx.getTargetInfo().getDataLayoutString(),
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000268 M.get(), BackendAction::Backend_EmitLL, &OS);
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000269 llvm::dbgs() << Buffer;
270 });
Adrian Prantlbc068582015-07-08 01:00:30 +0000271
272 // Use the LLVM backend to emit the pch container.
273 clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
Eric Christopher964a5f32015-08-05 23:48:05 +0000274 Ctx.getTargetInfo().getDataLayoutString(),
Adrian Prantlbc068582015-07-08 01:00:30 +0000275 M.get(), BackendAction::Backend_EmitObj, OS);
276
277 // Make sure the pch container hits disk.
278 OS->flush();
279
280 // Free the memory for the temporary buffer.
281 llvm::SmallVector<char, 0> Empty;
282 SerializedAST = std::move(Empty);
283 }
284};
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000285
Hans Wennborg7eb54642015-09-10 17:07:54 +0000286} // anonymous namespace
Adrian Prantlbc068582015-07-08 01:00:30 +0000287
288std::unique_ptr<ASTConsumer>
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000289ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
Adrian Prantl1e63b2b2015-09-19 21:42:52 +0000290 CompilerInstance &CI, const std::string &MainFileName,
291 const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
292 std::shared_ptr<PCHBuffer> Buffer) const {
293 return llvm::make_unique<PCHContainerGenerator>(CI, MainFileName,
Adrian Prantl03914062015-09-18 22:10:59 +0000294 OutputFileName, OS, Buffer);
Adrian Prantlbc068582015-07-08 01:00:30 +0000295}
296
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000297void ObjectFilePCHContainerReader::ExtractPCH(
Adrian Prantlbc068582015-07-08 01:00:30 +0000298 llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
299 if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
300 auto *Obj = OF.get().get();
301 bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
302 // Find the clang AST section in the container.
303 for (auto &Section : OF->get()->sections()) {
304 StringRef Name;
305 Section.getName(Name);
306 if ((!IsCOFF && Name == "__clangast") ||
307 ( IsCOFF && Name == "clangast")) {
308 StringRef Buf;
309 Section.getContents(Buf);
310 StreamFile.init((const unsigned char *)Buf.begin(),
311 (const unsigned char *)Buf.end());
312 return;
313 }
314 }
315 }
316
317 // As a fallback, treat the buffer as a raw AST.
318 StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
319 (const unsigned char *)Buffer.getBufferEnd());
Adrian Prantlbc068582015-07-08 01:00:30 +0000320}