ObjectFilePCHContainerOperations.cpp 12 KB

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