ObjectFilePCHContainerOperations.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
  10. #include "CGDebugInfo.h"
  11. #include "CodeGenModule.h"
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/DeclObjC.h"
  14. #include "clang/AST/Expr.h"
  15. #include "clang/AST/RecursiveASTVisitor.h"
  16. #include "clang/Basic/Diagnostic.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "clang/CodeGen/BackendUtil.h"
  19. #include "clang/Frontend/CodeGenOptions.h"
  20. #include "clang/Frontend/CompilerInstance.h"
  21. #include "clang/Lex/HeaderSearch.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Serialization/ASTWriter.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/Bitcode/BitstreamReader.h"
  26. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/LLVMContext.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/Object/COFF.h"
  32. #include "llvm/Object/ObjectFile.h"
  33. #include "llvm/Support/Path.h"
  34. #include "llvm/Support/TargetRegistry.h"
  35. #include <memory>
  36. using namespace clang;
  37. #define DEBUG_TYPE "pchcontainer"
  38. namespace {
  39. class PCHContainerGenerator : public ASTConsumer {
  40. DiagnosticsEngine &Diags;
  41. const std::string MainFileName;
  42. const std::string OutputFileName;
  43. ASTContext *Ctx;
  44. ModuleMap &MMap;
  45. const HeaderSearchOptions &HeaderSearchOpts;
  46. const PreprocessorOptions &PreprocessorOpts;
  47. CodeGenOptions CodeGenOpts;
  48. const TargetOptions TargetOpts;
  49. const LangOptions LangOpts;
  50. std::unique_ptr<llvm::LLVMContext> VMContext;
  51. std::unique_ptr<llvm::Module> M;
  52. std::unique_ptr<CodeGen::CodeGenModule> Builder;
  53. raw_pwrite_stream *OS;
  54. std::shared_ptr<PCHBuffer> Buffer;
  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. /// Determine whether this type can be represented in DWARF.
  62. static bool CanRepresent(const Type *Ty) {
  63. return !Ty->isDependentType() && !Ty->isUndeducedType();
  64. }
  65. bool VisitImportDecl(ImportDecl *D) {
  66. auto *Import = cast<ImportDecl>(D);
  67. if (!Import->getImportedOwningModule())
  68. DI.EmitImportDecl(*Import);
  69. return true;
  70. }
  71. bool VisitTypeDecl(TypeDecl *D) {
  72. // TagDecls may be deferred until after all decls have been merged and we
  73. // know the complete type. Pure forward declarations will be skipped, but
  74. // they don't need to be emitted into the module anyway.
  75. if (auto *TD = dyn_cast<TagDecl>(D))
  76. if (!TD->isCompleteDefinition())
  77. return true;
  78. QualType QualTy = Ctx.getTypeDeclType(D);
  79. if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
  80. DI.getOrCreateStandaloneType(QualTy, D->getLocation());
  81. return true;
  82. }
  83. bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
  84. QualType QualTy(D->getTypeForDecl(), 0);
  85. if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
  86. DI.getOrCreateStandaloneType(QualTy, D->getLocation());
  87. return true;
  88. }
  89. bool VisitFunctionDecl(FunctionDecl *D) {
  90. if (isa<CXXMethodDecl>(D))
  91. // This is not yet supported. Constructing the `this' argument
  92. // mandates a CodeGenFunction.
  93. return true;
  94. SmallVector<QualType, 16> ArgTypes;
  95. for (auto i : D->params())
  96. ArgTypes.push_back(i->getType());
  97. QualType RetTy = D->getReturnType();
  98. QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
  99. FunctionProtoType::ExtProtoInfo());
  100. if (CanRepresent(FnTy.getTypePtr()))
  101. DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
  102. return true;
  103. }
  104. bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
  105. if (!D->getClassInterface())
  106. return true;
  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. public:
  123. PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
  124. const std::string &OutputFileName,
  125. raw_pwrite_stream *OS,
  126. std::shared_ptr<PCHBuffer> Buffer)
  127. : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
  128. OutputFileName(OutputFileName), Ctx(nullptr),
  129. MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
  130. HeaderSearchOpts(CI.getHeaderSearchOpts()),
  131. PreprocessorOpts(CI.getPreprocessorOpts()),
  132. TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), OS(OS),
  133. 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.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
  141. }
  142. ~PCHContainerGenerator() override = default;
  143. void Initialize(ASTContext &Context) override {
  144. assert(!Ctx && "initialized multiple times");
  145. Ctx = &Context;
  146. VMContext.reset(new llvm::LLVMContext());
  147. M.reset(new llvm::Module(MainFileName, *VMContext));
  148. M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
  149. Builder.reset(new CodeGen::CodeGenModule(
  150. *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
  151. // Prepare CGDebugInfo to emit debug info for a clang module.
  152. auto *DI = Builder->getModuleDebugInfo();
  153. StringRef ModuleName = llvm::sys::path::filename(MainFileName);
  154. DI->setPCHDescriptor({ModuleName, "", OutputFileName, ~1ULL});
  155. DI->setModuleMap(MMap);
  156. }
  157. bool HandleTopLevelDecl(DeclGroupRef D) override {
  158. if (Diags.hasErrorOccurred())
  159. return true;
  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. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
  169. HandleTopLevelDecl(D);
  170. }
  171. void HandleTagDeclDefinition(TagDecl *D) override {
  172. if (Diags.hasErrorOccurred())
  173. return;
  174. if (D->isFromASTFile())
  175. return;
  176. // Anonymous tag decls are deferred until we are building their declcontext.
  177. if (D->getName().empty())
  178. return;
  179. // Defer tag decls until their declcontext is complete.
  180. auto *DeclCtx = D->getDeclContext();
  181. while (DeclCtx) {
  182. if (auto *D = dyn_cast<TagDecl>(DeclCtx))
  183. if (!D->isCompleteDefinition())
  184. return;
  185. DeclCtx = DeclCtx->getParent();
  186. }
  187. DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
  188. DTV.TraverseDecl(D);
  189. Builder->UpdateCompletedType(D);
  190. }
  191. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  192. if (Diags.hasErrorOccurred())
  193. return;
  194. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  195. Builder->getModuleDebugInfo()->completeRequiredType(RD);
  196. }
  197. /// Emit a container holding the serialized AST.
  198. void HandleTranslationUnit(ASTContext &Ctx) override {
  199. assert(M && VMContext && Builder);
  200. // Delete these on function exit.
  201. std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
  202. std::unique_ptr<llvm::Module> M = std::move(this->M);
  203. std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
  204. if (Diags.hasErrorOccurred())
  205. return;
  206. M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
  207. M->setDataLayout(Ctx.getTargetInfo().getDataLayout());
  208. // PCH files don't have a signature field in the control block,
  209. // but LLVM detects DWO CUs by looking for a non-zero DWO id.
  210. uint64_t Signature = Buffer->Signature ? Buffer->Signature : ~1ULL;
  211. Builder->getModuleDebugInfo()->setDwoId(Signature);
  212. // Finalize the Builder.
  213. if (Builder)
  214. Builder->Release();
  215. // Ensure the target exists.
  216. std::string Error;
  217. auto Triple = Ctx.getTargetInfo().getTriple();
  218. if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
  219. llvm::report_fatal_error(Error);
  220. // Emit the serialized Clang AST into its own section.
  221. assert(Buffer->IsComplete && "serialization did not complete");
  222. auto &SerializedAST = Buffer->Data;
  223. auto Size = SerializedAST.size();
  224. auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
  225. auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
  226. auto *Data = llvm::ConstantDataArray::getString(
  227. *VMContext, StringRef(SerializedAST.data(), Size),
  228. /*AddNull=*/false);
  229. auto *ASTSym = new llvm::GlobalVariable(
  230. *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
  231. "__clang_ast");
  232. // The on-disk hashtable needs to be aligned.
  233. ASTSym->setAlignment(8);
  234. // Mach-O also needs a segment name.
  235. if (Triple.isOSBinFormatMachO())
  236. ASTSym->setSection("__CLANG,__clangast");
  237. // COFF has an eight character length limit.
  238. else if (Triple.isOSBinFormatCOFF())
  239. ASTSym->setSection("clangast");
  240. else
  241. ASTSym->setSection("__clangast");
  242. DEBUG({
  243. // Print the IR for the PCH container to the debug output.
  244. llvm::SmallString<0> Buffer;
  245. llvm::raw_svector_ostream OS(Buffer);
  246. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  247. Ctx.getTargetInfo().getDataLayout(), M.get(),
  248. BackendAction::Backend_EmitLL, &OS);
  249. llvm::dbgs() << Buffer;
  250. });
  251. // Use the LLVM backend to emit the pch container.
  252. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  253. Ctx.getTargetInfo().getDataLayout(), M.get(),
  254. BackendAction::Backend_EmitObj, OS);
  255. // Make sure the pch container hits disk.
  256. OS->flush();
  257. // Free the memory for the temporary buffer.
  258. llvm::SmallVector<char, 0> Empty;
  259. SerializedAST = std::move(Empty);
  260. }
  261. };
  262. } // anonymous namespace
  263. std::unique_ptr<ASTConsumer>
  264. ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
  265. CompilerInstance &CI, const std::string &MainFileName,
  266. const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
  267. std::shared_ptr<PCHBuffer> Buffer) const {
  268. return llvm::make_unique<PCHContainerGenerator>(CI, MainFileName,
  269. OutputFileName, OS, Buffer);
  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. // 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. }