ObjectFilePCHContainerOperations.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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/Preprocessor.h"
  22. #include "clang/Lex/HeaderSearch.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/TargetRegistry.h"
  34. #include <memory>
  35. using namespace clang;
  36. #define DEBUG_TYPE "pchcontainer"
  37. namespace {
  38. class PCHContainerGenerator : public ASTConsumer {
  39. DiagnosticsEngine &Diags;
  40. const std::string MainFileName;
  41. ASTContext *Ctx;
  42. ModuleMap &MMap;
  43. const HeaderSearchOptions &HeaderSearchOpts;
  44. const PreprocessorOptions &PreprocessorOpts;
  45. CodeGenOptions CodeGenOpts;
  46. const TargetOptions TargetOpts;
  47. const LangOptions LangOpts;
  48. std::unique_ptr<llvm::LLVMContext> VMContext;
  49. std::unique_ptr<llvm::Module> M;
  50. std::unique_ptr<CodeGen::CodeGenModule> Builder;
  51. raw_pwrite_stream *OS;
  52. std::shared_ptr<PCHBuffer> Buffer;
  53. /// Visit every type and emit debug info for it.
  54. struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
  55. clang::CodeGen::CGDebugInfo &DI;
  56. ASTContext &Ctx;
  57. DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
  58. : DI(DI), Ctx(Ctx) {}
  59. /// Determine whether this type can be represented in DWARF.
  60. static bool CanRepresent(const Type *Ty) {
  61. return !Ty->isDependentType() && !Ty->isUndeducedType();
  62. }
  63. bool VisitImportDecl(ImportDecl *D) {
  64. auto *Import = cast<ImportDecl>(D);
  65. if (!Import->getImportedOwningModule())
  66. DI.EmitImportDecl(*Import);
  67. return true;
  68. }
  69. bool VisitTypeDecl(TypeDecl *D) {
  70. QualType QualTy = Ctx.getTypeDeclType(D);
  71. if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
  72. DI.getOrCreateStandaloneType(QualTy, D->getLocation());
  73. return true;
  74. }
  75. bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
  76. QualType QualTy(D->getTypeForDecl(), 0);
  77. if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
  78. DI.getOrCreateStandaloneType(QualTy, D->getLocation());
  79. return true;
  80. }
  81. bool VisitFunctionDecl(FunctionDecl *D) {
  82. if (isa<CXXMethodDecl>(D))
  83. // This is not yet supported. Constructing the `this' argument
  84. // mandates a CodeGenFunction.
  85. return true;
  86. SmallVector<QualType, 16> ArgTypes;
  87. for (auto i : D->params())
  88. ArgTypes.push_back(i->getType());
  89. QualType RetTy = D->getReturnType();
  90. QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
  91. FunctionProtoType::ExtProtoInfo());
  92. if (CanRepresent(FnTy.getTypePtr()))
  93. DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
  94. return true;
  95. }
  96. bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
  97. if (!D->getClassInterface())
  98. return true;
  99. bool selfIsPseudoStrong, selfIsConsumed;
  100. SmallVector<QualType, 16> ArgTypes;
  101. ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
  102. selfIsPseudoStrong, selfIsConsumed));
  103. ArgTypes.push_back(Ctx.getObjCSelType());
  104. for (auto i : D->params())
  105. ArgTypes.push_back(i->getType());
  106. QualType RetTy = D->getReturnType();
  107. QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
  108. FunctionProtoType::ExtProtoInfo());
  109. if (CanRepresent(FnTy.getTypePtr()))
  110. DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
  111. return true;
  112. }
  113. };
  114. public:
  115. PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
  116. const std::string &OutputFileName,
  117. raw_pwrite_stream *OS,
  118. std::shared_ptr<PCHBuffer> Buffer)
  119. : Diags(CI.getDiagnostics()), Ctx(nullptr),
  120. MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
  121. HeaderSearchOpts(CI.getHeaderSearchOpts()),
  122. PreprocessorOpts(CI.getPreprocessorOpts()),
  123. TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), OS(OS),
  124. Buffer(Buffer) {
  125. // The debug info output isn't affected by CodeModel and
  126. // ThreadModel, but the backend expects them to be nonempty.
  127. CodeGenOpts.CodeModel = "default";
  128. CodeGenOpts.ThreadModel = "single";
  129. CodeGenOpts.DebugTypeExtRefs = true;
  130. CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
  131. }
  132. ~PCHContainerGenerator() override = default;
  133. void Initialize(ASTContext &Context) override {
  134. assert(!Ctx && "initialized multiple times");
  135. Ctx = &Context;
  136. VMContext.reset(new llvm::LLVMContext());
  137. M.reset(new llvm::Module(MainFileName, *VMContext));
  138. M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
  139. Builder.reset(new CodeGen::CodeGenModule(
  140. *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
  141. Builder->getModuleDebugInfo()->setModuleMap(MMap);
  142. }
  143. bool HandleTopLevelDecl(DeclGroupRef D) override {
  144. if (Diags.hasErrorOccurred())
  145. return true;
  146. // Collect debug info for all decls in this group.
  147. for (auto *I : D)
  148. if (!I->isFromASTFile()) {
  149. DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
  150. DTV.TraverseDecl(I);
  151. }
  152. return true;
  153. }
  154. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
  155. HandleTopLevelDecl(D);
  156. }
  157. void HandleTagDeclDefinition(TagDecl *D) override {
  158. if (Diags.hasErrorOccurred())
  159. return;
  160. Builder->UpdateCompletedType(D);
  161. }
  162. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  163. if (Diags.hasErrorOccurred())
  164. return;
  165. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  166. Builder->getModuleDebugInfo()->completeRequiredType(RD);
  167. }
  168. /// Emit a container holding the serialized AST.
  169. void HandleTranslationUnit(ASTContext &Ctx) override {
  170. assert(M && VMContext && Builder);
  171. // Delete these on function exit.
  172. std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
  173. std::unique_ptr<llvm::Module> M = std::move(this->M);
  174. std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
  175. if (Diags.hasErrorOccurred())
  176. return;
  177. M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
  178. M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
  179. Builder->getModuleDebugInfo()->setDwoId(Buffer->Signature);
  180. // Finalize the Builder.
  181. if (Builder)
  182. Builder->Release();
  183. // Ensure the target exists.
  184. std::string Error;
  185. auto Triple = Ctx.getTargetInfo().getTriple();
  186. if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
  187. llvm::report_fatal_error(Error);
  188. // Emit the serialized Clang AST into its own section.
  189. assert(Buffer->IsComplete && "serialization did not complete");
  190. auto &SerializedAST = Buffer->Data;
  191. auto Size = SerializedAST.size();
  192. auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
  193. auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
  194. auto *Data = llvm::ConstantDataArray::getString(
  195. *VMContext, StringRef(SerializedAST.data(), Size),
  196. /*AddNull=*/false);
  197. auto *ASTSym = new llvm::GlobalVariable(
  198. *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
  199. "__clang_ast");
  200. // The on-disk hashtable needs to be aligned.
  201. ASTSym->setAlignment(8);
  202. // Mach-O also needs a segment name.
  203. if (Triple.isOSBinFormatMachO())
  204. ASTSym->setSection("__CLANG,__clangast");
  205. // COFF has an eight character length limit.
  206. else if (Triple.isOSBinFormatCOFF())
  207. ASTSym->setSection("clangast");
  208. else
  209. ASTSym->setSection("__clangast");
  210. DEBUG({
  211. // Print the IR for the PCH container to the debug output.
  212. llvm::SmallString<0> Buffer;
  213. llvm::raw_svector_ostream OS(Buffer);
  214. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  215. Ctx.getTargetInfo().getDataLayoutString(),
  216. M.get(), BackendAction::Backend_EmitLL, &OS);
  217. llvm::dbgs() << Buffer;
  218. });
  219. // Use the LLVM backend to emit the pch container.
  220. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  221. Ctx.getTargetInfo().getDataLayoutString(),
  222. M.get(), BackendAction::Backend_EmitObj, OS);
  223. // Make sure the pch container hits disk.
  224. OS->flush();
  225. // Free the memory for the temporary buffer.
  226. llvm::SmallVector<char, 0> Empty;
  227. SerializedAST = std::move(Empty);
  228. }
  229. };
  230. } // anonymous namespace
  231. std::unique_ptr<ASTConsumer>
  232. ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
  233. CompilerInstance &CI, const std::string &MainFileName,
  234. const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
  235. std::shared_ptr<PCHBuffer> Buffer) const {
  236. return llvm::make_unique<PCHContainerGenerator>(CI, MainFileName,
  237. OutputFileName, OS, Buffer);
  238. }
  239. void ObjectFilePCHContainerReader::ExtractPCH(
  240. llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
  241. if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
  242. auto *Obj = OF.get().get();
  243. bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
  244. // Find the clang AST section in the container.
  245. for (auto &Section : OF->get()->sections()) {
  246. StringRef Name;
  247. Section.getName(Name);
  248. if ((!IsCOFF && Name == "__clangast") ||
  249. ( IsCOFF && Name == "clangast")) {
  250. StringRef Buf;
  251. Section.getContents(Buf);
  252. StreamFile.init((const unsigned char *)Buf.begin(),
  253. (const unsigned char *)Buf.end());
  254. return;
  255. }
  256. }
  257. }
  258. // As a fallback, treat the buffer as a raw AST.
  259. StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
  260. (const unsigned char *)Buffer.getBufferEnd());
  261. }