clang 23.0.0git
ChainedIncludesSource.cpp
Go to the documentation of this file.
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
25#include "llvm/Support/MemoryBuffer.h"
26
27using namespace clang;
28
29namespace {
30class ChainedIncludesSource : public ExternalSemaSource {
31public:
32 ChainedIncludesSource(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.
42 void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override {
43 for (unsigned i = 0, e = CIs.size(); i != e; ++i) {
44 if (const ExternalASTSource *eSrc =
45 CIs[i]->getASTContext().getExternalSource()) {
46 eSrc->getMemoryBufferSizes(sizes);
47 }
48 }
49 }
50
51private:
52 std::vector<std::unique_ptr<CompilerInstance>> CIs;
53};
54} // end anonymous namespace
55
57createASTReader(CompilerInstance &CI, StringRef pchFile,
58 SmallVectorImpl<std::unique_ptr<llvm::MemoryBuffer>> &MemBufs,
60 ASTDeserializationListener *deserialListener = nullptr) {
62 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
64 CI.getCodeGenOpts(),
65 /*Extensions=*/ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
67 for (unsigned ti = 0; ti < bufNames.size(); ++ti) {
68 StringRef sr(bufNames[ti]);
69 Reader->addInMemoryBuffer(sr, std::move(MemBufs[ti]));
70 }
71 Reader->setDeserializationListener(deserialListener);
72 switch (Reader->ReadAST(ModuleFileName::makeExplicit(pchFile),
76 // Set the predefines buffer as suggested by the PCH reader.
77 PP.setPredefines(Reader->getSuggestedPredefines());
78 return Reader;
79
86 break;
87 }
88 return nullptr;
89}
90
94
95 std::vector<std::string> &includes = CI.getPreprocessorOpts().ChainedIncludes;
96 assert(!includes.empty() && "No '-chain-include' in options!");
97
98 std::vector<std::unique_ptr<CompilerInstance>> CIs;
99 InputKind IK = CI.getFrontendOpts().Inputs[0].getKind();
100
102 SmallVector<std::string, 4> serialBufNames;
103
104 for (unsigned i = 0, e = includes.size(); i != e; ++i) {
105 bool firstInclude = (i == 0);
106 std::unique_ptr<CompilerInvocation> CInvok;
107 CInvok.reset(new CompilerInvocation(CI.getInvocation()));
108
109 CInvok->getPreprocessorOpts().ChainedIncludes.clear();
110 CInvok->getPreprocessorOpts().ImplicitPCHInclude.clear();
111 CInvok->getPreprocessorOpts().DisablePCHOrModuleValidation =
113 CInvok->getPreprocessorOpts().Includes.clear();
114 CInvok->getPreprocessorOpts().MacroIncludes.clear();
115 CInvok->getPreprocessorOpts().Macros.clear();
116
117 CInvok->getFrontendOpts().Inputs.clear();
118 FrontendInputFile InputFile(includes[i], IK);
119 CInvok->getFrontendOpts().Inputs.push_back(InputFile);
120
121 TextDiagnosticPrinter *DiagClient =
122 new TextDiagnosticPrinter(llvm::errs(), CI.getDiagnosticOpts());
123 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
124 DiagnosticIDs::create(), CI.getDiagnosticOpts(), DiagClient);
125
126 auto Clang = std::make_unique<CompilerInstance>(
127 std::move(CInvok), CI.getPCHContainerOperations());
128 // Inherit the VFS as-is: code below does not make changes to the VFS or to
129 // the VFS-affecting options.
130 Clang->setVirtualFileSystem(CI.getVirtualFileSystemPtr());
131 Clang->setDiagnostics(Diags);
132 Clang->setTarget(TargetInfo::CreateTargetInfo(
133 Clang->getDiagnostics(), Clang->getInvocation().getTargetOpts()));
134 Clang->createFileManager();
135 Clang->createSourceManager();
136 Clang->createPreprocessor(TU_Prefix);
137 Clang->getDiagnosticClient().BeginSourceFile(Clang->getLangOpts(),
138 &Clang->getPreprocessor());
139 Clang->createASTContext();
140
141 auto Buffer = std::make_shared<PCHBuffer>();
143 auto consumer = std::make_unique<PCHGenerator>(
144 Clang->getPreprocessor(), Clang->getModuleCache(), "-", /*isysroot=*/"",
145 Buffer, Clang->getCodeGenOpts(), Extensions,
146 /*AllowASTWithErrors=*/true);
147 Clang->getASTContext().setASTMutationListener(
148 consumer->GetASTMutationListener());
149 Clang->setASTConsumer(std::move(consumer));
150 Clang->createSema(TU_Prefix, nullptr);
151
152 if (firstInclude) {
153 Preprocessor &PP = Clang->getPreprocessor();
155 PP.getLangOpts());
156 } else {
157 assert(!SerialBufs.empty());
159 // TODO: Pass through the existing MemoryBuffer instances instead of
160 // allocating new ones.
161 for (auto &SB : SerialBufs)
162 Bufs.push_back(llvm::MemoryBuffer::getMemBuffer(SB->getBuffer()));
163 std::string pchName = includes[i-1];
164 llvm::raw_string_ostream os(pchName);
165 os << ".pch" << i-1;
166 serialBufNames.push_back(pchName);
167
169 Reader = createASTReader(
170 *Clang, pchName, Bufs, serialBufNames,
171 Clang->getASTConsumer().GetASTDeserializationListener());
172 if (!Reader)
173 return nullptr;
174 Clang->setASTReader(Reader);
175 Clang->getASTContext().setExternalSource(Reader);
176 }
177
178 if (!Clang->InitializeSourceManager(InputFile))
179 return nullptr;
180
181 ParseAST(Clang->getSema());
182 Clang->getDiagnosticClient().EndSourceFile();
183 assert(Buffer->IsComplete && "serialization did not complete");
184 auto &serialAST = Buffer->Data;
185 SerialBufs.push_back(llvm::MemoryBuffer::getMemBufferCopy(
186 StringRef(serialAST.data(), serialAST.size())));
187 serialAST.clear();
188 CIs.push_back(std::move(Clang));
189 }
190
191 assert(!SerialBufs.empty());
192 std::string pchName = includes.back() + ".pch-final";
193 serialBufNames.push_back(pchName);
194 OutReader = createASTReader(CI, pchName, SerialBufs, serialBufNames);
195 if (!OutReader)
196 return nullptr;
197
198 auto ChainedSrc =
199 llvm::makeIntrusiveRefCnt<ChainedIncludesSource>(std::move(CIs));
200 return llvm::makeIntrusiveRefCnt<MultiplexExternalSemaSource>(
201 std::move(ChainedSrc), OutReader);
202}
Defines enum values for all the target-independent builtin functions.
static llvm::IntrusiveRefCntPtr< ASTReader > createASTReader(CompilerInstance &CI, StringRef pchFile, SmallVectorImpl< std::unique_ptr< llvm::MemoryBuffer > > &MemBufs, SmallVectorImpl< std::string > &bufNames, ASTDeserializationListener *deserialListener=nullptr)
Defines the clang::Preprocessor interface.
@ ARR_None
The client can't handle any AST loading failures.
Definition ASTReader.h:1843
@ Success
The control block was read successfully.
Definition ASTReader.h:450
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:467
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:460
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:453
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:463
@ HadErrors
The AST file has errors.
Definition ASTReader.h:470
@ Missing
The AST file was missing.
Definition ASTReader.h:456
void initializeBuiltins(IdentifierTable &Table, const LangOptions &LangOpts)
Mark the identifiers for all the builtins with their appropriate builtin ID # and mark any non-portab...
Definition Builtins.cpp:293
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
ModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
FrontendOptions & getFrontendOpts()
CompilerInvocation & getInvocation()
PreprocessorOptions & getPreprocessorOpts()
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
DiagnosticOptions & getDiagnosticOpts()
CodeGenOptions & getCodeGenOpts()
Helper class for holding the data necessary to invoke the compiler.
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
An abstract interface that should be implemented by external AST sources that also provide informatio...
An input file for the front end.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
The kind of a file that we've been handed as an input.
static ModuleFileName makeExplicit(std::string Name)
Creates a file name for an explicit module.
Definition Module.h:116
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void setPredefines(std::string P)
Set the predefines for this Preprocessor.
IdentifierTable & getIdentifierTable()
Builtin::Context & getBuiltinInfo()
const LangOptions & getLangOpts() const
Encodes a location in the source.
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
Definition Targets.cpp:810
Defines the clang::TargetInfo interface.
@ MK_PCH
File is a PCH file treated as such.
Definition ModuleFile.h:51
The JSON file list parser is used to communicate input to InstallAPI.
void ParseAST(Preprocessor &pp, ASTConsumer *C, ASTContext &Ctx, bool PrintStats=false, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr, bool SkipFunctionBodies=false)
Parse the entire file specified, notifying the ASTConsumer as the file is parsed.
Definition ParseAST.cpp:99
IntrusiveRefCntPtr< ExternalSemaSource > createChainedIncludesSource(CompilerInstance &CI, IntrusiveRefCntPtr< ASTReader > &OutReader)
The ChainedIncludesSource class converts headers to chained PCHs in memory, mainly for testing.
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
@ PCH
Disable validation for a precompiled header and the modules it depends on.