ObjectFilePCHContainerOperations.cpp 11 KB

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