ObjectFilePCHContainerOperations.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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), Ctx(nullptr), 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. if (Ctx) {
  69. assert(Ctx == &Context);
  70. return;
  71. }
  72. Ctx = &Context;
  73. VMContext.reset(new llvm::LLVMContext());
  74. M.reset(new llvm::Module(MainFileName, *VMContext));
  75. M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
  76. Builder.reset(new CodeGen::CodeGenModule(
  77. *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
  78. }
  79. /// Emit a container holding the serialized AST.
  80. void HandleTranslationUnit(ASTContext &Ctx) override {
  81. assert(M && VMContext && Builder);
  82. // Delete these on function exit.
  83. std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
  84. std::unique_ptr<llvm::Module> M = std::move(this->M);
  85. std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
  86. if (Diags.hasErrorOccurred())
  87. return;
  88. M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
  89. M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
  90. // Finalize the Builder.
  91. if (Builder)
  92. Builder->Release();
  93. // Ensure the target exists.
  94. std::string Error;
  95. auto Triple = Ctx.getTargetInfo().getTriple();
  96. if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
  97. llvm::report_fatal_error(Error);
  98. // Emit the serialized Clang AST into its own section.
  99. assert(Buffer->IsComplete && "serialization did not complete");
  100. auto &SerializedAST = Buffer->Data;
  101. auto Size = SerializedAST.size();
  102. auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
  103. auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
  104. auto *Data = llvm::ConstantDataArray::getString(
  105. *VMContext, StringRef(SerializedAST.data(), Size),
  106. /*AddNull=*/false);
  107. auto *ASTSym = new llvm::GlobalVariable(
  108. *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
  109. "__clang_ast");
  110. // The on-disk hashtable needs to be aligned.
  111. ASTSym->setAlignment(8);
  112. // Mach-O also needs a segment name.
  113. if (Triple.isOSBinFormatMachO())
  114. ASTSym->setSection("__CLANG,__clangast");
  115. // COFF has an eight character length limit.
  116. else if (Triple.isOSBinFormatCOFF())
  117. ASTSym->setSection("clangast");
  118. else
  119. ASTSym->setSection("__clangast");
  120. DEBUG({
  121. // Print the IR for the PCH container to the debug output.
  122. llvm::SmallString<0> Buffer;
  123. llvm::raw_svector_ostream OS(Buffer);
  124. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  125. Ctx.getTargetInfo().getDataLayoutString(),
  126. M.get(), BackendAction::Backend_EmitLL, &OS);
  127. llvm::dbgs() << Buffer;
  128. });
  129. // Use the LLVM backend to emit the pch container.
  130. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  131. Ctx.getTargetInfo().getDataLayoutString(),
  132. M.get(), BackendAction::Backend_EmitObj, OS);
  133. // Make sure the pch container hits disk.
  134. OS->flush();
  135. // Free the memory for the temporary buffer.
  136. llvm::SmallVector<char, 0> Empty;
  137. SerializedAST = std::move(Empty);
  138. }
  139. };
  140. } // namespace
  141. std::unique_ptr<ASTConsumer>
  142. ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
  143. DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
  144. const PreprocessorOptions &PPO, const TargetOptions &TO,
  145. const LangOptions &LO, const std::string &MainFileName,
  146. const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
  147. std::shared_ptr<PCHBuffer> Buffer) const {
  148. return llvm::make_unique<PCHContainerGenerator>(
  149. Diags, HSO, PPO, TO, LO, MainFileName, OutputFileName, OS, Buffer);
  150. }
  151. void ObjectFilePCHContainerReader::ExtractPCH(
  152. llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
  153. if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
  154. auto *Obj = OF.get().get();
  155. bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
  156. // Find the clang AST section in the container.
  157. for (auto &Section : OF->get()->sections()) {
  158. StringRef Name;
  159. Section.getName(Name);
  160. if ((!IsCOFF && Name == "__clangast") ||
  161. ( IsCOFF && Name == "clangast")) {
  162. StringRef Buf;
  163. Section.getContents(Buf);
  164. StreamFile.init((const unsigned char *)Buf.begin(),
  165. (const unsigned char *)Buf.end());
  166. return;
  167. }
  168. }
  169. }
  170. // As a fallback, treat the buffer as a raw AST.
  171. StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
  172. (const unsigned char *)Buffer.getBufferEnd());
  173. return;
  174. }