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
14#include "clang/Basic/Builtins.h"
15#include "clang/Basic/TargetInfo.h"
16#include "clang/Frontend/ASTUnit.h"
17#include "clang/Frontend/CompilerInstance.h"
18#include "clang/Frontend/TextDiagnosticPrinter.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/PreprocessorOptions.h"
21#include "clang/Parse/ParseAST.h"
22#include "clang/Sema/MultiplexExternalSemaSource.h"
23#include "clang/Serialization/ASTReader.h"
24#include "clang/Serialization/ASTWriter.h"
25#include "clang/Serialization/InMemoryModuleCache.h"
26#include "clang/Serialization/ModuleCache.h"
27#include "llvm/Support/MemoryBuffer.h"
28
29using namespace clang;
30
31namespace {
32class ChainedIncludesSource : public ExternalSemaSource {
33public:
34 ChainedIncludesSource(std::vector<std::unique_ptr<CompilerInstance>> CIs)
35 : CIs(std::move(CIs)) {}
36
37protected:
38 //===--------------------------------------------------------------------===//
39 // ExternalASTSource interface.
40 //===--------------------------------------------------------------------===//
41
42 /// Return the amount of memory used by memory buffers, breaking down
43 /// by heap-backed versus mmap'ed memory.
44 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override {
45 for (unsigned i = 0, e = CIs.size(); i != e; ++i) {
46 if (const ExternalASTSource *eSrc =
47 CIs[i]->getASTContext().getExternalSource()) {
48 eSrc->getMemoryBufferSizes(sizes);
49 }
50 }
51 }
52
53private:
54 std::vector<std::unique_ptr<CompilerInstance>> CIs;
55};
56} // end anonymous namespace
57
58static llvm::IntrusiveRefCntPtr<ASTReader>
59createASTReader(CompilerInstance &CI, StringRef pchFile,
60 SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs,
61 SmallVectorImpl<std::string> &bufNames,
62 ASTDeserializationListener *deserialListener = nullptr) {
63 Preprocessor &PP = CI.getPreprocessor();
64 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
65 A&: PP, A&: CI.getModuleCache(), A: &CI.getASTContext(), A: CI.getPCHContainerReader(),
66 A&: CI.getCodeGenOpts(),
67 /*Extensions=*/A: ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
68 /*isysroot=*/A: "", A: DisableValidationForModuleKind::PCH);
69 for (unsigned ti = 0; ti < bufNames.size(); ++ti) {
70 off_t MemBufSize = MemBufs[ti]->getBufferSize();
71 CI.getModuleCache().getInMemoryModuleCache().addBuiltPCM(
72 Filename: bufNames[ti], Buffer: std::move(MemBufs[ti]), Size: MemBufSize, /*ModTime=*/0);
73 }
74 Reader->setDeserializationListener(Listener: deserialListener);
75 switch (Reader->ReadAST(FileName: ModuleFileName::makeInMemory(Name: pchFile),
76 Type: serialization::MK_PCH, ImportLoc: SourceLocation(),
77 ClientLoadCapabilities: ASTReader::ARR_None)) {
78 case ASTReader::Success:
79 // Set the predefines buffer as suggested by the PCH reader.
80 PP.setPredefines(Reader->getSuggestedPredefines());
81 return Reader;
82
83 case ASTReader::Failure:
84 case ASTReader::Missing:
85 case ASTReader::OutOfDate:
86 case ASTReader::VersionMismatch:
87 case ASTReader::ConfigurationMismatch:
88 case ASTReader::HadErrors:
89 break;
90 }
91 return nullptr;
92}
93
94IntrusiveRefCntPtr<ExternalSemaSource>
95clang::createChainedIncludesSource(CompilerInstance &CI,
96 IntrusiveRefCntPtr<ASTReader> &OutReader) {
97
98 std::vector<std::string> &includes = CI.getPreprocessorOpts().ChainedIncludes;
99 assert(!includes.empty() && "No '-chain-include' in options!");
100
101 std::vector<std::unique_ptr<CompilerInstance>> CIs;
102 InputKind IK = CI.getFrontendOpts().Inputs[0].getKind();
103
104 SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> SerialBufs;
105 SmallVector<std::string, 4> serialBufNames;
106
107 for (unsigned i = 0, e = includes.size(); i != e; ++i) {
108 bool firstInclude = (i == 0);
109 std::unique_ptr<CompilerInvocation> CInvok;
110 CInvok.reset(p: new CompilerInvocation(CI.getInvocation()));
111
112 CInvok->getPreprocessorOpts().ChainedIncludes.clear();
113 CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear();
114 CInvok->getPreprocessorOpts().DisablePCHOrModuleValidation =
115 DisableValidationForModuleKind::PCH;
116 CInvok->getPreprocessorOpts().Includes.clear();
117 CInvok->getPreprocessorOpts().MacroIncludes.clear();
118 CInvok->getPreprocessorOpts().Macros.clear();
119
120 CInvok->getFrontendOpts().Inputs.clear();
121 FrontendInputFile InputFile(includes[i], IK);
122 CInvok->getFrontendOpts().Inputs.push_back(Elt: InputFile);
123
124 TextDiagnosticPrinter *DiagClient =
125 new TextDiagnosticPrinter(llvm::errs(), CI.getDiagnosticOpts());
126 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
127 A: DiagnosticIDs::create(), A&: CI.getDiagnosticOpts(), A&: DiagClient);
128
129 auto Clang = std::make_unique<CompilerInstance>(
130 args: std::move(CInvok), args: CI.getPCHContainerOperations());
131 // Inherit the VFS as-is: code below does not make changes to the VFS or to
132 // the VFS-affecting options.
133 Clang->setVirtualFileSystem(CI.getVirtualFileSystemPtr());
134 Clang->setDiagnostics(Diags);
135 Clang->setTarget(TargetInfo::CreateTargetInfo(
136 Diags&: Clang->getDiagnostics(), Opts&: Clang->getInvocation().getTargetOpts()));
137 Clang->createFileManager();
138 Clang->createSourceManager();
139 Clang->createPreprocessor(TUKind: TU_Prefix);
140 Clang->getDiagnosticClient().BeginSourceFile(LangOpts: Clang->getLangOpts(),
141 PP: &Clang->getPreprocessor());
142 Clang->createASTContext();
143
144 auto Buffer = std::make_shared<PCHBuffer>();
145 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions;
146 auto consumer = std::make_unique<PCHGenerator>(
147 args&: Clang->getPreprocessor(), args&: Clang->getModuleCache(), args: "-", /*isysroot=*/args: "",
148 args&: Buffer, args&: Clang->getCodeGenOpts(), args&: Extensions,
149 /*AllowASTWithErrors=*/args: true);
150 Clang->getASTContext().setASTMutationListener(
151 consumer->GetASTMutationListener());
152 Clang->setASTConsumer(std::move(consumer));
153 Clang->createSema(TUKind: TU_Prefix, CompletionConsumer: nullptr);
154
155 if (firstInclude) {
156 Preprocessor &PP = Clang->getPreprocessor();
157 PP.getBuiltinInfo().initializeBuiltins(Table&: PP.getIdentifierTable(),
158 LangOpts: PP.getLangOpts());
159 } else {
160 assert(!SerialBufs.empty());
161 SmallVector<std::unique_ptr<llvm::MemoryBuffer>, 4> Bufs;
162 // TODO: Pass through the existing MemoryBuffer instances instead of
163 // allocating new ones.
164 for (auto &SB : SerialBufs)
165 Bufs.push_back(Elt: llvm::MemoryBuffer::getMemBuffer(InputData: SB->getBuffer()));
166 std::string pchName = includes[i-1];
167 llvm::raw_string_ostream os(pchName);
168 os << ".pch" << i-1;
169 serialBufNames.push_back(Elt: pchName);
170
171 IntrusiveRefCntPtr<ASTReader> Reader;
172 Reader = createASTReader(
173 CI&: *Clang, pchFile: pchName, MemBufs&: Bufs, bufNames&: serialBufNames,
174 deserialListener: Clang->getASTConsumer().GetASTDeserializationListener());
175 if (!Reader)
176 return nullptr;
177 Clang->setASTReader(Reader);
178 Clang->getASTContext().setExternalSource(Reader);
179 }
180
181 if (!Clang->InitializeSourceManager(Input: InputFile))
182 return nullptr;
183
184 ParseAST(S&: Clang->getSema());
185 Clang->getDiagnosticClient().EndSourceFile();
186 assert(Buffer->IsComplete && "serialization did not complete");
187 auto &serialAST = Buffer->Data;
188 SerialBufs.push_back(Elt: llvm::MemoryBuffer::getMemBufferCopy(
189 InputData: StringRef(serialAST.data(), serialAST.size())));
190 serialAST.clear();
191 CIs.push_back(x: std::move(Clang));
192 }
193
194 assert(!SerialBufs.empty());
195 std::string pchName = includes.back() + ".pch-final";
196 serialBufNames.push_back(Elt: pchName);
197 OutReader = createASTReader(CI, pchFile: pchName, MemBufs&: SerialBufs, bufNames&: serialBufNames);
198 if (!OutReader)
199 return nullptr;
200
201 auto ChainedSrc =
202 llvm::makeIntrusiveRefCnt<ChainedIncludesSource>(A: std::move(CIs));
203 return llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
204 A: std::move(ChainedSrc), A&: OutReader);
205}
206