1 //===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Helper class to build precompiled preamble.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/PrecompiledPreamble.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Basic/VirtualFileSystem.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "clang/Frontend/CompilerInvocation.h"
20 #include "clang/Frontend/FrontendActions.h"
21 #include "clang/Frontend/FrontendOptions.h"
22 #include "clang/Lex/Lexer.h"
23 #include "clang/Lex/PreprocessorOptions.h"
24 #include "clang/Serialization/ASTWriter.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/Support/CrashRecoveryContext.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/Mutex.h"
31 #include "llvm/Support/MutexGuard.h"
32 #include "llvm/Support/Process.h"
36 using namespace clang;
40 StringRef getInMemoryPreamblePath() {
41 #if defined(LLVM_ON_UNIX)
42 return "/__clang_tmp/___clang_inmemory_preamble___";
43 #elif defined(LLVM_ON_WIN32)
44 return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
46 #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
47 return "/__clang_tmp/___clang_inmemory_preamble___";
51 IntrusiveRefCntPtr<vfs::FileSystem>
52 createVFSOverlayForPreamblePCH(StringRef PCHFilename,
53 std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
54 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
55 // We want only the PCH file from the real filesystem to be available,
56 // so we create an in-memory VFS with just that and overlay it on top.
57 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> PCHFS(
58 new vfs::InMemoryFileSystem());
59 PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
60 IntrusiveRefCntPtr<vfs::OverlayFileSystem> Overlay(
61 new vfs::OverlayFileSystem(VFS));
62 Overlay->pushOverlay(PCHFS);
66 /// Keeps a track of files to be deleted in destructor.
67 class TemporaryFiles {
69 // A static instance to be used by all clients.
70 static TemporaryFiles &getInstance();
73 // Disallow constructing the class directly.
74 TemporaryFiles() = default;
76 TemporaryFiles(const TemporaryFiles &) = delete;
81 /// Adds \p File to a set of tracked files.
82 void addFile(StringRef File);
84 /// Remove \p File from disk and from the set of tracked files.
85 void removeFile(StringRef File);
88 llvm::sys::SmartMutex<false> Mutex;
89 llvm::StringSet<> Files;
92 TemporaryFiles &TemporaryFiles::getInstance() {
93 static TemporaryFiles Instance;
97 TemporaryFiles::~TemporaryFiles() {
98 llvm::MutexGuard Guard(Mutex);
99 for (const auto &File : Files)
100 llvm::sys::fs::remove(File.getKey());
103 void TemporaryFiles::addFile(StringRef File) {
104 llvm::MutexGuard Guard(Mutex);
105 auto IsInserted = Files.insert(File).second;
107 assert(IsInserted && "File has already been added");
110 void TemporaryFiles::removeFile(StringRef File) {
111 llvm::MutexGuard Guard(Mutex);
112 auto WasPresent = Files.erase(File);
114 assert(WasPresent && "File was not tracked");
115 llvm::sys::fs::remove(File);
118 class PrecompilePreambleAction : public ASTFrontendAction {
120 PrecompilePreambleAction(std::string *InMemStorage,
121 PreambleCallbacks &Callbacks)
122 : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
124 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
125 StringRef InFile) override;
127 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
129 void setEmittedPreamblePCH(ASTWriter &Writer) {
130 this->HasEmittedPreamblePCH = true;
131 Callbacks.AfterPCHEmitted(Writer);
134 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
135 bool hasCodeCompletionSupport() const override { return false; }
136 bool hasASTFileSupport() const override { return false; }
137 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
140 friend class PrecompilePreambleConsumer;
142 bool HasEmittedPreamblePCH = false;
143 std::string *InMemStorage;
144 PreambleCallbacks &Callbacks;
147 class PrecompilePreambleConsumer : public PCHGenerator {
149 PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
150 const Preprocessor &PP, StringRef isysroot,
151 std::unique_ptr<raw_ostream> Out)
152 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
153 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
154 /*AllowASTWithErrors=*/true),
155 Action(Action), Out(std::move(Out)) {}
157 bool HandleTopLevelDecl(DeclGroupRef DG) override {
158 Action.Callbacks.HandleTopLevelDecl(DG);
162 void HandleTranslationUnit(ASTContext &Ctx) override {
163 PCHGenerator::HandleTranslationUnit(Ctx);
164 if (!hasEmittedPCH())
167 // Write the generated bitstream to "Out".
169 // Make sure it hits disk now.
172 llvm::SmallVector<char, 0> Empty;
173 getPCH() = std::move(Empty);
175 Action.setEmittedPreamblePCH(getWriter());
179 PrecompilePreambleAction &Action;
180 std::unique_ptr<raw_ostream> Out;
183 std::unique_ptr<ASTConsumer>
184 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
187 if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
190 std::unique_ptr<llvm::raw_ostream> OS;
192 OS = llvm::make_unique<llvm::raw_string_ostream>(*InMemStorage);
194 std::string OutputFile;
195 OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
200 if (!CI.getFrontendOpts().RelocatablePCH)
203 return llvm::make_unique<PrecompilePreambleConsumer>(
204 *this, CI.getPreprocessor(), Sysroot, std::move(OS));
207 template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
210 Output = std::move(*Val);
216 PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
217 llvm::MemoryBuffer *Buffer,
219 return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
222 llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
223 const CompilerInvocation &Invocation,
224 const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
225 DiagnosticsEngine &Diagnostics, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
226 std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
227 PreambleCallbacks &Callbacks) {
228 assert(VFS && "VFS is null");
231 return BuildPreambleError::PreambleIsEmpty;
233 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
234 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
235 PreprocessorOptions &PreprocessorOpts =
236 PreambleInvocation->getPreprocessorOpts();
238 llvm::Optional<TempPCHFile> TempFile;
239 if (!StoreInMemory) {
240 // Create a temporary file for the precompiled preamble. In rare
241 // circumstances, this can fail.
242 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
243 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
244 if (!PreamblePCHFile)
245 return BuildPreambleError::CouldntCreateTempFile;
246 TempFile = std::move(*PreamblePCHFile);
249 PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
250 : PCHStorage(std::move(*TempFile));
252 // Save the preamble text for later; we'll need to compare against it for
253 // subsequent reparses.
254 std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
255 MainFileBuffer->getBufferStart() +
257 bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
259 // Tell the compiler invocation to generate a temporary precompiled header.
260 FrontendOpts.ProgramAction = frontend::GeneratePCH;
261 FrontendOpts.OutputFile = StoreInMemory ? getInMemoryPreamblePath()
262 : Storage.asFile().getFilePath();
263 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
264 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
265 // Inform preprocessor to record conditional stack when building the preamble.
266 PreprocessorOpts.GeneratePreamble = true;
268 // Create the compiler instance to use for building the precompiled preamble.
269 std::unique_ptr<CompilerInstance> Clang(
270 new CompilerInstance(std::move(PCHContainerOps)));
272 // Recover resources if we crash before exiting this method.
273 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
276 Clang->setInvocation(std::move(PreambleInvocation));
277 Clang->setDiagnostics(&Diagnostics);
279 // Create the target instance.
280 Clang->setTarget(TargetInfo::CreateTargetInfo(
281 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
282 if (!Clang->hasTarget())
283 return BuildPreambleError::CouldntCreateTargetInfo;
285 // Inform the target of the language options.
287 // FIXME: We shouldn't need to do this, the target should be immutable once
288 // created. This complexity should be lifted elsewhere.
289 Clang->getTarget().adjust(Clang->getLangOpts());
291 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
292 "Invocation must have exactly one source file!");
293 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
295 "FIXME: AST inputs not yet supported here!");
296 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
297 InputKind::LLVM_IR &&
298 "IR inputs not support here!");
300 // Clear out old caches and data.
302 ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
305 createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
307 return BuildPreambleError::CouldntCreateVFSOverlay;
309 // Create a file manager object to provide access to and cache the filesystem.
310 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
312 // Create the source manager.
313 Clang->setSourceManager(
314 new SourceManager(Diagnostics, Clang->getFileManager()));
316 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
317 Clang->addDependencyCollector(PreambleDepCollector);
319 // Remap the main source file to the preamble buffer.
320 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
321 auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
322 MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
323 if (PreprocessorOpts.RetainRemappedFileBuffers) {
324 // MainFileBuffer will be deleted by unique_ptr after leaving the method.
325 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
327 // In that case, remapped buffer will be deleted by CompilerInstance on
328 // BeginSourceFile, so we call release() to avoid double deletion.
329 PreprocessorOpts.addRemappedFile(MainFilePath,
330 PreambleInputBuffer.release());
333 std::unique_ptr<PrecompilePreambleAction> Act;
334 Act.reset(new PrecompilePreambleAction(
335 StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
336 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
337 return BuildPreambleError::BeginSourceFileFailed;
339 std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
340 Callbacks.createPPCallbacks();
341 if (DelegatedPPCallbacks)
342 Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
346 // Run the callbacks.
347 Callbacks.AfterExecute(*Clang);
349 Act->EndSourceFile();
351 if (!Act->hasEmittedPreamblePCH())
352 return BuildPreambleError::CouldntEmitPCH;
354 // Keep track of all of the files that the source manager knows about,
355 // so we can verify whether they have changed or not.
356 llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
358 SourceManager &SourceMgr = Clang->getSourceManager();
359 for (auto &Filename : PreambleDepCollector->getDependencies()) {
360 const FileEntry *File = Clang->getFileManager().getFile(Filename);
361 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
363 if (time_t ModTime = File->getModificationTime()) {
364 FilesInPreamble[File->getName()] =
365 PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
368 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
369 FilesInPreamble[File->getName()] =
370 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
374 return PrecompiledPreamble(std::move(Storage), std::move(PreambleBytes),
375 PreambleEndsAtStartOfLine,
376 std::move(FilesInPreamble));
379 PreambleBounds PrecompiledPreamble::getBounds() const {
380 return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
383 bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
384 const llvm::MemoryBuffer *MainFileBuffer,
385 PreambleBounds Bounds,
386 vfs::FileSystem *VFS) const {
389 Bounds.Size <= MainFileBuffer->getBufferSize() &&
390 "Buffer is too large. Bounds were calculated from a different buffer?");
392 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
393 PreprocessorOptions &PreprocessorOpts =
394 PreambleInvocation->getPreprocessorOpts();
399 // We've previously computed a preamble. Check whether we have the same
400 // preamble now that we did before, and that there's enough space in
401 // the main-file buffer within the precompiled preamble to fit the
403 if (PreambleBytes.size() != Bounds.Size ||
404 PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
405 memcmp(PreambleBytes.data(), MainFileBuffer->getBufferStart(),
408 // The preamble has not changed. We may be able to re-use the precompiled
411 // Check that none of the files used by the preamble have changed.
412 // First, make a record of those files that have been overridden via
413 // remapping or unsaved_files.
414 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
415 for (const auto &R : PreprocessorOpts.RemappedFiles) {
417 if (!moveOnNoError(VFS->status(R.second), Status)) {
418 // If we can't stat the file we're remapping to, assume that something
419 // horrible happened.
423 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
424 Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
427 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
429 if (!moveOnNoError(VFS->status(RB.first), Status))
432 OverriddenFiles[Status.getUniqueID()] =
433 PreambleFileHash::createForMemoryBuffer(RB.second);
436 // Check whether anything has changed.
437 for (const auto &F : FilesInPreamble) {
439 if (!moveOnNoError(VFS->status(F.first()), Status)) {
440 // If we can't stat the file, assume that something horrible happened.
444 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
445 OverriddenFiles.find(Status.getUniqueID());
446 if (Overridden != OverriddenFiles.end()) {
447 // This file was remapped; check whether the newly-mapped file
448 // matches up with the previous mapping.
449 if (Overridden->second != F.second)
454 // The file was not remapped; check whether it has changed on disk.
455 if (Status.getSize() != uint64_t(F.second.Size) ||
456 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
463 void PrecompiledPreamble::AddImplicitPreamble(
464 CompilerInvocation &CI, IntrusiveRefCntPtr<vfs::FileSystem> &VFS,
465 llvm::MemoryBuffer *MainFileBuffer) const {
466 assert(VFS && "VFS must not be null");
468 auto &PreprocessorOpts = CI.getPreprocessorOpts();
470 // Remap main file to point to MainFileBuffer.
471 auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
472 PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
474 // Configure ImpicitPCHInclude.
475 PreprocessorOpts.PrecompiledPreambleBytes.first = PreambleBytes.size();
476 PreprocessorOpts.PrecompiledPreambleBytes.second = PreambleEndsAtStartOfLine;
477 PreprocessorOpts.DisablePCHValidation = true;
479 setupPreambleStorage(Storage, PreprocessorOpts, VFS);
482 PrecompiledPreamble::PrecompiledPreamble(
483 PCHStorage Storage, std::vector<char> PreambleBytes,
484 bool PreambleEndsAtStartOfLine,
485 llvm::StringMap<PreambleFileHash> FilesInPreamble)
486 : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
487 PreambleBytes(std::move(PreambleBytes)),
488 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
489 assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
492 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
493 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
494 // FIXME: This is a hack so that we can override the preamble file during
495 // crash-recovery testing, which is the only case where the preamble files
496 // are not necessarily cleaned up.
497 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
499 return TempPCHFile::createFromCustomPath(TmpFile);
500 return TempPCHFile::createInSystemTempDir("preamble", "pch");
503 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
504 PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
506 llvm::SmallString<64> File;
507 // Using a version of createTemporaryFile with a file descriptor guarantees
508 // that we would never get a race condition in a multi-threaded setting (i.e.,
509 // multiple threads getting the same temporary path).
511 auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File);
514 // We only needed to make sure the file exists, close the file right away.
515 llvm::sys::Process::SafelyCloseFileDescriptor(FD);
516 return TempPCHFile(std::move(File).str());
519 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
520 PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
521 return TempPCHFile(Path.str());
524 PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
525 : FilePath(std::move(FilePath)) {
526 TemporaryFiles::getInstance().addFile(*this->FilePath);
529 PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
530 FilePath = std::move(Other.FilePath);
531 Other.FilePath = None;
534 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
535 operator=(TempPCHFile &&Other) {
536 RemoveFileIfPresent();
538 FilePath = std::move(Other.FilePath);
539 Other.FilePath = None;
543 PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
545 void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
547 TemporaryFiles::getInstance().removeFile(*FilePath);
552 llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
553 assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
557 PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
558 : StorageKind(Kind::TempFile) {
559 new (&asFile()) TempPCHFile(std::move(File));
562 PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
563 : StorageKind(Kind::InMemory) {
564 new (&asMemory()) InMemoryPreamble(std::move(Memory));
567 PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
568 *this = std::move(Other);
571 PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
572 operator=(PCHStorage &&Other) {
575 StorageKind = Other.StorageKind;
576 switch (StorageKind) {
581 new (&asFile()) TempPCHFile(std::move(Other.asFile()));
584 new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
592 PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
594 PrecompiledPreamble::PCHStorage::Kind
595 PrecompiledPreamble::PCHStorage::getKind() const {
599 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
600 assert(getKind() == Kind::TempFile);
601 return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
604 const PrecompiledPreamble::TempPCHFile &
605 PrecompiledPreamble::PCHStorage::asFile() const {
606 return const_cast<PCHStorage *>(this)->asFile();
609 PrecompiledPreamble::InMemoryPreamble &
610 PrecompiledPreamble::PCHStorage::asMemory() {
611 assert(getKind() == Kind::InMemory);
612 return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
615 const PrecompiledPreamble::InMemoryPreamble &
616 PrecompiledPreamble::PCHStorage::asMemory() const {
617 return const_cast<PCHStorage *>(this)->asMemory();
620 void PrecompiledPreamble::PCHStorage::destroy() {
621 switch (StorageKind) {
625 asFile().~TempPCHFile();
628 asMemory().~InMemoryPreamble();
633 void PrecompiledPreamble::PCHStorage::setEmpty() {
635 StorageKind = Kind::Empty;
638 PrecompiledPreamble::PreambleFileHash
639 PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
641 PreambleFileHash Result;
643 Result.ModTime = ModTime;
648 PrecompiledPreamble::PreambleFileHash
649 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
650 const llvm::MemoryBuffer *Buffer) {
651 PreambleFileHash Result;
652 Result.Size = Buffer->getBufferSize();
656 MD5Ctx.update(Buffer->getBuffer().data());
657 MD5Ctx.final(Result.MD5);
662 void PrecompiledPreamble::setupPreambleStorage(
663 const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
664 IntrusiveRefCntPtr<vfs::FileSystem> &VFS) {
665 if (Storage.getKind() == PCHStorage::Kind::TempFile) {
666 const TempPCHFile &PCHFile = Storage.asFile();
667 PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
669 // Make sure we can access the PCH file even if we're using a VFS
670 IntrusiveRefCntPtr<vfs::FileSystem> RealFS = vfs::getRealFileSystem();
671 auto PCHPath = PCHFile.getFilePath();
672 if (VFS == RealFS || VFS->exists(PCHPath))
674 auto Buf = RealFS->getBufferForFile(PCHPath);
676 // We can't read the file even from RealFS, this is clearly an error,
677 // but we'll just leave the current VFS as is and let clang's code
678 // figure out what to do with missing PCH.
682 // We have a slight inconsistency here -- we're using the VFS to
683 // read files, but the PCH was generated in the real file system.
684 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
686 assert(Storage.getKind() == PCHStorage::Kind::InMemory);
687 // For in-memory preamble, we have to provide a VFS overlay that makes it
689 StringRef PCHPath = getInMemoryPreamblePath();
690 PreprocessorOpts.ImplicitPCHInclude = PCHPath;
692 auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
693 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
697 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
698 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
699 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
700 std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
704 std::error_code clang::make_error_code(BuildPreambleError Error) {
705 return std::error_code(static_cast<int>(Error), BuildPreambleErrorCategory());
708 const char *BuildPreambleErrorCategory::name() const noexcept {
709 return "build-preamble.error";
712 std::string BuildPreambleErrorCategory::message(int condition) const {
713 switch (static_cast<BuildPreambleError>(condition)) {
714 case BuildPreambleError::PreambleIsEmpty:
715 return "Preamble is empty";
716 case BuildPreambleError::CouldntCreateTempFile:
717 return "Could not create temporary file for PCH";
718 case BuildPreambleError::CouldntCreateTargetInfo:
719 return "CreateTargetInfo() return null";
720 case BuildPreambleError::CouldntCreateVFSOverlay:
721 return "Could not create VFS Overlay";
722 case BuildPreambleError::BeginSourceFileFailed:
723 return "BeginSourceFile() return an error";
724 case BuildPreambleError::CouldntEmitPCH:
725 return "Could not emit PCH";
727 llvm_unreachable("unexpected BuildPreambleError");