1 //===--- PrecompiledPreamble.cpp - Build precompiled preambles --*- 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 // Helper class to build precompiled preamble.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Frontend/PrecompiledPreamble.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/LangStandard.h"
17 #include "clang/Basic/TargetInfo.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/Preprocessor.h"
24 #include "clang/Lex/PreprocessorOptions.h"
25 #include "clang/Serialization/ASTWriter.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/Config/llvm-config.h"
29 #include "llvm/Support/CrashRecoveryContext.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Process.h"
32 #include "llvm/Support/VirtualFileSystem.h"
33 #include <limits>
34 #include <mutex>
35 #include <utility>
36 
37 using namespace clang;
38 
39 namespace {
40 
41 StringRef getInMemoryPreamblePath() {
42 #if defined(LLVM_ON_UNIX)
43   return "/__clang_tmp/___clang_inmemory_preamble___";
44 #elif defined(_WIN32)
45   return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
46 #else
47 #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
48   return "/__clang_tmp/___clang_inmemory_preamble___";
49 #endif
50 }
51 
52 IntrusiveRefCntPtr<llvm::vfs::FileSystem>
53 createVFSOverlayForPreamblePCH(StringRef PCHFilename,
54                                std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
55                                IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
56   // We want only the PCH file from the real filesystem to be available,
57   // so we create an in-memory VFS with just that and overlay it on top.
58   IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> PCHFS(
59       new llvm::vfs::InMemoryFileSystem());
60   PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
61   IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> Overlay(
62       new llvm::vfs::OverlayFileSystem(VFS));
63   Overlay->pushOverlay(PCHFS);
64   return Overlay;
65 }
66 
67 class PreambleDependencyCollector : public DependencyCollector {
68 public:
69   // We want to collect all dependencies for correctness. Avoiding the real
70   // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
71   // but there is no way to distinguish between those and the ones that can be
72   // spuriously added by '-isystem' (e.g. to suppress warnings from those
73   // headers).
74   bool needSystemDependencies() override { return true; }
75 };
76 
77 /// Keeps a track of files to be deleted in destructor.
78 class TemporaryFiles {
79 public:
80   // A static instance to be used by all clients.
81   static TemporaryFiles &getInstance();
82 
83 private:
84   // Disallow constructing the class directly.
85   TemporaryFiles() = default;
86   // Disallow copy.
87   TemporaryFiles(const TemporaryFiles &) = delete;
88 
89 public:
90   ~TemporaryFiles();
91 
92   /// Adds \p File to a set of tracked files.
93   void addFile(StringRef File);
94 
95   /// Remove \p File from disk and from the set of tracked files.
96   void removeFile(StringRef File);
97 
98 private:
99   std::mutex Mutex;
100   llvm::StringSet<> Files;
101 };
102 
103 TemporaryFiles &TemporaryFiles::getInstance() {
104   static TemporaryFiles Instance;
105   return Instance;
106 }
107 
108 TemporaryFiles::~TemporaryFiles() {
109   std::lock_guard<std::mutex> Guard(Mutex);
110   for (const auto &File : Files)
111     llvm::sys::fs::remove(File.getKey());
112 }
113 
114 void TemporaryFiles::addFile(StringRef File) {
115   std::lock_guard<std::mutex> Guard(Mutex);
116   auto IsInserted = Files.insert(File).second;
117   (void)IsInserted;
118   assert(IsInserted && "File has already been added");
119 }
120 
121 void TemporaryFiles::removeFile(StringRef File) {
122   std::lock_guard<std::mutex> Guard(Mutex);
123   auto WasPresent = Files.erase(File);
124   (void)WasPresent;
125   assert(WasPresent && "File was not tracked");
126   llvm::sys::fs::remove(File);
127 }
128 
129 class PrecompilePreambleAction : public ASTFrontendAction {
130 public:
131   PrecompilePreambleAction(std::string *InMemStorage,
132                            PreambleCallbacks &Callbacks)
133       : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
134 
135   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
136                                                  StringRef InFile) override;
137 
138   bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
139 
140   void setEmittedPreamblePCH(ASTWriter &Writer) {
141     this->HasEmittedPreamblePCH = true;
142     Callbacks.AfterPCHEmitted(Writer);
143   }
144 
145   bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
146   bool hasCodeCompletionSupport() const override { return false; }
147   bool hasASTFileSupport() const override { return false; }
148   TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
149 
150 private:
151   friend class PrecompilePreambleConsumer;
152 
153   bool HasEmittedPreamblePCH = false;
154   std::string *InMemStorage;
155   PreambleCallbacks &Callbacks;
156 };
157 
158 class PrecompilePreambleConsumer : public PCHGenerator {
159 public:
160   PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
161                              const Preprocessor &PP,
162                              InMemoryModuleCache &ModuleCache,
163                              StringRef isysroot,
164                              std::unique_ptr<raw_ostream> Out)
165       : PCHGenerator(PP, ModuleCache, "", isysroot,
166                      std::make_shared<PCHBuffer>(),
167                      ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
168                      /*AllowASTWithErrors=*/true),
169         Action(Action), Out(std::move(Out)) {}
170 
171   bool HandleTopLevelDecl(DeclGroupRef DG) override {
172     Action.Callbacks.HandleTopLevelDecl(DG);
173     return true;
174   }
175 
176   void HandleTranslationUnit(ASTContext &Ctx) override {
177     PCHGenerator::HandleTranslationUnit(Ctx);
178     if (!hasEmittedPCH())
179       return;
180 
181     // Write the generated bitstream to "Out".
182     *Out << getPCH();
183     // Make sure it hits disk now.
184     Out->flush();
185     // Free the buffer.
186     llvm::SmallVector<char, 0> Empty;
187     getPCH() = std::move(Empty);
188 
189     Action.setEmittedPreamblePCH(getWriter());
190   }
191 
192 private:
193   PrecompilePreambleAction &Action;
194   std::unique_ptr<raw_ostream> Out;
195 };
196 
197 std::unique_ptr<ASTConsumer>
198 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
199                                             StringRef InFile) {
200   std::string Sysroot;
201   if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
202     return nullptr;
203 
204   std::unique_ptr<llvm::raw_ostream> OS;
205   if (InMemStorage) {
206     OS = std::make_unique<llvm::raw_string_ostream>(*InMemStorage);
207   } else {
208     std::string OutputFile;
209     OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
210   }
211   if (!OS)
212     return nullptr;
213 
214   if (!CI.getFrontendOpts().RelocatablePCH)
215     Sysroot.clear();
216 
217   return std::make_unique<PrecompilePreambleConsumer>(
218       *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
219 }
220 
221 template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
222   if (!Val)
223     return false;
224   Output = std::move(*Val);
225   return true;
226 }
227 
228 } // namespace
229 
230 PreambleBounds clang::ComputePreambleBounds(const LangOptions &LangOpts,
231                                             const llvm::MemoryBuffer *Buffer,
232                                             unsigned MaxLines) {
233   return Lexer::ComputePreamble(Buffer->getBuffer(), LangOpts, MaxLines);
234 }
235 
236 llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
237     const CompilerInvocation &Invocation,
238     const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
239     DiagnosticsEngine &Diagnostics,
240     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
241     std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
242     PreambleCallbacks &Callbacks) {
243   assert(VFS && "VFS is null");
244 
245   auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
246   FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
247   PreprocessorOptions &PreprocessorOpts =
248       PreambleInvocation->getPreprocessorOpts();
249 
250   llvm::Optional<TempPCHFile> TempFile;
251   if (!StoreInMemory) {
252     // Create a temporary file for the precompiled preamble. In rare
253     // circumstances, this can fail.
254     llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> PreamblePCHFile =
255         PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile();
256     if (!PreamblePCHFile)
257       return BuildPreambleError::CouldntCreateTempFile;
258     TempFile = std::move(*PreamblePCHFile);
259   }
260 
261   PCHStorage Storage = StoreInMemory ? PCHStorage(InMemoryPreamble())
262                                      : PCHStorage(std::move(*TempFile));
263 
264   // Save the preamble text for later; we'll need to compare against it for
265   // subsequent reparses.
266   std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
267                                   MainFileBuffer->getBufferStart() +
268                                       Bounds.Size);
269   bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
270 
271   // Tell the compiler invocation to generate a temporary precompiled header.
272   FrontendOpts.ProgramAction = frontend::GeneratePCH;
273   FrontendOpts.OutputFile =
274       std::string(StoreInMemory ? getInMemoryPreamblePath()
275                                 : Storage.asFile().getFilePath());
276   PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
277   PreprocessorOpts.PrecompiledPreambleBytes.second = false;
278   // Inform preprocessor to record conditional stack when building the preamble.
279   PreprocessorOpts.GeneratePreamble = true;
280 
281   // Create the compiler instance to use for building the precompiled preamble.
282   std::unique_ptr<CompilerInstance> Clang(
283       new CompilerInstance(std::move(PCHContainerOps)));
284 
285   // Recover resources if we crash before exiting this method.
286   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
287       Clang.get());
288 
289   Clang->setInvocation(std::move(PreambleInvocation));
290   Clang->setDiagnostics(&Diagnostics);
291 
292   // Create the target instance.
293   Clang->setTarget(TargetInfo::CreateTargetInfo(
294       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
295   if (!Clang->hasTarget())
296     return BuildPreambleError::CouldntCreateTargetInfo;
297 
298   // Inform the target of the language options.
299   //
300   // FIXME: We shouldn't need to do this, the target should be immutable once
301   // created. This complexity should be lifted elsewhere.
302   Clang->getTarget().adjust(Clang->getLangOpts());
303 
304   if (Clang->getFrontendOpts().Inputs.size() != 1 ||
305       Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
306           InputKind::Source ||
307       Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
308           Language::LLVM_IR) {
309     return BuildPreambleError::BadInputs;
310   }
311 
312   // Clear out old caches and data.
313   Diagnostics.Reset();
314   ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
315 
316   VFS =
317       createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
318 
319   // Create a file manager object to provide access to and cache the filesystem.
320   Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
321 
322   // Create the source manager.
323   Clang->setSourceManager(
324       new SourceManager(Diagnostics, Clang->getFileManager()));
325 
326   auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
327   Clang->addDependencyCollector(PreambleDepCollector);
328 
329   // Remap the main source file to the preamble buffer.
330   StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
331   auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
332       MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
333   if (PreprocessorOpts.RetainRemappedFileBuffers) {
334     // MainFileBuffer will be deleted by unique_ptr after leaving the method.
335     PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
336   } else {
337     // In that case, remapped buffer will be deleted by CompilerInstance on
338     // BeginSourceFile, so we call release() to avoid double deletion.
339     PreprocessorOpts.addRemappedFile(MainFilePath,
340                                      PreambleInputBuffer.release());
341   }
342 
343   std::unique_ptr<PrecompilePreambleAction> Act;
344   Act.reset(new PrecompilePreambleAction(
345       StoreInMemory ? &Storage.asMemory().Data : nullptr, Callbacks));
346   Callbacks.BeforeExecute(*Clang);
347   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
348     return BuildPreambleError::BeginSourceFileFailed;
349 
350   std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
351       Callbacks.createPPCallbacks();
352   if (DelegatedPPCallbacks)
353     Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
354   if (auto CommentHandler = Callbacks.getCommentHandler())
355     Clang->getPreprocessor().addCommentHandler(CommentHandler);
356 
357   if (llvm::Error Err = Act->Execute())
358     return errorToErrorCode(std::move(Err));
359 
360   // Run the callbacks.
361   Callbacks.AfterExecute(*Clang);
362 
363   Act->EndSourceFile();
364 
365   if (!Act->hasEmittedPreamblePCH())
366     return BuildPreambleError::CouldntEmitPCH;
367 
368   // Keep track of all of the files that the source manager knows about,
369   // so we can verify whether they have changed or not.
370   llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
371 
372   SourceManager &SourceMgr = Clang->getSourceManager();
373   for (auto &Filename : PreambleDepCollector->getDependencies()) {
374     auto FileOrErr = Clang->getFileManager().getFile(Filename);
375     if (!FileOrErr ||
376         *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
377       continue;
378     auto File = *FileOrErr;
379     if (time_t ModTime = File->getModificationTime()) {
380       FilesInPreamble[File->getName()] =
381           PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
382                                                                ModTime);
383     } else {
384       const llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
385       FilesInPreamble[File->getName()] =
386           PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
387     }
388   }
389 
390   return PrecompiledPreamble(std::move(Storage), std::move(PreambleBytes),
391                              PreambleEndsAtStartOfLine,
392                              std::move(FilesInPreamble));
393 }
394 
395 PreambleBounds PrecompiledPreamble::getBounds() const {
396   return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
397 }
398 
399 std::size_t PrecompiledPreamble::getSize() const {
400   switch (Storage.getKind()) {
401   case PCHStorage::Kind::Empty:
402     assert(false && "Calling getSize() on invalid PrecompiledPreamble. "
403                     "Was it std::moved?");
404     return 0;
405   case PCHStorage::Kind::InMemory:
406     return Storage.asMemory().Data.size();
407   case PCHStorage::Kind::TempFile: {
408     uint64_t Result;
409     if (llvm::sys::fs::file_size(Storage.asFile().getFilePath(), Result))
410       return 0;
411 
412     assert(Result <= std::numeric_limits<std::size_t>::max() &&
413            "file size did not fit into size_t");
414     return Result;
415   }
416   }
417   llvm_unreachable("Unhandled storage kind");
418 }
419 
420 bool PrecompiledPreamble::CanReuse(const CompilerInvocation &Invocation,
421                                    const llvm::MemoryBuffer *MainFileBuffer,
422                                    PreambleBounds Bounds,
423                                    llvm::vfs::FileSystem *VFS) const {
424 
425   assert(
426       Bounds.Size <= MainFileBuffer->getBufferSize() &&
427       "Buffer is too large. Bounds were calculated from a different buffer?");
428 
429   auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
430   PreprocessorOptions &PreprocessorOpts =
431       PreambleInvocation->getPreprocessorOpts();
432 
433   // We've previously computed a preamble. Check whether we have the same
434   // preamble now that we did before, and that there's enough space in
435   // the main-file buffer within the precompiled preamble to fit the
436   // new main file.
437   if (PreambleBytes.size() != Bounds.Size ||
438       PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
439       !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
440                   MainFileBuffer->getBuffer().begin()))
441     return false;
442   // The preamble has not changed. We may be able to re-use the precompiled
443   // preamble.
444 
445   // Check that none of the files used by the preamble have changed.
446   // First, make a record of those files that have been overridden via
447   // remapping or unsaved_files.
448   std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
449   for (const auto &R : PreprocessorOpts.RemappedFiles) {
450     llvm::vfs::Status Status;
451     if (!moveOnNoError(VFS->status(R.second), Status)) {
452       // If we can't stat the file we're remapping to, assume that something
453       // horrible happened.
454       return false;
455     }
456 
457     OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
458         Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
459   }
460 
461   // OverridenFileBuffers tracks only the files not found in VFS.
462   llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
463   for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
464     const PrecompiledPreamble::PreambleFileHash PreambleHash =
465         PreambleFileHash::createForMemoryBuffer(RB.second);
466     llvm::vfs::Status Status;
467     if (moveOnNoError(VFS->status(RB.first), Status))
468       OverriddenFiles[Status.getUniqueID()] = PreambleHash;
469     else
470       OverridenFileBuffers[RB.first] = PreambleHash;
471   }
472 
473   // Check whether anything has changed.
474   for (const auto &F : FilesInPreamble) {
475     auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
476     if (OverridenFileBuffer != OverridenFileBuffers.end()) {
477       // The file's buffer was remapped and the file was not found in VFS.
478       // Check whether it matches up with the previous mapping.
479       if (OverridenFileBuffer->second != F.second)
480         return false;
481       continue;
482     }
483 
484     llvm::vfs::Status Status;
485     if (!moveOnNoError(VFS->status(F.first()), Status)) {
486       // If the file's buffer is not remapped and we can't stat it,
487       // assume that something horrible happened.
488       return false;
489     }
490 
491     std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
492         OverriddenFiles.find(Status.getUniqueID());
493     if (Overridden != OverriddenFiles.end()) {
494       // This file was remapped; check whether the newly-mapped file
495       // matches up with the previous mapping.
496       if (Overridden->second != F.second)
497         return false;
498       continue;
499     }
500 
501     // Neither the file's buffer nor the file itself was remapped;
502     // check whether it has changed on disk.
503     if (Status.getSize() != uint64_t(F.second.Size) ||
504         llvm::sys::toTimeT(Status.getLastModificationTime()) !=
505             F.second.ModTime)
506       return false;
507   }
508   return true;
509 }
510 
511 void PrecompiledPreamble::AddImplicitPreamble(
512     CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
513     llvm::MemoryBuffer *MainFileBuffer) const {
514   PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
515   configurePreamble(Bounds, CI, VFS, MainFileBuffer);
516 }
517 
518 void PrecompiledPreamble::OverridePreamble(
519     CompilerInvocation &CI, IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
520     llvm::MemoryBuffer *MainFileBuffer) const {
521   auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), MainFileBuffer, 0);
522   configurePreamble(Bounds, CI, VFS, MainFileBuffer);
523 }
524 
525 PrecompiledPreamble::PrecompiledPreamble(
526     PCHStorage Storage, std::vector<char> PreambleBytes,
527     bool PreambleEndsAtStartOfLine,
528     llvm::StringMap<PreambleFileHash> FilesInPreamble)
529     : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
530       PreambleBytes(std::move(PreambleBytes)),
531       PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
532   assert(this->Storage.getKind() != PCHStorage::Kind::Empty);
533 }
534 
535 llvm::ErrorOr<PrecompiledPreamble::TempPCHFile>
536 PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() {
537   // FIXME: This is a hack so that we can override the preamble file during
538   // crash-recovery testing, which is the only case where the preamble files
539   // are not necessarily cleaned up.
540   if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
541     return TempPCHFile(TmpFile);
542 
543   llvm::SmallString<64> File;
544   // Using a version of createTemporaryFile with a file descriptor guarantees
545   // that we would never get a race condition in a multi-threaded setting
546   // (i.e., multiple threads getting the same temporary path).
547   int FD;
548   auto EC = llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File);
549   if (EC)
550     return EC;
551   // We only needed to make sure the file exists, close the file right away.
552   llvm::sys::Process::SafelyCloseFileDescriptor(FD);
553   return TempPCHFile(std::string(std::move(File).str()));
554 }
555 
556 PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath)
557     : FilePath(std::move(FilePath)) {
558   TemporaryFiles::getInstance().addFile(*this->FilePath);
559 }
560 
561 PrecompiledPreamble::TempPCHFile::TempPCHFile(TempPCHFile &&Other) {
562   FilePath = std::move(Other.FilePath);
563   Other.FilePath = None;
564 }
565 
566 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::TempPCHFile::
567 operator=(TempPCHFile &&Other) {
568   RemoveFileIfPresent();
569 
570   FilePath = std::move(Other.FilePath);
571   Other.FilePath = None;
572   return *this;
573 }
574 
575 PrecompiledPreamble::TempPCHFile::~TempPCHFile() { RemoveFileIfPresent(); }
576 
577 void PrecompiledPreamble::TempPCHFile::RemoveFileIfPresent() {
578   if (FilePath) {
579     TemporaryFiles::getInstance().removeFile(*FilePath);
580     FilePath = None;
581   }
582 }
583 
584 llvm::StringRef PrecompiledPreamble::TempPCHFile::getFilePath() const {
585   assert(FilePath && "TempPCHFile doesn't have a FilePath. Had it been moved?");
586   return *FilePath;
587 }
588 
589 PrecompiledPreamble::PCHStorage::PCHStorage(TempPCHFile File)
590     : StorageKind(Kind::TempFile) {
591   new (&asFile()) TempPCHFile(std::move(File));
592 }
593 
594 PrecompiledPreamble::PCHStorage::PCHStorage(InMemoryPreamble Memory)
595     : StorageKind(Kind::InMemory) {
596   new (&asMemory()) InMemoryPreamble(std::move(Memory));
597 }
598 
599 PrecompiledPreamble::PCHStorage::PCHStorage(PCHStorage &&Other) : PCHStorage() {
600   *this = std::move(Other);
601 }
602 
603 PrecompiledPreamble::PCHStorage &PrecompiledPreamble::PCHStorage::
604 operator=(PCHStorage &&Other) {
605   destroy();
606 
607   StorageKind = Other.StorageKind;
608   switch (StorageKind) {
609   case Kind::Empty:
610     // do nothing;
611     break;
612   case Kind::TempFile:
613     new (&asFile()) TempPCHFile(std::move(Other.asFile()));
614     break;
615   case Kind::InMemory:
616     new (&asMemory()) InMemoryPreamble(std::move(Other.asMemory()));
617     break;
618   }
619 
620   Other.setEmpty();
621   return *this;
622 }
623 
624 PrecompiledPreamble::PCHStorage::~PCHStorage() { destroy(); }
625 
626 PrecompiledPreamble::PCHStorage::Kind
627 PrecompiledPreamble::PCHStorage::getKind() const {
628   return StorageKind;
629 }
630 
631 PrecompiledPreamble::TempPCHFile &PrecompiledPreamble::PCHStorage::asFile() {
632   assert(getKind() == Kind::TempFile);
633   return *reinterpret_cast<TempPCHFile *>(Storage.buffer);
634 }
635 
636 const PrecompiledPreamble::TempPCHFile &
637 PrecompiledPreamble::PCHStorage::asFile() const {
638   return const_cast<PCHStorage *>(this)->asFile();
639 }
640 
641 PrecompiledPreamble::InMemoryPreamble &
642 PrecompiledPreamble::PCHStorage::asMemory() {
643   assert(getKind() == Kind::InMemory);
644   return *reinterpret_cast<InMemoryPreamble *>(Storage.buffer);
645 }
646 
647 const PrecompiledPreamble::InMemoryPreamble &
648 PrecompiledPreamble::PCHStorage::asMemory() const {
649   return const_cast<PCHStorage *>(this)->asMemory();
650 }
651 
652 void PrecompiledPreamble::PCHStorage::destroy() {
653   switch (StorageKind) {
654   case Kind::Empty:
655     return;
656   case Kind::TempFile:
657     asFile().~TempPCHFile();
658     return;
659   case Kind::InMemory:
660     asMemory().~InMemoryPreamble();
661     return;
662   }
663 }
664 
665 void PrecompiledPreamble::PCHStorage::setEmpty() {
666   destroy();
667   StorageKind = Kind::Empty;
668 }
669 
670 PrecompiledPreamble::PreambleFileHash
671 PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
672                                                      time_t ModTime) {
673   PreambleFileHash Result;
674   Result.Size = Size;
675   Result.ModTime = ModTime;
676   Result.MD5 = {};
677   return Result;
678 }
679 
680 PrecompiledPreamble::PreambleFileHash
681 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
682     const llvm::MemoryBuffer *Buffer) {
683   PreambleFileHash Result;
684   Result.Size = Buffer->getBufferSize();
685   Result.ModTime = 0;
686 
687   llvm::MD5 MD5Ctx;
688   MD5Ctx.update(Buffer->getBuffer().data());
689   MD5Ctx.final(Result.MD5);
690 
691   return Result;
692 }
693 
694 void PrecompiledPreamble::configurePreamble(
695     PreambleBounds Bounds, CompilerInvocation &CI,
696     IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS,
697     llvm::MemoryBuffer *MainFileBuffer) const {
698   assert(VFS);
699 
700   auto &PreprocessorOpts = CI.getPreprocessorOpts();
701 
702   // Remap main file to point to MainFileBuffer.
703   auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
704   PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
705 
706   // Configure ImpicitPCHInclude.
707   PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
708   PreprocessorOpts.PrecompiledPreambleBytes.second =
709       Bounds.PreambleEndsAtStartOfLine;
710   PreprocessorOpts.DisablePCHValidation = true;
711 
712   setupPreambleStorage(Storage, PreprocessorOpts, VFS);
713 }
714 
715 void PrecompiledPreamble::setupPreambleStorage(
716     const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
717     IntrusiveRefCntPtr<llvm::vfs::FileSystem> &VFS) {
718   if (Storage.getKind() == PCHStorage::Kind::TempFile) {
719     const TempPCHFile &PCHFile = Storage.asFile();
720     PreprocessorOpts.ImplicitPCHInclude = std::string(PCHFile.getFilePath());
721 
722     // Make sure we can access the PCH file even if we're using a VFS
723     IntrusiveRefCntPtr<llvm::vfs::FileSystem> RealFS =
724         llvm::vfs::getRealFileSystem();
725     auto PCHPath = PCHFile.getFilePath();
726     if (VFS == RealFS || VFS->exists(PCHPath))
727       return;
728     auto Buf = RealFS->getBufferForFile(PCHPath);
729     if (!Buf) {
730       // We can't read the file even from RealFS, this is clearly an error,
731       // but we'll just leave the current VFS as is and let clang's code
732       // figure out what to do with missing PCH.
733       return;
734     }
735 
736     // We have a slight inconsistency here -- we're using the VFS to
737     // read files, but the PCH was generated in the real file system.
738     VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
739   } else {
740     assert(Storage.getKind() == PCHStorage::Kind::InMemory);
741     // For in-memory preamble, we have to provide a VFS overlay that makes it
742     // accessible.
743     StringRef PCHPath = getInMemoryPreamblePath();
744     PreprocessorOpts.ImplicitPCHInclude = std::string(PCHPath);
745 
746     auto Buf = llvm::MemoryBuffer::getMemBuffer(Storage.asMemory().Data);
747     VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
748   }
749 }
750 
751 void PreambleCallbacks::BeforeExecute(CompilerInstance &CI) {}
752 void PreambleCallbacks::AfterExecute(CompilerInstance &CI) {}
753 void PreambleCallbacks::AfterPCHEmitted(ASTWriter &Writer) {}
754 void PreambleCallbacks::HandleTopLevelDecl(DeclGroupRef DG) {}
755 std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
756   return nullptr;
757 }
758 CommentHandler *PreambleCallbacks::getCommentHandler() { return nullptr; }
759 
760 static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
761 
762 std::error_code clang::make_error_code(BuildPreambleError Error) {
763   return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
764 }
765 
766 const char *BuildPreambleErrorCategory::name() const noexcept {
767   return "build-preamble.error";
768 }
769 
770 std::string BuildPreambleErrorCategory::message(int condition) const {
771   switch (static_cast<BuildPreambleError>(condition)) {
772   case BuildPreambleError::CouldntCreateTempFile:
773     return "Could not create temporary file for PCH";
774   case BuildPreambleError::CouldntCreateTargetInfo:
775     return "CreateTargetInfo() return null";
776   case BuildPreambleError::BeginSourceFileFailed:
777     return "BeginSourceFile() return an error";
778   case BuildPreambleError::CouldntEmitPCH:
779     return "Could not emit PCH";
780   case BuildPreambleError::BadInputs:
781     return "Command line arguments must contain exactly one source file";
782   }
783   llvm_unreachable("unexpected BuildPreambleError");
784 }
785