ObjectFilePCHContainerOperations.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. // TagDecls may be deferred until after all decls have been merged and we
  71. // know the complete type. Pure forward declarations will be skipped, but
  72. // they don't need to be emitted into the module anyway.
  73. if (auto *TD = dyn_cast<TagDecl>(D))
  74. if (!TD->isCompleteDefinition())
  75. return true;
  76. QualType QualTy = Ctx.getTypeDeclType(D);
  77. if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
  78. DI.getOrCreateStandaloneType(QualTy, D->getLocation());
  79. return true;
  80. }
  81. bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
  82. QualType QualTy(D->getTypeForDecl(), 0);
  83. if (!QualTy.isNull() && CanRepresent(QualTy.getTypePtr()))
  84. DI.getOrCreateStandaloneType(QualTy, D->getLocation());
  85. return true;
  86. }
  87. bool VisitFunctionDecl(FunctionDecl *D) {
  88. if (isa<CXXMethodDecl>(D))
  89. // This is not yet supported. Constructing the `this' argument
  90. // mandates a CodeGenFunction.
  91. return true;
  92. SmallVector<QualType, 16> ArgTypes;
  93. for (auto i : D->params())
  94. ArgTypes.push_back(i->getType());
  95. QualType RetTy = D->getReturnType();
  96. QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
  97. FunctionProtoType::ExtProtoInfo());
  98. if (CanRepresent(FnTy.getTypePtr()))
  99. DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
  100. return true;
  101. }
  102. bool VisitObjCMethodDecl(ObjCMethodDecl *D) {
  103. if (!D->getClassInterface())
  104. return true;
  105. bool selfIsPseudoStrong, selfIsConsumed;
  106. SmallVector<QualType, 16> ArgTypes;
  107. ArgTypes.push_back(D->getSelfType(Ctx, D->getClassInterface(),
  108. selfIsPseudoStrong, selfIsConsumed));
  109. ArgTypes.push_back(Ctx.getObjCSelType());
  110. for (auto i : D->params())
  111. ArgTypes.push_back(i->getType());
  112. QualType RetTy = D->getReturnType();
  113. QualType FnTy = Ctx.getFunctionType(RetTy, ArgTypes,
  114. FunctionProtoType::ExtProtoInfo());
  115. if (CanRepresent(FnTy.getTypePtr()))
  116. DI.EmitFunctionDecl(D, D->getLocation(), FnTy);
  117. return true;
  118. }
  119. };
  120. public:
  121. PCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName,
  122. const std::string &OutputFileName,
  123. raw_pwrite_stream *OS,
  124. std::shared_ptr<PCHBuffer> Buffer)
  125. : Diags(CI.getDiagnostics()), Ctx(nullptr),
  126. MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
  127. HeaderSearchOpts(CI.getHeaderSearchOpts()),
  128. PreprocessorOpts(CI.getPreprocessorOpts()),
  129. TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()), OS(OS),
  130. Buffer(Buffer) {
  131. // The debug info output isn't affected by CodeModel and
  132. // ThreadModel, but the backend expects them to be nonempty.
  133. CodeGenOpts.CodeModel = "default";
  134. CodeGenOpts.ThreadModel = "single";
  135. CodeGenOpts.DebugTypeExtRefs = true;
  136. CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
  137. }
  138. ~PCHContainerGenerator() override = default;
  139. void Initialize(ASTContext &Context) override {
  140. assert(!Ctx && "initialized multiple times");
  141. Ctx = &Context;
  142. VMContext.reset(new llvm::LLVMContext());
  143. M.reset(new llvm::Module(MainFileName, *VMContext));
  144. M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
  145. Builder.reset(new CodeGen::CodeGenModule(
  146. *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
  147. Builder->getModuleDebugInfo()->setModuleMap(MMap);
  148. }
  149. bool HandleTopLevelDecl(DeclGroupRef D) override {
  150. if (Diags.hasErrorOccurred())
  151. return true;
  152. // Collect debug info for all decls in this group.
  153. for (auto *I : D)
  154. if (!I->isFromASTFile()) {
  155. DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
  156. DTV.TraverseDecl(I);
  157. }
  158. return true;
  159. }
  160. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
  161. HandleTopLevelDecl(D);
  162. }
  163. void HandleTagDeclDefinition(TagDecl *D) override {
  164. if (Diags.hasErrorOccurred())
  165. return;
  166. if (D->isFromASTFile())
  167. return;
  168. // Anonymous tag decls are deferred until we are building their declcontext.
  169. if (D->getName().empty())
  170. return;
  171. DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
  172. DTV.TraverseDecl(D);
  173. Builder->UpdateCompletedType(D);
  174. }
  175. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  176. if (Diags.hasErrorOccurred())
  177. return;
  178. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  179. Builder->getModuleDebugInfo()->completeRequiredType(RD);
  180. }
  181. /// Emit a container holding the serialized AST.
  182. void HandleTranslationUnit(ASTContext &Ctx) override {
  183. assert(M && VMContext && Builder);
  184. // Delete these on function exit.
  185. std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
  186. std::unique_ptr<llvm::Module> M = std::move(this->M);
  187. std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
  188. if (Diags.hasErrorOccurred())
  189. return;
  190. M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
  191. M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
  192. // PCH files don't have a signature field in the control block,
  193. // but LLVM detects DWO CUs by looking for a non-zero DWO id.
  194. uint64_t Signature = Buffer->Signature ? Buffer->Signature : ~1ULL;
  195. Builder->getModuleDebugInfo()->setDwoId(Signature);
  196. // Finalize the Builder.
  197. if (Builder)
  198. Builder->Release();
  199. // Ensure the target exists.
  200. std::string Error;
  201. auto Triple = Ctx.getTargetInfo().getTriple();
  202. if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
  203. llvm::report_fatal_error(Error);
  204. // Emit the serialized Clang AST into its own section.
  205. assert(Buffer->IsComplete && "serialization did not complete");
  206. auto &SerializedAST = Buffer->Data;
  207. auto Size = SerializedAST.size();
  208. auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
  209. auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
  210. auto *Data = llvm::ConstantDataArray::getString(
  211. *VMContext, StringRef(SerializedAST.data(), Size),
  212. /*AddNull=*/false);
  213. auto *ASTSym = new llvm::GlobalVariable(
  214. *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
  215. "__clang_ast");
  216. // The on-disk hashtable needs to be aligned.
  217. ASTSym->setAlignment(8);
  218. // Mach-O also needs a segment name.
  219. if (Triple.isOSBinFormatMachO())
  220. ASTSym->setSection("__CLANG,__clangast");
  221. // COFF has an eight character length limit.
  222. else if (Triple.isOSBinFormatCOFF())
  223. ASTSym->setSection("clangast");
  224. else
  225. ASTSym->setSection("__clangast");
  226. DEBUG({
  227. // Print the IR for the PCH container to the debug output.
  228. llvm::SmallString<0> Buffer;
  229. llvm::raw_svector_ostream OS(Buffer);
  230. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  231. Ctx.getTargetInfo().getDataLayoutString(),
  232. M.get(), BackendAction::Backend_EmitLL, &OS);
  233. llvm::dbgs() << Buffer;
  234. });
  235. // Use the LLVM backend to emit the pch container.
  236. clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  237. Ctx.getTargetInfo().getDataLayoutString(),
  238. M.get(), BackendAction::Backend_EmitObj, OS);
  239. // Make sure the pch container hits disk.
  240. OS->flush();
  241. // Free the memory for the temporary buffer.
  242. llvm::SmallVector<char, 0> Empty;
  243. SerializedAST = std::move(Empty);
  244. }
  245. };
  246. } // anonymous namespace
  247. std::unique_ptr<ASTConsumer>
  248. ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
  249. CompilerInstance &CI, const std::string &MainFileName,
  250. const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
  251. std::shared_ptr<PCHBuffer> Buffer) const {
  252. return llvm::make_unique<PCHContainerGenerator>(CI, MainFileName,
  253. OutputFileName, OS, Buffer);
  254. }
  255. void ObjectFilePCHContainerReader::ExtractPCH(
  256. llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
  257. if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
  258. auto *Obj = OF.get().get();
  259. bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
  260. // Find the clang AST section in the container.
  261. for (auto &Section : OF->get()->sections()) {
  262. StringRef Name;
  263. Section.getName(Name);
  264. if ((!IsCOFF && Name == "__clangast") ||
  265. ( IsCOFF && Name == "clangast")) {
  266. StringRef Buf;
  267. Section.getContents(Buf);
  268. StreamFile.init((const unsigned char *)Buf.begin(),
  269. (const unsigned char *)Buf.end());
  270. return;
  271. }
  272. }
  273. }
  274. // As a fallback, treat the buffer as a raw AST.
  275. StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
  276. (const unsigned char *)Buffer.getBufferEnd());
  277. }