blob: d0760b9cc2a60a989418676a1d3b195439652809 [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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000020#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/HeaderSearch.h"
Adrian Prantl3a2d4942016-01-22 23:30:56 +000023#include "clang/Lex/Preprocessor.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"
Adrian Prantl3a2d4942016-01-22 23:30:56 +000034#include "llvm/Support/Path.h"
Adrian Prantlbc068582015-07-08 01:00:30 +000035#include "llvm/Support/TargetRegistry.h"
36#include <memory>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000037#include <utility>
Hans Wennborg7eb54642015-09-10 17:07:54 +000038
Adrian Prantlbc068582015-07-08 01:00:30 +000039using namespace clang;
40
41#define DEBUG_TYPE "pchcontainer"
42
43namespace {
Adrian Prantl5a88e1a2015-07-09 19:46:39 +000044class PCHContainerGenerator : public ASTConsumer {
Adrian Prantlbc068582015-07-08 01:00:30 +000045 DiagnosticsEngine &Diags;
46 const std::string MainFileName;
Adrian Prantlaa5d08d2016-01-22 21:14:41 +000047 const std::string OutputFileName;
Adrian Prantlbc068582015-07-08 01:00:30 +000048 ASTContext *Ctx;
Adrian Prantl9402cef2015-09-20 16:51:35 +000049 ModuleMap &MMap;
Adrian Prantlbc068582015-07-08 01:00:30 +000050 const HeaderSearchOptions &HeaderSearchOpts;
51 const PreprocessorOptions &PreprocessorOpts;
52 CodeGenOptions CodeGenOpts;
53 const TargetOptions TargetOpts;
54 const LangOptions LangOpts;
55 std::unique_ptr<llvm::LLVMContext> VMContext;
56 std::unique_ptr<llvm::Module> M;
57 std::unique_ptr<CodeGen::CodeGenModule> Builder;
Peter Collingbourne03f89072016-07-15 00:55:40 +000058 std::unique_ptr<raw_pwrite_stream> OS;
Adrian Prantlbc068582015-07-08 01:00:30 +000059 std::shared_ptr<PCHBuffer> Buffer;
60
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +000061 /// Visit every type and emit debug info for it.
62 struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
63 clang::CodeGen::CGDebugInfo &DI;
64 ASTContext &Ctx;
Adrian Prantlcd975012016-01-19 23:42:44 +000065 DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
66 : DI(DI), Ctx(Ctx) {}
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +000067
68 /// Determine whether this type can be represented in DWARF.
69 static bool CanRepresent(const Type *Ty) {
70 return !Ty->isDependentType() && !Ty->isUndeducedType();
71 }
72
Adrian Prantl85d938a2015-09-21 17:48:37 +000073 bool VisitImportDecl(ImportDecl *D) {
74 auto *Import = cast<ImportDecl>(D);
75 if (!Import->getImportedOwningModule())
76 DI.EmitImportDecl(*Import);
77 return true;
78 }
79
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +000080 bool VisitTypeDecl(TypeDecl *D) {
Adrian Prantlb3b821f2016-01-06 19:22:19 +000081 // TagDecls may be deferred until after all decls have been merged and we
82 // know the complete type. Pure forward declarations will be skipped, but
83 // they don't need to be emitted into the module anyway.
Adrian Prantlcd975012016-01-19 23:42:44 +000084 if (auto *TD = dyn_cast<TagDecl>(D))
85 if (!TD->isCompleteDefinition())
Adrian Prantlb3b821f2016-01-06 19:22:19 +000086 return true;
87
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +000088 QualType QualTy = Ctx.getTypeDeclType(D);
89 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
90 DI.getOrCreateStandaloneType(QualTy, D->getLocation());
91 return true;
92 }
93
Adrian Prantl748a6cd2015-09-08 20:41:52 +000094 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
95 QualType QualTy(D->getTypeForDecl(), 0);
96 if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
97 DI.getOrCreateStandaloneType(QualTy, D->getLocation());
98 return true;
99 }
100
101 bool VisitFunctionDecl(FunctionDecl *D) {
102 if (isa<CXXMethodDecl>(D))
103 // This is not yet supported. Constructing the `this' argument
104 // mandates a CodeGenFunction.
105 return true;
106
107 SmallVector<QualType, 16> ArgTypes;
David Majnemer59f77922016-06-24 04:05:48 +0000108 for (auto i : D->parameters())
Adrian Prantl748a6cd2015-09-08 20:41:52 +0000109 ArgTypes.push_back(i->getType());
110 QualType RetTy = D->getReturnType();
111 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
112 FunctionProtoType::ExtProtoInfo());
113 if (CanRepresent(FnTy.getTypePtr()))
114 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
115 return true;
116 }
117
118 bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
119 if (!D->getClassInterface())
120 return true;
121
122 bool selfIsPseudoStrong, selfIsConsumed;
123 SmallVector<QualType, 16> ArgTypes;
124 ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
125 selfIsPseudoStrong, selfIsConsumed));
126 ArgTypes.push_back(Ctx.getObjCSelType());
David Majnemer59f77922016-06-24 04:05:48 +0000127 for (auto i : D->parameters())
Adrian Prantl748a6cd2015-09-08 20:41:52 +0000128 ArgTypes.push_back(i->getType());
129 QualType RetTy = D->getReturnType();
130 QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
131 FunctionProtoType::ExtProtoInfo());
132 if (CanRepresent(FnTy.getTypePtr()))
133 DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
134 return true;
135 }
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000136 };
137
Adrian Prantlbc068582015-07-08 01:00:30 +0000138public:
Adrian Prantl1e63b2b2015-09-19 21:42:52 +0000139 PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000140 const std::string &OutputFileName,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000141 std::unique_ptr<raw_pwrite_stream> OS,
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000142 std::shared_ptr<PCHBuffer> Buffer)
Adrian Prantlaa5d08d2016-01-22 21:14:41 +0000143 : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
144 OutputFileName(OutputFileName), Ctx(nullptr),
Adrian Prantl9402cef2015-09-20 16:51:35 +0000145 MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
Adrian Prantl1e63b2b2015-09-19 21:42:52 +0000146 HeaderSearchOpts(CI.getHeaderSearchOpts()),
Adrian Prantl03914062015-09-18 22:10:59 +0000147 PreprocessorOpts(CI.getPreprocessorOpts()),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000148 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
149 OS(std::move(OS)), Buffer(std::move(Buffer)) {
Adrian Prantlbc068582015-07-08 01:00:30 +0000150 // The debug info output isn't affected by CodeModel and
151 // ThreadModel, but the backend expects them to be nonempty.
152 CodeGenOpts.CodeModel = "default";
153 CodeGenOpts.ThreadModel = "single";
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000154 CodeGenOpts.DebugTypeExtRefs = true;
Adrian Prantl9a1a1aa2017-07-18 23:58:34 +0000155 // When building a module MainFileName is the name of the modulemap file.
156 CodeGenOpts.MainFileName =
157 LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule;
Benjamin Kramer8c305922016-02-02 11:06:51 +0000158 CodeGenOpts.setDebugInfo(codegenoptions::FullDebugInfo);
David Blaikieaf09f4a2016-05-03 23:06:40 +0000159 CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
Adrian Prantlbc068582015-07-08 01:00:30 +0000160 }
161
Hans Wennborg7eb54642015-09-10 17:07:54 +0000162 ~PCHContainerGenerator() override = default;
Adrian Prantlbc068582015-07-08 01:00:30 +0000163
164 void Initialize(ASTContext &Context) override {
Richard Smith293534b2015-08-18 20:39:29 +0000165 assert(!Ctx && "initialized multiple times");
Richard Smith0f99d6a2015-08-09 08:48:41 +0000166
Adrian Prantlbc068582015-07-08 01:00:30 +0000167 Ctx = &Context;
168 VMContext.reset(new llvm::LLVMContext());
169 M.reset(new llvm::Module(MainFileName, *VMContext));
James Y Knightb214cbc2016-03-04 19:00:41 +0000170 M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000171 Builder.reset(new CodeGen::CodeGenModule(
172 *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
Adrian Prantl3a2d4942016-01-22 23:30:56 +0000173
174 // Prepare CGDebugInfo to emit debug info for a clang module.
175 auto *DI = Builder->getModuleDebugInfo();
176 StringRef ModuleName = llvm::sys::path::filename(MainFileName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000177 DI->setPCHDescriptor({ModuleName, "", OutputFileName,
178 ASTFileSignature{{{~0U, ~0U, ~0U, ~0U, ~1U}}}});
Adrian Prantl3a2d4942016-01-22 23:30:56 +0000179 DI->setModuleMap(MMap);
Adrian Prantlbc068582015-07-08 01:00:30 +0000180 }
181
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000182 bool HandleTopLevelDecl(DeclGroupRef D) override {
Adrian Prantlabdd6fc2015-10-23 16:51:32 +0000183 if (Diags.hasErrorOccurred())
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000184 return true;
185
186 // Collect debug info for all decls in this group.
187 for (auto *I : D)
188 if (!I->isFromASTFile()) {
Adrian Prantlcd975012016-01-19 23:42:44 +0000189 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000190 DTV.TraverseDecl(I);
191 }
192 return true;
193 }
194
Adrian Prantld43fe0b2015-10-23 17:02:22 +0000195 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
196 HandleTopLevelDecl(D);
197 }
198
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000199 void HandleTagDeclDefinition(TagDecl *D) override {
200 if (Diags.hasErrorOccurred())
201 return;
202
Adrian Prantlb3b821f2016-01-06 19:22:19 +0000203 if (D->isFromASTFile())
204 return;
205
Adrian Prantle5238d22016-01-19 18:02:47 +0000206 // Anonymous tag decls are deferred until we are building their declcontext.
207 if (D->getName().empty())
208 return;
209
Adrian Prantl5a9a4272016-03-07 20:58:52 +0000210 // Defer tag decls until their declcontext is complete.
211 auto *DeclCtx = D->getDeclContext();
212 while (DeclCtx) {
213 if (auto *D = dyn_cast<TagDecl>(DeclCtx))
214 if (!D->isCompleteDefinition())
215 return;
216 DeclCtx = DeclCtx->getParent();
217 }
218
Adrian Prantlcd975012016-01-19 23:42:44 +0000219 DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
Adrian Prantlb3b821f2016-01-06 19:22:19 +0000220 DTV.TraverseDecl(D);
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000221 Builder->UpdateCompletedType(D);
222 }
223
224 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
225 if (Diags.hasErrorOccurred())
226 return;
227
Adrian Prantl8bd4c132015-09-19 00:10:25 +0000228 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
229 Builder->getModuleDebugInfo()->completeRequiredType(RD);
Adrian Prantl4aa2b3a2015-09-08 19:20:27 +0000230 }
231
Adrian Prantlbc068582015-07-08 01:00:30 +0000232 /// Emit a container holding the serialized AST.
233 void HandleTranslationUnit(ASTContext &Ctx) override {
234 assert(M && VMContext && Builder);
235 // Delete these on function exit.
236 std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
237 std::unique_ptr<llvm::Module> M = std::move(this->M);
238 std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
239
240 if (Diags.hasErrorOccurred())
241 return;
242
243 M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
James Y Knightb214cbc2016-03-04 19:00:41 +0000244 M->setDataLayout(Ctx.getTargetInfo().getDataLayout());
Adrian Prantlc96da8f2016-01-22 17:43:43 +0000245
246 // PCH files don't have a signature field in the control block,
247 // but LLVM detects DWO CUs by looking for a non-zero DWO id.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000248 // We use the lower 64 bits for debug info.
249 uint64_t Signature =
250 Buffer->Signature
251 ? (uint64_t)Buffer->Signature[1] << 32 | Buffer->Signature[0]
252 : ~1ULL;
Adrian Prantlc96da8f2016-01-22 17:43:43 +0000253 Builder->getModuleDebugInfo()->setDwoId(Signature);
Adrian Prantlbc068582015-07-08 01:00:30 +0000254
255 // Finalize the Builder.
256 if (Builder)
257 Builder->Release();
258
259 // Ensure the target exists.
260 std::string Error;
261 auto Triple = Ctx.getTargetInfo().getTriple();
262 if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
263 llvm::report_fatal_error(Error);
264
265 // Emit the serialized Clang AST into its own section.
266 assert(Buffer->IsComplete && "serialization did not complete");
267 auto &SerializedAST = Buffer->Data;
268 auto Size = SerializedAST.size();
269 auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
270 auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000271 auto *Data = llvm::ConstantDataArray::getString(
272 *VMContext, StringRef(SerializedAST.data(), Size),
273 /*AddNull=*/false);
Adrian Prantlbc068582015-07-08 01:00:30 +0000274 auto *ASTSym = new llvm::GlobalVariable(
275 *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
276 "__clang_ast");
277 // The on-disk hashtable needs to be aligned.
278 ASTSym->setAlignment(8);
279
280 // Mach-O also needs a segment name.
281 if (Triple.isOSBinFormatMachO())
282 ASTSym->setSection("__CLANG,__clangast");
283 // COFF has an eight character length limit.
284 else if (Triple.isOSBinFormatCOFF())
285 ASTSym->setSection("clangast");
286 else
287 ASTSym->setSection("__clangast");
288
289 DEBUG({
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000290 // Print the IR for the PCH container to the debug output.
291 llvm::SmallString<0> Buffer;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000292 clang::EmitBackendOutput(
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000293 Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000294 Ctx.getTargetInfo().getDataLayout(), M.get(),
295 BackendAction::Backend_EmitLL,
296 llvm::make_unique<llvm::raw_svector_ostream>(Buffer));
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000297 llvm::dbgs() << Buffer;
298 });
Adrian Prantlbc068582015-07-08 01:00:30 +0000299
300 // Use the LLVM backend to emit the pch container.
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000301 clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
302 LangOpts, Ctx.getTargetInfo().getDataLayout(),
303 M.get(), BackendAction::Backend_EmitObj,
304 std::move(OS));
Adrian Prantlbc068582015-07-08 01:00:30 +0000305
306 // Free the memory for the temporary buffer.
307 llvm::SmallVector<char, 0> Empty;
308 SerializedAST = std::move(Empty);
309 }
310};
Adrian Prantl5a88e1a2015-07-09 19:46:39 +0000311
Hans Wennborg7eb54642015-09-10 17:07:54 +0000312} // anonymous namespace
Adrian Prantlbc068582015-07-08 01:00:30 +0000313
314std::unique_ptr<ASTConsumer>
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000315ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
Adrian Prantl1e63b2b2015-09-19 21:42:52 +0000316 CompilerInstance &CI, const std::string &MainFileName,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000317 const std::string &OutputFileName,
318 std::unique_ptr<llvm::raw_pwrite_stream> OS,
Adrian Prantl1e63b2b2015-09-19 21:42:52 +0000319 std::shared_ptr<PCHBuffer> Buffer) const {
Peter Collingbourne03f89072016-07-15 00:55:40 +0000320 return llvm::make_unique<PCHContainerGenerator>(
321 CI, MainFileName, OutputFileName, std::move(OS), Buffer);
Adrian Prantlbc068582015-07-08 01:00:30 +0000322}
323
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000324StringRef
325ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
326 StringRef PCH;
Adrian Prantl576b2db2016-08-17 23:13:53 +0000327 auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
328 if (OFOrErr) {
329 auto &OF = OFOrErr.get();
330 bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF);
Adrian Prantlbc068582015-07-08 01:00:30 +0000331 // Find the clang AST section in the container.
Adrian Prantl576b2db2016-08-17 23:13:53 +0000332 for (auto &Section : OF->sections()) {
Adrian Prantlbc068582015-07-08 01:00:30 +0000333 StringRef Name;
334 Section.getName(Name);
Adrian Prantl576b2db2016-08-17 23:13:53 +0000335 if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) {
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000336 Section.getContents(PCH);
337 return PCH;
Adrian Prantlbc068582015-07-08 01:00:30 +0000338 }
339 }
340 }
Adrian Prantl576b2db2016-08-17 23:13:53 +0000341 handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
342 if (EIB.convertToErrorCode() ==
343 llvm::object::object_error::invalid_file_type)
344 // As a fallback, treat the buffer as a raw AST.
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000345 PCH = Buffer.getBuffer();
Adrian Prantl576b2db2016-08-17 23:13:53 +0000346 else
347 EIB.log(llvm::errs());
348 });
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000349 return PCH;
Adrian Prantlbc068582015-07-08 01:00:30 +0000350}