ObjectFilePCHContainerOperations.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
  9. #include "CGDebugInfo.h"
  10. #include "CodeGenModule.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/DeclObjC.h"
  13. #include "clang/AST/Expr.h"
  14. #include "clang/AST/RecursiveASTVisitor.h"
  15. #include "clang/Basic/CodeGenOptions.h"
  16. #include "clang/Basic/Diagnostic.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "clang/CodeGen/BackendUtil.h"
  19. #include "clang/Frontend/CompilerInstance.h"
  20. #include "clang/Lex/HeaderSearch.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/Bitstream/BitstreamReader.h"
  24. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/LLVMContext.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/MC/TargetRegistry.h"
  30. #include "llvm/Object/COFF.h"
  31. #include "llvm/Object/ObjectFile.h"
  32. #include "llvm/Support/Path.h"
  33. #include <memory>
  34. #include <utility>
  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. const std::string OutputFileName;
  42. ASTContext *Ctx;
  43. ModuleMap &MMap;
  44. const HeaderSearchOptions &HeaderSearchOpts;
  45. const PreprocessorOptions &PreprocessorOpts;
  46. CodeGenOptions CodeGenOpts;
  47. const TargetOptions TargetOpts;
  48. LangOptions LangOpts;
  49. std::unique_ptr<llvm::LLVMContext> VMContext;
  50. std::unique_ptr<llvm::Module> M;
  51. std::unique_ptr<CodeGen::CodeGenModule> Builder;
  52. std::unique_ptr<raw_pwrite_stream> OS;
  53. std::shared_ptr<PCHBuffer> Buffer;
  54. /// Visit every type and emit debug info for it.
  55. struct DebugTypeVisitor : public RecursiveASTVisitor<DebugTypeVisitor> {
  56. clang::CodeGen::CGDebugInfo &DI;
  57. ASTContext &Ctx;
  58. DebugTypeVisitor(clang::CodeGen::CGDebugInfo &DI, ASTContext &Ctx)
  59. : DI(DI), Ctx(Ctx) {}
  60. /// Determine whether this type can be represented in DWARF.
  61. static bool CanRepresent(const Type *Ty) {
  62. return !Ty->isDependentType() && !Ty->isUndeducedType();
  63. }
  64. bool VisitImportDecl(ImportDecl *D) {
  65. if (!D->getImportedOwningModule())
  66. DI.EmitImportDecl(*D);
  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->parameters())
  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->parameters())
  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. std::unique_ptr<raw_pwrite_stream> OS,
  124. std::shared_ptr<PCHBuffer> Buffer)
  125. : Diags(CI.getDiagnostics()), MainFileName(MainFileName),
  126. OutputFileName(OutputFileName), Ctx(nullptr),
  127. MMap(CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()),
  128. HeaderSearchOpts(CI.getHeaderSearchOpts()),
  129. PreprocessorOpts(CI.getPreprocessorOpts()),
  130. TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
  131. OS(std::move(OS)), Buffer(std::move(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. LangOpts.setThreadModel(LangOptions::ThreadModelKind::Single);
  136. CodeGenOpts.DebugTypeExtRefs = true;
  137. // When building a module MainFileName is the name of the modulemap file.
  138. CodeGenOpts.MainFileName =
  139. LangOpts.CurrentModule.empty() ? MainFileName : LangOpts.CurrentModule;
  140. CodeGenOpts.setDebugInfo(codegenoptions::FullDebugInfo);
  141. CodeGenOpts.setDebuggerTuning(CI.getCodeGenOpts().getDebuggerTuning());
  142. CodeGenOpts.DebugPrefixMap =
  143. CI.getInvocation().getCodeGenOpts().DebugPrefixMap;
  144. CodeGenOpts.DebugStrictDwarf = CI.getCodeGenOpts().DebugStrictDwarf;
  145. }
  146. ~PCHContainerGenerator() override = default;
  147. void Initialize(ASTContext &Context) override {
  148. assert(!Ctx && "initialized multiple times");
  149. Ctx = &Context;
  150. VMContext.reset(new llvm::LLVMContext());
  151. M.reset(new llvm::Module(MainFileName, *VMContext));
  152. M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
  153. Builder.reset(new CodeGen::CodeGenModule(
  154. *Ctx, HeaderSearchOpts, PreprocessorOpts, CodeGenOpts, *M, Diags));
  155. // Prepare CGDebugInfo to emit debug info for a clang module.
  156. auto *DI = Builder->getModuleDebugInfo();
  157. StringRef ModuleName = llvm::sys::path::filename(MainFileName);
  158. DI->setPCHDescriptor(
  159. {ModuleName, "", OutputFileName, ASTFileSignature::createDISentinel()});
  160. DI->setModuleMap(MMap);
  161. }
  162. bool HandleTopLevelDecl(DeclGroupRef D) override {
  163. if (Diags.hasErrorOccurred())
  164. return true;
  165. // Collect debug info for all decls in this group.
  166. for (auto *I : D)
  167. if (!I->isFromASTFile()) {
  168. DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
  169. DTV.TraverseDecl(I);
  170. }
  171. return true;
  172. }
  173. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
  174. HandleTopLevelDecl(D);
  175. }
  176. void HandleTagDeclDefinition(TagDecl *D) override {
  177. if (Diags.hasErrorOccurred())
  178. return;
  179. if (D->isFromASTFile())
  180. return;
  181. // Anonymous tag decls are deferred until we are building their declcontext.
  182. if (D->getName().empty())
  183. return;
  184. // Defer tag decls until their declcontext is complete.
  185. auto *DeclCtx = D->getDeclContext();
  186. while (DeclCtx) {
  187. if (auto *D = dyn_cast<TagDecl>(DeclCtx))
  188. if (!D->isCompleteDefinition())
  189. return;
  190. DeclCtx = DeclCtx->getParent();
  191. }
  192. DebugTypeVisitor DTV(*Builder->getModuleDebugInfo(), *Ctx);
  193. DTV.TraverseDecl(D);
  194. Builder->UpdateCompletedType(D);
  195. }
  196. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  197. if (Diags.hasErrorOccurred())
  198. return;
  199. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  200. Builder->getModuleDebugInfo()->completeRequiredType(RD);
  201. }
  202. void HandleImplicitImportDecl(ImportDecl *D) override {
  203. if (!D->getImportedOwningModule())
  204. Builder->getModuleDebugInfo()->EmitImportDecl(*D);
  205. }
  206. /// Emit a container holding the serialized AST.
  207. void HandleTranslationUnit(ASTContext &Ctx) override {
  208. assert(M && VMContext && Builder);
  209. // Delete these on function exit.
  210. std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
  211. std::unique_ptr<llvm::Module> M = std::move(this->M);
  212. std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
  213. if (Diags.hasErrorOccurred())
  214. return;
  215. M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
  216. M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
  217. // PCH files don't have a signature field in the control block,
  218. // but LLVM detects DWO CUs by looking for a non-zero DWO id.
  219. // We use the lower 64 bits for debug info.
  220. uint64_t Signature =
  221. Buffer->Signature ? Buffer->Signature.truncatedValue() : ~1ULL;
  222. Builder->getModuleDebugInfo()->setDwoId(Signature);
  223. // Finalize the Builder.
  224. if (Builder)
  225. Builder->Release();
  226. // Ensure the target exists.
  227. std::string Error;
  228. auto Triple = Ctx.getTargetInfo().getTriple();
  229. if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
  230. llvm::report_fatal_error(llvm::Twine(Error));
  231. // Emit the serialized Clang AST into its own section.
  232. assert(Buffer->IsComplete && "serialization did not complete");
  233. auto &SerializedAST = Buffer->Data;
  234. auto Size = SerializedAST.size();
  235. if (Triple.isOSBinFormatWasm()) {
  236. // Emit __clangast in custom section instead of named data segment
  237. // to find it while iterating sections.
  238. // This could be avoided if all data segements (the wasm sense) were
  239. // represented as their own sections (in the llvm sense).
  240. // TODO: https://github.com/WebAssembly/tool-conventions/issues/138
  241. llvm::NamedMDNode *MD =
  242. M->getOrInsertNamedMetadata("wasm.custom_sections");
  243. llvm::Metadata *Ops[2] = {
  244. llvm::MDString::get(*VMContext, "__clangast"),
  245. llvm::MDString::get(*VMContext,
  246. StringRef(SerializedAST.data(), Size))};
  247. auto *NameAndContent = llvm::MDTuple::get(*VMContext, Ops);
  248. MD->addOperand(NameAndContent);
  249. } else {
  250. auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
  251. auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
  252. auto *Data = llvm::ConstantDataArray::getString(
  253. *VMContext, StringRef(SerializedAST.data(), Size),
  254. /*AddNull=*/false);
  255. auto *ASTSym = new llvm::GlobalVariable(
  256. *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage,
  257. Data, "__clang_ast");
  258. // The on-disk hashtable needs to be aligned.
  259. ASTSym->setAlignment(llvm::Align(8));
  260. // Mach-O also needs a segment name.
  261. if (Triple.isOSBinFormatMachO())
  262. ASTSym->setSection("__CLANG,__clangast");
  263. // COFF has an eight character length limit.
  264. else if (Triple.isOSBinFormatCOFF())
  265. ASTSym->setSection("clangast");
  266. else
  267. ASTSym->setSection("__clangast");
  268. }
  269. LLVM_DEBUG({
  270. // Print the IR for the PCH container to the debug output.
  271. llvm::SmallString<0> Buffer;
  272. clang::EmitBackendOutput(
  273. Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
  274. Ctx.getTargetInfo().getDataLayoutString(), M.get(),
  275. BackendAction::Backend_EmitLL,
  276. std::make_unique<llvm::raw_svector_ostream>(Buffer));
  277. llvm::dbgs() << Buffer;
  278. });
  279. // Use the LLVM backend to emit the pch container.
  280. clang::EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
  281. LangOpts,
  282. Ctx.getTargetInfo().getDataLayoutString(), M.get(),
  283. BackendAction::Backend_EmitObj, std::move(OS));
  284. // Free the memory for the temporary buffer.
  285. llvm::SmallVector<char, 0> Empty;
  286. SerializedAST = std::move(Empty);
  287. }
  288. };
  289. } // anonymous namespace
  290. std::unique_ptr<ASTConsumer>
  291. ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
  292. CompilerInstance &CI, const std::string &MainFileName,
  293. const std::string &OutputFileName,
  294. std::unique_ptr<llvm::raw_pwrite_stream> OS,
  295. std::shared_ptr<PCHBuffer> Buffer) const {
  296. return std::make_unique<PCHContainerGenerator>(
  297. CI, MainFileName, OutputFileName, std::move(OS), Buffer);
  298. }
  299. StringRef
  300. ObjectFilePCHContainerReader::ExtractPCH(llvm::MemoryBufferRef Buffer) const {
  301. StringRef PCH;
  302. auto OFOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
  303. if (OFOrErr) {
  304. auto &OF = OFOrErr.get();
  305. bool IsCOFF = isa<llvm::object::COFFObjectFile>(*OF);
  306. // Find the clang AST section in the container.
  307. for (auto &Section : OF->sections()) {
  308. StringRef Name;
  309. if (Expected<StringRef> NameOrErr = Section.getName())
  310. Name = *NameOrErr;
  311. else
  312. consumeError(NameOrErr.takeError());
  313. if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) {
  314. if (Expected<StringRef> E = Section.getContents())
  315. return *E;
  316. else {
  317. handleAllErrors(E.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
  318. EIB.log(llvm::errs());
  319. });
  320. return "";
  321. }
  322. }
  323. }
  324. }
  325. handleAllErrors(OFOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
  326. if (EIB.convertToErrorCode() ==
  327. llvm::object::object_error::invalid_file_type)
  328. // As a fallback, treat the buffer as a raw AST.
  329. PCH = Buffer.getBuffer();
  330. else
  331. EIB.log(llvm::errs());
  332. });
  333. return PCH;
  334. }