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