ObjectFilePCHContainerOperations.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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/Serialization/ASTWriter.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/Bitcode/BitstreamReader.h"
  23. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  24. #include "llvm/IR/Constants.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/LLVMContext.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/Object/COFF.h"
  29. #include "llvm/Object/ObjectFile.h"
  30. #include "llvm/Support/TargetRegistry.h"
  31. #include <memory>
  32. using namespace clang;
  33. #define DEBUG_TYPE "pchcontainer"
  34. namespace {
  35. class PCHContainerGenerator : public ASTConsumer {
  36. DiagnosticsEngine &Diags;
  37. const std::string MainFileName;
  38. ASTContext *Ctx;
  39. const HeaderSearchOptions &HeaderSearchOpts;
  40. const PreprocessorOptions &PreprocessorOpts;
  41. CodeGenOptions CodeGenOpts;
  42. const TargetOptions TargetOpts;
  43. const LangOptions LangOpts;
  44. std::unique_ptr<llvm::LLVMContext> VMContext;
  45. std::unique_ptr<llvm::Module> M;
  46. std::unique_ptr<CodeGen::CodeGenModule> Builder;
  47. raw_pwrite_stream *OS;
  48. std::shared_ptr<PCHBuffer> Buffer;
  49. public:
  50. PCHContainerGenerator(DiagnosticsEngine &diags,
  51. const HeaderSearchOptions &HSO,
  52. const PreprocessorOptions &PPO, const TargetOptions &TO,
  53. const LangOptions &LO, const std::string &MainFileName,
  54. const std::string &OutputFileName,
  55. raw_pwrite_stream *OS,
  56. std::shared_ptr<PCHBuffer> Buffer)
  57. : Diags(diags), HeaderSearchOpts(HSO), PreprocessorOpts(PPO),
  58. TargetOpts(TO), LangOpts(LO), OS(OS), Buffer(Buffer) {
  59. // The debug info output isn't affected by CodeModel and
  60. // ThreadModel, but the backend expects them to be nonempty.
  61. CodeGenOpts.CodeModel = "default";
  62. CodeGenOpts.ThreadModel = "single";
  63. CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
  64. CodeGenOpts.SplitDwarfFile = OutputFileName;
  65. }
  66. virtual ~PCHContainerGenerator() {}
  67. void Initialize(ASTContext &Context) override {
  68. Ctx = &Context;
  69. VMContext.reset(new llvm::LLVMContext());
  70. M.reset(new llvm::Module(MainFileName, *VMContext));
  71. M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
  72. Builder.reset(new CodeGen::CodeGenModule(*Ctx, HeaderSearchOpts,
  73. PreprocessorOpts, CodeGenOpts, *M,
  74. M->getDataLayout(), Diags));
  75. }
  76. /// Emit a container holding the serialized AST.
  77. void HandleTranslationUnit(ASTContext &Ctx) override {
  78. assert(M && VMContext && Builder);
  79. // Delete these on function exit.
  80. std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
  81. std::unique_ptr<llvm::Module> M = std::move(this->M);
  82. std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
  83. if (Diags.hasErrorOccurred())
  84. return;
  85. M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
  86. M->setDataLayout(Ctx.getTargetInfo().getTargetDescription());
  87. // Finalize the Builder.
  88. if (Builder)
  89. Builder->Release();
  90. // Ensure the target exists.
  91. std::string Error;
  92. auto Triple = Ctx.getTargetInfo().getTriple();
  93. if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
  94. llvm::report_fatal_error(Error);
  95. // Emit the serialized Clang AST into its own section.
  96. assert(Buffer->IsComplete && "serialization did not complete");
  97. auto &SerializedAST = Buffer->Data;
  98. auto Size = SerializedAST.size();
  99. auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
  100. auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
  101. auto *Data = llvm::ConstantDataArray::getString(
  102. *VMContext, StringRef(SerializedAST.data(), Size),
  103. /*AddNull=*/false);
  104. auto *ASTSym = new llvm::GlobalVariable(
  105. *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
  106. "__clang_ast");
  107. // The on-disk hashtable needs to be aligned.
  108. ASTSym->setAlignment(8);
  109. // Mach-O also needs a segment name.
  110. if (Triple.isOSBinFormatMachO())
  111. ASTSym->setSection("__CLANG,__clangast");
  112. // COFF has an eight character length limit.
  113. else if (Triple.isOSBinFormatCOFF())
  114. ASTSym->setSection("clangast");
  115. else
  116. ASTSym->setSection("__clangast");
  117. DEBUG({
  118. // Print the IR for the PCH container to the debug output.
  119. llvm::SmallString<0> Buffer;
  120. llvm::raw_svector_ostream OS(Buffer);
  121. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  122. Ctx.getTargetInfo().getTargetDescription(),
  123. M.get(), BackendAction::Backend_EmitLL, &OS);
  124. OS.flush();
  125. llvm::dbgs() << Buffer;
  126. });
  127. // Use the LLVM backend to emit the pch container.
  128. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  129. Ctx.getTargetInfo().getTargetDescription(),
  130. M.get(), BackendAction::Backend_EmitObj, OS);
  131. // Make sure the pch container hits disk.
  132. OS->flush();
  133. // Free the memory for the temporary buffer.
  134. llvm::SmallVector<char, 0> Empty;
  135. SerializedAST = std::move(Empty);
  136. }
  137. };
  138. } // namespace
  139. std::unique_ptr<ASTConsumer>
  140. ObjectFilePCHContainerOperations::CreatePCHContainerGenerator(
  141. DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
  142. const PreprocessorOptions &PPO, const TargetOptions &TO,
  143. const LangOptions &LO, const std::string &MainFileName,
  144. const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
  145. std::shared_ptr<PCHBuffer> Buffer) const {
  146. return llvm::make_unique<PCHContainerGenerator>(
  147. Diags, HSO, PPO, TO, LO, MainFileName, OutputFileName, OS, Buffer);
  148. }
  149. void ObjectFilePCHContainerOperations::ExtractPCH(
  150. llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
  151. if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
  152. auto *Obj = OF.get().get();
  153. bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
  154. // Find the clang AST section in the container.
  155. for (auto &Section : OF->get()->sections()) {
  156. StringRef Name;
  157. Section.getName(Name);
  158. if ((!IsCOFF && Name == "__clangast") ||
  159. ( IsCOFF && Name == "clangast")) {
  160. StringRef Buf;
  161. Section.getContents(Buf);
  162. StreamFile.init((const unsigned char *)Buf.begin(),
  163. (const unsigned char *)Buf.end());
  164. return;
  165. }
  166. }
  167. }
  168. // As a fallback, treat the buffer as a raw AST.
  169. StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
  170. (const unsigned char *)Buffer.getBufferEnd());
  171. return;
  172. }