1 //===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // Helper class to build precompiled preamble.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Frontend/PrecompiledPreamble.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/Basic/LangStandard.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Frontend/CompilerInstance.h"
18 #include "clang/Frontend/CompilerInvocation.h"
19 #include "clang/Frontend/FrontendActions.h"
20 #include "clang/Frontend/FrontendOptions.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Lex/Preprocessor.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/Process.h"
31 #include "llvm/Support/VirtualFileSystem.h"
36 using namespace clang;
40 StringRef getInMemoryPreamblePath() {
41 #if defined(LLVM_ON_UNIX)
42 return "/__clang_tmp/___clang_inmemory_preamble___";
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<llvm::vfs::FileSystem>
52 createVFSOverlayForPreamblePCH(StringRef PCHFilename,
53 std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
54 IntrusiveRefCntPtr<llvm::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<llvm::vfs::InMemoryFileSystem> PCHFS(
58 new llvm::vfs::InMemoryFileSystem());
59 PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
60 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
61 new llvm::vfs::OverlayFileSystem(VFS));
62 Overlay->pushOverlay(PCHFS);
66 class PreambleDependencyCollector : public DependencyCollector {
68 // We want to collect all dependencies for correctness. Avoiding the real
69 // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
70 // but there is no way to distinguish between those and the ones that can be
71 // spuriously added by '-isystem' (e.g. to suppress warnings from those
73 bool needSystemDependencies() override { return true; }
76 /// Keeps a track of files to be deleted in destructor.
77 class TemporaryFiles {
79 // A static instance to be used by all clients.
80 static TemporaryFiles &getInstance();
83 // Disallow constructing the class directly.
84 TemporaryFiles() = default;
86 TemporaryFiles(const TemporaryFiles &) = delete;
91 /// Adds \p File to a set of tracked files.
92 void addFile(StringRef File);
94 /// Remove \p File from disk and from the set of tracked files.
95 void removeFile(StringRef File);
99 llvm::StringSet<> Files;
102 TemporaryFiles &TemporaryFiles::getInstance() {
103 static TemporaryFiles Instance;
107 TemporaryFiles::~TemporaryFiles() {
108 std::lock_guard<std::mutex> Guard(Mutex);
109 for (const auto &File : Files)
110 llvm::sys::fs::remove(File.getKey());
113 void TemporaryFiles::addFile(StringRef File) {
114 std::lock_guard<std::mutex> Guard(Mutex);
115 auto IsInserted = Files.insert(File).second;
117 assert(IsInserted && "File has already been added");
120 void TemporaryFiles::removeFile(StringRef File) {
121 std::lock_guard<std::mutex> Guard(Mutex);
122 auto WasPresent = Files.erase(File);
124 assert(WasPresent && "File was not tracked");
125 llvm::sys::fs::remove(File);
128 class PrecompilePreambleAction : public ASTFrontendAction {
130 PrecompilePreambleAction(std::string *InMemStorage,
131 PreambleCallbacks &Callbacks)
132 : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
134 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
135 StringRef InFile) override;
137 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
139 void setEmittedPreamblePCH(ASTWriter &Writer) {
140 this->HasEmittedPreamblePCH = true;
141 Callbacks.AfterPCHEmitted(Writer);
144 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
145 bool hasCodeCompletionSupport() const override { return false; }
146 bool hasASTFileSupport() const override { return false; }
147 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
150 friend class PrecompilePreambleConsumer;
152 bool HasEmittedPreamblePCH = false;
153 std::string *InMemStorage;
154 PreambleCallbacks &Callbacks;
157 class PrecompilePreambleConsumer : public PCHGenerator {
159 PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
160 const Preprocessor &PP,
161 InMemoryModuleCache &ModuleCache,
163 std::unique_ptr<raw_ostream> Out)
164 : PCHGenerator(PP, ModuleCache, "", isysroot,
165 std::make_shared<PCHBuffer>(),
166 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
167 /*AllowASTWithErrors=*/true),
168 Action(Action), Out(std::move(Out)) {}
170 bool HandleTopLevelDecl(DeclGroupRef DG) override {
171 Action.Callbacks.HandleTopLevelDecl(DG);
175 void HandleTranslationUnit(ASTContext &Ctx) override {
176 PCHGenerator::HandleTranslationUnit(Ctx);
177 if (!hasEmittedPCH())
180 // Write the generated bitstream to "Out".
182 // Make sure it hits disk now.
185 llvm::SmallVector<char, 0> Empty;
186 getPCH() = std::move(Empty);
188 Action.setEmittedPreamblePCH(getWriter());
192 PrecompilePreambleAction &Action;
193 std::unique_ptr<raw_ostream> Out;
196 std::unique_ptr<ASTConsumer>
197 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
200 if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
203 std::unique_ptr<llvm::raw_ostream> OS;
205 OS = std::make_unique<llvm::raw_string_ostream>(*InMemStorage);
207 std::string OutputFile;
208 OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
213 if (!CI.getFrontendOpts().RelocatablePCH)
216 return std::make_unique<PrecompilePreambleConsumer>(
217 *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
220 template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
223 Output = std::move(*Val);
229 PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
230 llvm::MemoryBuffer *Buffer,
232 return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
235 llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
236 const CompilerInvocation &Invocation,
237 const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
238 DiagnosticsEngine &Diagnostics,
239 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
240 std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
241 PreambleCallbacks &Callbacks) {
242 assert(VFS && "VFS is null");
244 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
245 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
246 PreprocessorOptions &PreprocessorOpts =
247 PreambleInvocation->getPreprocessorOpts();
249 llvm::Optional<TempPCHFile> TempFile;
250 if (!StoreInMemory) {
251 // Create a temporary file for the precompiled preamble. In rare
252 // circumstances, this can fail.
253 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
254 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
255 if (!PreamblePCHFile)
256 return BuildPreambleError::CouldntCreateTempFile;
257 TempFile = std::move(*PreamblePCHFile);
260 PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
261 : PCHStorage(std::move(*TempFile));
263 // Save the preamble text for later; we'll need to compare against it for
264 // subsequent reparses.
265 std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
266 MainFileBuffer->getBufferStart() +
268 bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
270 // Tell the compiler invocation to generate a temporary precompiled header.
271 FrontendOpts.ProgramAction = frontend::GeneratePCH;
272 FrontendOpts.OutputFile = StoreInMemory ? getInMemoryPreamblePath()
273 : Storage.asFile().getFilePath();
274 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
275 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
276 // Inform preprocessor to record conditional stack when building the preamble.
277 PreprocessorOpts.GeneratePreamble = true;
279 // Create the compiler instance to use for building the precompiled preamble.
280 std::unique_ptr<CompilerInstance> Clang(
281 new CompilerInstance(std::move(PCHContainerOps)));
283 // Recover resources if we crash before exiting this method.
284 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
287 Clang->setInvocation(std::move(PreambleInvocation));
288 Clang->setDiagnostics(&Diagnostics);
290 // Create the target instance.
291 Clang->setTarget(TargetInfo::CreateTargetInfo(
292 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
293 if (!Clang->hasTarget())
294 return BuildPreambleError::CouldntCreateTargetInfo;
296 // Inform the target of the language options.
298 // FIXME: We shouldn't need to do this, the target should be immutable once
299 // created. This complexity should be lifted elsewhere.
300 Clang->getTarget().adjust(Clang->getLangOpts());
302 if (Clang->getFrontendOpts().Inputs.size() != 1 ||
303 Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
305 Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
307 return BuildPreambleError::BadInputs;
310 // Clear out old caches and data.
312 ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
315 createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
317 // Create a file manager object to provide access to and cache the filesystem.
318 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
320 // Create the source manager.
321 Clang->setSourceManager(
322 new SourceManager(Diagnostics, Clang->getFileManager()));
324 auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
325 Clang->addDependencyCollector(PreambleDepCollector);
327 // Remap the main source file to the preamble buffer.
328 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
329 auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
330 MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
331 if (PreprocessorOpts.RetainRemappedFileBuffers) {
332 // MainFileBuffer will be deleted by unique_ptr after leaving the method.
333 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
335 // In that case, remapped buffer will be deleted by CompilerInstance on
336 // BeginSourceFile, so we call release() to avoid double deletion.
337 PreprocessorOpts.addRemappedFile(MainFilePath,
338 PreambleInputBuffer.release());
341 std::unique_ptr<PrecompilePreambleAction> Act;
342 Act.reset(new PrecompilePreambleAction(
343 StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
344 Callbacks.BeforeExecute(*Clang);
345 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
346 return BuildPreambleError::BeginSourceFileFailed;
348 std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
349 Callbacks.createPPCallbacks();
350 if (DelegatedPPCallbacks)
351 Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
352 if (auto CommentHandler = Callbacks.getCommentHandler())
353 Clang->getPreprocessor().addCommentHandler(CommentHandler);
355 if (llvm::Error Err = Act->Execute())
356 return errorToErrorCode(std::move(Err));
358 // Run the callbacks.
359 Callbacks.AfterExecute(*Clang);
361 Act->EndSourceFile();
363 if (!Act->hasEmittedPreamblePCH())
364 return BuildPreambleError::CouldntEmitPCH;
366 // Keep track of all of the files that the source manager knows about,
367 // so we can verify whether they have changed or not.
368 llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
370 SourceManager &SourceMgr = Clang->getSourceManager();
371 for (auto &Filename : PreambleDepCollector->getDependencies()) {
372 auto FileOrErr = Clang->getFileManager().getFile(Filename);
374 *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
376 auto File = *FileOrErr;
377 if (time_t ModTime = File->getModificationTime()) {
378 FilesInPreamble[File->getName()] =
379 PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
382 const llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
383 FilesInPreamble[File->getName()] =
384 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
388 return PrecompiledPreamble(std::move(Storage), std::move(PreambleBytes),
389 PreambleEndsAtStartOfLine,
390 std::move(FilesInPreamble));
393 PreambleBounds PrecompiledPreamble::getBounds() const {
394 return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
397 std::size_t PrecompiledPreamble::getSize() const {
398 switch (Storage.getKind()) {
399 case PCHStorage::Kind::Empty:
400 assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
401 "Was it std::moved?");
403 case PCHStorage::Kind::InMemory:
404 return Storage.asMemory().Data.size();
405 case PCHStorage::Kind::TempFile: {
407 if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
410 assert(Result <= std::numeric_limits<std::size_t>::max() &&
411 "file size did not fit into size_t");
415 llvm_unreachable("Unhandled storage kind");
418 bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
419 const llvm::MemoryBuffer *MainFileBuffer,
420 PreambleBounds Bounds,
421 llvm::vfs::FileSystem *VFS) const {
424 Bounds.Size <= MainFileBuffer->getBufferSize() &&
425 "Buffer is too large. Bounds were calculated from a different buffer?");
427 auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
428 PreprocessorOptions &PreprocessorOpts =
429 PreambleInvocation->getPreprocessorOpts();
431 // We've previously computed a preamble. Check whether we have the same
432 // preamble now that we did before, and that there's enough space in
433 // the main-file buffer within the precompiled preamble to fit the
435 if (PreambleBytes.size() != Bounds.Size ||
436 PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
437 !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
438 MainFileBuffer->getBuffer().begin()))
440 // The preamble has not changed. We may be able to re-use the precompiled
443 // Check that none of the files used by the preamble have changed.
444 // First, make a record of those files that have been overridden via
445 // remapping or unsaved_files.
446 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
447 for (const auto &R : PreprocessorOpts.RemappedFiles) {
448 llvm::vfs::Status Status;
449 if (!moveOnNoError(VFS->status(R.second), Status)) {
450 // If we can't stat the file we're remapping to, assume that something
451 // horrible happened.
455 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
456 Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
459 // OverridenFileBuffers tracks only the files not found in VFS.
460 llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
461 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
462 const PrecompiledPreamble::PreambleFileHash PreambleHash =
463 PreambleFileHash::createForMemoryBuffer(RB.second);
464 llvm::vfs::Status Status;
465 if (moveOnNoError(VFS->status(RB.first), Status))
466 OverriddenFiles[Status.getUniqueID()] = PreambleHash;
468 OverridenFileBuffers[RB.first] = PreambleHash;
471 // Check whether anything has changed.
472 for (const auto &F : FilesInPreamble) {
473 auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
474 if (OverridenFileBuffer != OverridenFileBuffers.end()) {
475 // The file's buffer was remapped and the file was not found in VFS.
476 // Check whether it matches up with the previous mapping.
477 if (OverridenFileBuffer->second != F.second)
482 llvm::vfs::Status Status;
483 if (!moveOnNoError(VFS->status(F.first()), Status)) {
484 // If the file's buffer is not remapped and we can't stat it,
485 // assume that something horrible happened.
489 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
490 OverriddenFiles.find(Status.getUniqueID());
491 if (Overridden != OverriddenFiles.end()) {
492 // This file was remapped; check whether the newly-mapped file
493 // matches up with the previous mapping.
494 if (Overridden->second != F.second)
499 // Neither the file's buffer nor the file itself was remapped;
500 // check whether it has changed on disk.
501 if (Status.getSize() != uint64_t(F.second.Size) ||
502 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
509 void PrecompiledPreamble::AddImplicitPreamble(
510 CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
511 llvm::MemoryBuffer *MainFileBuffer) const {
512 PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
513 configurePreamble(Bounds, CI, VFS, MainFileBuffer);
516 void PrecompiledPreamble::OverridePreamble(
517 CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
518 llvm::MemoryBuffer *MainFileBuffer) const {
519 auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0);
520 configurePreamble(Bounds, CI, VFS, MainFileBuffer);
523 PrecompiledPreamble::PrecompiledPreamble(
524 PCHStorage Storage, std::vector<char> PreambleBytes,
525 bool PreambleEndsAtStartOfLine,
526 llvm::StringMap<PreambleFileHash> FilesInPreamble)
527 : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
528 PreambleBytes(std::move(PreambleBytes)),
529 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
530 assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
533 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
534 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
535 // FIXME: This is a hack so that we can override the preamble file during
536 // crash-recovery testing, which is the only case where the preamble files
537 // are not necessarily cleaned up.
538 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
540 return TempPCHFile::createFromCustomPath(TmpFile);
541 return TempPCHFile::createInSystemTempDir("preamble", "pch");
544 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
545 PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix,
547 llvm::SmallString<64> File;
548 // Using a version of createTemporaryFile with a file descriptor guarantees
549 // that we would never get a race condition in a multi-threaded setting
550 // (i.e., multiple threads getting the same temporary path).
552 auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File);
555 // We only needed to make sure the file exists, close the file right away.
556 llvm::sys::Process::SafelyCloseFileDescriptor(FD);
557 return TempPCHFile(std::move(File).str());
560 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
561 PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) {
562 return TempPCHFile(Path.str());
565 PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
566 : FilePath(std::move(FilePath)) {
567 TemporaryFiles::getInstance().addFile(*this->FilePath);
570 PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
571 FilePath = std::move(Other.FilePath);
572 Other.FilePath = None;
575 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
576 operator=(TempPCHFile &&Other) {
577 RemoveFileIfPresent();
579 FilePath = std::move(Other.FilePath);
580 Other.FilePath = None;
584 PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
586 void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
588 TemporaryFiles::getInstance().removeFile(*FilePath);
593 llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
594 assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
598 PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
599 : StorageKind(Kind::TempFile) {
600 new (&asFile()) TempPCHFile(std::move(File));
603 PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
604 : StorageKind(Kind::InMemory) {
605 new (&asMemory()) InMemoryPreamble(std::move(Memory));
608 PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
609 *this = std::move(Other);
612 PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
613 operator=(PCHStorage &&Other) {
616 StorageKind = Other.StorageKind;
617 switch (StorageKind) {
622 new (&asFile()) TempPCHFile(std::move(Other.asFile()));
625 new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
633 PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
635 PrecompiledPreamble::PCHStorage::Kind
636 PrecompiledPreamble::PCHStorage::getKind() const {
640 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
641 assert(getKind() == Kind::TempFile);
642 return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
645 const PrecompiledPreamble::TempPCHFile &
646 PrecompiledPreamble::PCHStorage::asFile() const {
647 return const_cast<PCHStorage *>(this)->asFile();
650 PrecompiledPreamble::InMemoryPreamble &
651 PrecompiledPreamble::PCHStorage::asMemory() {
652 assert(getKind() == Kind::InMemory);
653 return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
656 const PrecompiledPreamble::InMemoryPreamble &
657 PrecompiledPreamble::PCHStorage::asMemory() const {
658 return const_cast<PCHStorage *>(this)->asMemory();
661 void PrecompiledPreamble::PCHStorage::destroy() {
662 switch (StorageKind) {
666 asFile().~TempPCHFile();
669 asMemory().~InMemoryPreamble();
674 void PrecompiledPreamble::PCHStorage::setEmpty() {
676 StorageKind = Kind::Empty;
679 PrecompiledPreamble::PreambleFileHash
680 PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
682 PreambleFileHash Result;
684 Result.ModTime = ModTime;
689 PrecompiledPreamble::PreambleFileHash
690 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
691 const llvm::MemoryBuffer *Buffer) {
692 PreambleFileHash Result;
693 Result.Size = Buffer->getBufferSize();
697 MD5Ctx.update(Buffer->getBuffer().data());
698 MD5Ctx.final(Result.MD5);
703 void PrecompiledPreamble::configurePreamble(
704 PreambleBounds Bounds, CompilerInvocation &CI,
705 IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
706 llvm::MemoryBuffer *MainFileBuffer) const {
709 auto &PreprocessorOpts = CI.getPreprocessorOpts();
711 // Remap main file to point to MainFileBuffer.
712 auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
713 PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
715 // Configure ImpicitPCHInclude.
716 PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
717 PreprocessorOpts.PrecompiledPreambleBytes.second =
718 Bounds.PreambleEndsAtStartOfLine;
719 PreprocessorOpts.DisablePCHValidation = true;
721 setupPreambleStorage(Storage, PreprocessorOpts, VFS);
724 void PrecompiledPreamble::setupPreambleStorage(
725 const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
726 IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
727 if (Storage.getKind() == PCHStorage::Kind::TempFile) {
728 const TempPCHFile &PCHFile = Storage.asFile();
729 PreprocessorOpts.ImplicitPCHInclude = PCHFile.getFilePath();
731 // Make sure we can access the PCH file even if we're using a VFS
732 IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
733 llvm::vfs::getRealFileSystem();
734 auto PCHPath = PCHFile.getFilePath();
735 if (VFS == RealFS || VFS->exists(PCHPath))
737 auto Buf = RealFS->getBufferForFile(PCHPath);
739 // We can't read the file even from RealFS, this is clearly an error,
740 // but we'll just leave the current VFS as is and let clang's code
741 // figure out what to do with missing PCH.
745 // We have a slight inconsistency here -- we're using the VFS to
746 // read files, but the PCH was generated in the real file system.
747 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
749 assert(Storage.getKind() == PCHStorage::Kind::InMemory);
750 // For in-memory preamble, we have to provide a VFS overlay that makes it
752 StringRef PCHPath = getInMemoryPreamblePath();
753 PreprocessorOpts.ImplicitPCHInclude = PCHPath;
755 auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
756 VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
760 void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
761 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
762 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
763 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
764 std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
767 CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
769 static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
771 std::error_code clang::make_error_code(BuildPreambleError Error) {
772 return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
775 const char *BuildPreambleErrorCategory::name() const noexcept {
776 return "build-preamble.error";
779 std::string BuildPreambleErrorCategory::message(int condition) const {
780 switch (static_cast<BuildPreambleError>(condition)) {
781 case BuildPreambleError::CouldntCreateTempFile:
782 return "Could not create temporary file for PCH";
783 case BuildPreambleError::CouldntCreateTargetInfo:
784 return "CreateTargetInfo() return null";
785 case BuildPreambleError::BeginSourceFileFailed:
786 return "BeginSourceFile() return an error";
787 case BuildPreambleError::CouldntEmitPCH:
788 return "Could not emit PCH";
789 case BuildPreambleError::BadInputs:
790 return "Command line arguments must contain exactly one source file";
792 llvm_unreachable("unexpected BuildPreambleError");