ChainedIncludesSource.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. //===- ChainedIncludesSource.cpp - Chained PCHs in Memory -------*- C++ -*-===//
  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. //
  9. // This file defines the ChainedIncludesSource class, which converts headers
  10. // to chained PCHs in memory, mainly used for testing.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Basic/Builtins.h"
  14. #include "clang/Basic/TargetInfo.h"
  15. #include "clang/Frontend/ASTUnit.h"
  16. #include "clang/Frontend/CompilerInstance.h"
  17. #include "clang/Frontend/TextDiagnosticPrinter.h"
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Lex/PreprocessorOptions.h"
  20. #include "clang/Parse/ParseAST.h"
  21. #include "clang/Sema/MultiplexExternalSemaSource.h"
  22. #include "clang/Serialization/ASTReader.h"
  23. #include "clang/Serialization/ASTWriter.h"
  24. #include "llvm/Support/MemoryBuffer.h"
  25. using namespace clang;
  26. namespace {
  27. class ChainedIncludesSourceImpl : public ExternalSemaSource {
  28. public:
  29. ChainedIncludesSourceImpl(std::vector<std::unique_ptr<CompilerInstance>> CIs)
  30. : CIs(std::move(CIs)) {}
  31. protected:
  32. //===----------------------------------------------------------------------===//
  33. // ExternalASTSource interface.
  34. //===----------------------------------------------------------------------===//
  35. /// Return the amount of memory used by memory buffers, breaking down
  36. /// by heap-backed versus mmap'ed memory.
  37. void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override {
  38. for (unsigned i = 0, e = CIs.size(); i != e; ++i) {
  39. if (const ExternalASTSource *eSrc =
  40. CIs[i]->getASTContext().getExternalSource()) {
  41. eSrc->getMemoryBufferSizes(sizes);
  42. }
  43. }
  44. }
  45. private:
  46. std::vector<std::unique_ptr<CompilerInstance>> CIs;
  47. };
  48. /// Members of ChainedIncludesSource, factored out so we can initialize
  49. /// them before we initialize the ExternalSemaSource base class.
  50. struct ChainedIncludesSourceMembers {
  51. ChainedIncludesSourceMembers(
  52. std::vector<std::unique_ptr<CompilerInstance>> CIs,
  53. IntrusiveRefCntPtr<ExternalSemaSource> FinalReader)
  54. : Impl(std::move(CIs)), FinalReader(std::move(FinalReader)) {}
  55. ChainedIncludesSourceImpl Impl;
  56. IntrusiveRefCntPtr<ExternalSemaSource> FinalReader;
  57. };
  58. /// Use MultiplexExternalSemaSource to dispatch all ExternalSemaSource
  59. /// calls to the final reader.
  60. class ChainedIncludesSource
  61. : private ChainedIncludesSourceMembers,
  62. public MultiplexExternalSemaSource {
  63. public:
  64. ChainedIncludesSource(std::vector<std::unique_ptr<CompilerInstance>> CIs,
  65. IntrusiveRefCntPtr<ExternalSemaSource> FinalReader)
  66. : ChainedIncludesSourceMembers(std::move(CIs), std::move(FinalReader)),
  67. MultiplexExternalSemaSource(Impl, *this->FinalReader) {}
  68. };
  69. }
  70. static ASTReader *
  71. createASTReader(CompilerInstance &CI, StringRef pchFile,
  72. SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs,
  73. SmallVectorImpl<std::string> &bufNames,
  74. ASTDeserializationListener *deserialListener = nullptr) {
  75. Preprocessor &PP = CI.getPreprocessor();
  76. std::unique_ptr<ASTReader> Reader;
  77. Reader.reset(new ASTReader(
  78. PP, CI.getModuleCache(), &CI.getASTContext(), CI.getPCHContainerReader(),
  79. /*Extensions=*/{},
  80. /*isysroot=*/"", DisableValidationForModuleKind::PCH));
  81. for (unsigned ti = 0; ti < bufNames.size(); ++ti) {
  82. StringRef sr(bufNames[ti]);
  83. Reader->addInMemoryBuffer(sr, std::move(MemBufs[ti]));
  84. }
  85. Reader->setDeserializationListener(deserialListener);
  86. switch (Reader->ReadAST(pchFile, serialization::MK_PCH, SourceLocation(),
  87. ASTReader::ARR_None)) {
  88. case ASTReader::Success:
  89. // Set the predefines buffer as suggested by the PCH reader.
  90. PP.setPredefines(Reader->getSuggestedPredefines());
  91. return Reader.release();
  92. case ASTReader::Failure:
  93. case ASTReader::Missing:
  94. case ASTReader::OutOfDate:
  95. case ASTReader::VersionMismatch:
  96. case ASTReader::ConfigurationMismatch:
  97. case ASTReader::HadErrors:
  98. break;
  99. }
  100. return nullptr;
  101. }
  102. IntrusiveRefCntPtr<ExternalSemaSource> clang::createChainedIncludesSource(
  103. CompilerInstance &CI, IntrusiveRefCntPtr<ExternalSemaSource> &Reader) {
  104. std::vector<std::string> &includes = CI.getPreprocessorOpts().ChainedIncludes;
  105. assert(!includes.empty() && "No '-chain-include' in options!");
  106. std::vector<std::unique_ptr<CompilerInstance>> CIs;
  107. InputKind IK = CI.getFrontendOpts().Inputs[0].getKind();
  108. SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> SerialBufs;
  109. SmallVector<std::string, 4> serialBufNames;
  110. for (unsigned i = 0, e = includes.size(); i != e; ++i) {
  111. bool firstInclude = (i == 0);
  112. std::unique_ptr<CompilerInvocation> CInvok;
  113. CInvok.reset(new CompilerInvocation(CI.getInvocation()));
  114. CInvok->getPreprocessorOpts().ChainedIncludes.clear();
  115. CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear();
  116. CInvok->getPreprocessorOpts().DisablePCHOrModuleValidation =
  117. DisableValidationForModuleKind::PCH;
  118. CInvok->getPreprocessorOpts().Includes.clear();
  119. CInvok->getPreprocessorOpts().MacroIncludes.clear();
  120. CInvok->getPreprocessorOpts().Macros.clear();
  121. CInvok->getFrontendOpts().Inputs.clear();
  122. FrontendInputFile InputFile(includes[i], IK);
  123. CInvok->getFrontendOpts().Inputs.push_back(InputFile);
  124. TextDiagnosticPrinter *DiagClient =
  125. new TextDiagnosticPrinter(llvm::errs(), new DiagnosticOptions());
  126. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  127. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
  128. new DiagnosticsEngine(DiagID, &CI.getDiagnosticOpts(), DiagClient));
  129. std::unique_ptr<CompilerInstance> Clang(
  130. new CompilerInstance(CI.getPCHContainerOperations()));
  131. Clang->setInvocation(std::move(CInvok));
  132. Clang->setDiagnostics(Diags.get());
  133. Clang->setTarget(TargetInfo::CreateTargetInfo(
  134. Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
  135. Clang->createFileManager();
  136. Clang->createSourceManager(Clang->getFileManager());
  137. Clang->createPreprocessor(TU_Prefix);
  138. Clang->getDiagnosticClient().BeginSourceFile(Clang->getLangOpts(),
  139. &Clang->getPreprocessor());
  140. Clang->createASTContext();
  141. auto Buffer = std::make_shared<PCHBuffer>();
  142. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions;
  143. auto consumer = std::make_unique<PCHGenerator>(
  144. Clang->getPreprocessor(), Clang->getModuleCache(), "-", /*isysroot=*/"",
  145. Buffer, Extensions, /*AllowASTWithErrors=*/true);
  146. Clang->getASTContext().setASTMutationListener(
  147. consumer->GetASTMutationListener());
  148. Clang->setASTConsumer(std::move(consumer));
  149. Clang->createSema(TU_Prefix, nullptr);
  150. if (firstInclude) {
  151. Preprocessor &PP = Clang->getPreprocessor();
  152. PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
  153. PP.getLangOpts());
  154. } else {
  155. assert(!SerialBufs.empty());
  156. SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> Bufs;
  157. // TODO: Pass through the existing MemoryBuffer instances instead of
  158. // allocating new ones.
  159. for (auto &SB : SerialBufs)
  160. Bufs.push_back(llvm::MemoryBuffer::getMemBuffer(SB->getBuffer()));
  161. std::string pchName = includes[i-1];
  162. llvm::raw_string_ostream os(pchName);
  163. os << ".pch" << i-1;
  164. serialBufNames.push_back(os.str());
  165. IntrusiveRefCntPtr<ASTReader> Reader;
  166. Reader = createASTReader(
  167. *Clang, pchName, Bufs, serialBufNames,
  168. Clang->getASTConsumer().GetASTDeserializationListener());
  169. if (!Reader)
  170. return nullptr;
  171. Clang->setASTReader(Reader);
  172. Clang->getASTContext().setExternalSource(Reader);
  173. }
  174. if (!Clang->InitializeSourceManager(InputFile))
  175. return nullptr;
  176. ParseAST(Clang->getSema());
  177. Clang->getDiagnosticClient().EndSourceFile();
  178. assert(Buffer->IsComplete && "serialization did not complete");
  179. auto &serialAST = Buffer->Data;
  180. SerialBufs.push_back(llvm::MemoryBuffer::getMemBufferCopy(
  181. StringRef(serialAST.data(), serialAST.size())));
  182. serialAST.clear();
  183. CIs.push_back(std::move(Clang));
  184. }
  185. assert(!SerialBufs.empty());
  186. std::string pchName = includes.back() + ".pch-final";
  187. serialBufNames.push_back(pchName);
  188. Reader = createASTReader(CI, pchName, SerialBufs, serialBufNames);
  189. if (!Reader)
  190. return nullptr;
  191. return IntrusiveRefCntPtr<ChainedIncludesSource>(
  192. new ChainedIncludesSource(std::move(CIs), Reader));
  193. }