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