clang  16.0.0git
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 
20 #include "clang/Lex/HeaderSearch.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Lex/Preprocessor.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/ADT/iterator_range.h"
28 #include "llvm/Config/llvm-config.h"
29 #include "llvm/Support/CrashRecoveryContext.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/VirtualFileSystem.h"
34 #include <limits>
35 #include <mutex>
36 #include <utility>
37 
38 using namespace clang;
39 
40 namespace {
41 
42 StringRef getInMemoryPreamblePath() {
43 #if defined(LLVM_ON_UNIX)
44  return "/__clang_tmp/___clang_inmemory_preamble___";
45 #elif defined(_WIN32)
46  return "C:\\__clang_tmp\\___clang_inmemory_preamble___";
47 #else
48 #warning "Unknown platform. Defaulting to UNIX-style paths for in-memory PCHs"
49  return "/__clang_tmp/___clang_inmemory_preamble___";
50 #endif
51 }
52 
54 createVFSOverlayForPreamblePCH(StringRef PCHFilename,
55  std::unique_ptr<llvm::MemoryBuffer> PCHBuffer,
57  // We want only the PCH file from the real filesystem to be available,
58  // so we create an in-memory VFS with just that and overlay it on top.
60  new llvm::vfs::InMemoryFileSystem());
61  PCHFS->addFile(PCHFilename, 0, std::move(PCHBuffer));
63  new llvm::vfs::OverlayFileSystem(VFS));
64  Overlay->pushOverlay(PCHFS);
65  return Overlay;
66 }
67 
68 class PreambleDependencyCollector : public DependencyCollector {
69 public:
70  // We want to collect all dependencies for correctness. Avoiding the real
71  // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
72  // but there is no way to distinguish between those and the ones that can be
73  // spuriously added by '-isystem' (e.g. to suppress warnings from those
74  // headers).
75  bool needSystemDependencies() override { return true; }
76 };
77 
78 // Collects files whose existence would invalidate the preamble.
79 // Collecting *all* of these would make validating it too slow though, so we
80 // just find all the candidates for 'file not found' diagnostics.
81 //
82 // A caveat that may be significant for generated files: we'll omit files under
83 // search path entries whose roots don't exist when the preamble is built.
84 // These are pruned by InitHeaderSearch and so we don't see the search path.
85 // It would be nice to include them but we don't want to duplicate all the rest
86 // of the InitHeaderSearch logic to reconstruct them.
87 class MissingFileCollector : public PPCallbacks {
88  llvm::StringSet<> &Out;
89  const HeaderSearch &Search;
90  const SourceManager &SM;
91 
92 public:
93  MissingFileCollector(llvm::StringSet<> &Out, const HeaderSearch &Search,
94  const SourceManager &SM)
95  : Out(Out), Search(Search), SM(SM) {}
96 
97  void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
98  StringRef FileName, bool IsAngled,
99  CharSourceRange FilenameRange,
100  Optional<FileEntryRef> File, StringRef SearchPath,
101  StringRef RelativePath, const Module *Imported,
102  SrcMgr::CharacteristicKind FileType) override {
103  // File is None if it wasn't found.
104  // (We have some false negatives if PP recovered e.g. <foo> -> "foo")
105  if (File)
106  return;
107 
108  // If it's a rare absolute include, we know the full path already.
109  if (llvm::sys::path::is_absolute(FileName)) {
110  Out.insert(FileName);
111  return;
112  }
113 
114  // Reconstruct the filenames that would satisfy this directive...
116  auto NotFoundRelativeTo = [&](const DirectoryEntry *DE) {
117  Buf = DE->getName();
118  llvm::sys::path::append(Buf, FileName);
119  llvm::sys::path::remove_dots(Buf, /*remove_dot_dot=*/true);
120  Out.insert(Buf);
121  };
122  // ...relative to the including file.
123  if (!IsAngled) {
124  if (const FileEntry *IncludingFile =
125  SM.getFileEntryForID(SM.getFileID(IncludeTok.getLocation())))
126  if (IncludingFile->getDir())
127  NotFoundRelativeTo(IncludingFile->getDir());
128  }
129  // ...relative to the search paths.
130  for (const auto &Dir : llvm::make_range(
131  IsAngled ? Search.angled_dir_begin() : Search.search_dir_begin(),
132  Search.search_dir_end())) {
133  // No support for frameworks or header maps yet.
134  if (Dir.isNormalDir())
135  NotFoundRelativeTo(Dir.getDir());
136  }
137  }
138 };
139 
140 /// Keeps a track of files to be deleted in destructor.
141 class TemporaryFiles {
142 public:
143  // A static instance to be used by all clients.
144  static TemporaryFiles &getInstance();
145 
146 private:
147  // Disallow constructing the class directly.
148  TemporaryFiles() = default;
149  // Disallow copy.
150  TemporaryFiles(const TemporaryFiles &) = delete;
151 
152 public:
153  ~TemporaryFiles();
154 
155  /// Adds \p File to a set of tracked files.
156  void addFile(StringRef File);
157 
158  /// Remove \p File from disk and from the set of tracked files.
159  void removeFile(StringRef File);
160 
161 private:
162  std::mutex Mutex;
163  llvm::StringSet<> Files;
164 };
165 
166 TemporaryFiles &TemporaryFiles::getInstance() {
167  static TemporaryFiles Instance;
168  return Instance;
169 }
170 
171 TemporaryFiles::~TemporaryFiles() {
172  std::lock_guard<std::mutex> Guard(Mutex);
173  for (const auto &File : Files)
174  llvm::sys::fs::remove(File.getKey());
175 }
176 
177 void TemporaryFiles::addFile(StringRef File) {
178  std::lock_guard<std::mutex> Guard(Mutex);
179  auto IsInserted = Files.insert(File).second;
180  (void)IsInserted;
181  assert(IsInserted && "File has already been added");
182 }
183 
184 void TemporaryFiles::removeFile(StringRef File) {
185  std::lock_guard<std::mutex> Guard(Mutex);
186  auto WasPresent = Files.erase(File);
187  (void)WasPresent;
188  assert(WasPresent && "File was not tracked");
189  llvm::sys::fs::remove(File);
190 }
191 
192 // A temp file that would be deleted on destructor call. If destructor is not
193 // called for any reason, the file will be deleted at static objects'
194 // destruction.
195 // An assertion will fire if two TempPCHFiles are created with the same name,
196 // so it's not intended to be used outside preamble-handling.
197 class TempPCHFile {
198 public:
199  // A main method used to construct TempPCHFile.
200  static std::unique_ptr<TempPCHFile> create() {
201  // FIXME: This is a hack so that we can override the preamble file during
202  // crash-recovery testing, which is the only case where the preamble files
203  // are not necessarily cleaned up.
204  if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
205  return std::unique_ptr<TempPCHFile>(new TempPCHFile(TmpFile));
206 
208  // Using a version of createTemporaryFile with a file descriptor guarantees
209  // that we would never get a race condition in a multi-threaded setting
210  // (i.e., multiple threads getting the same temporary path).
211  int FD;
212  if (auto EC =
213  llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File))
214  return nullptr;
215  // We only needed to make sure the file exists, close the file right away.
216  llvm::sys::Process::SafelyCloseFileDescriptor(FD);
217  return std::unique_ptr<TempPCHFile>(new TempPCHFile(File.str().str()));
218  }
219 
220  TempPCHFile &operator=(const TempPCHFile &) = delete;
221  TempPCHFile(const TempPCHFile &) = delete;
222  ~TempPCHFile() { TemporaryFiles::getInstance().removeFile(FilePath); };
223 
224  /// A path where temporary file is stored.
225  llvm::StringRef getFilePath() const { return FilePath; };
226 
227 private:
228  TempPCHFile(std::string FilePath) : FilePath(std::move(FilePath)) {
229  TemporaryFiles::getInstance().addFile(this->FilePath);
230  }
231 
232  std::string FilePath;
233 };
234 
235 class PrecompilePreambleAction : public ASTFrontendAction {
236 public:
237  PrecompilePreambleAction(std::shared_ptr<PCHBuffer> Buffer, bool WritePCHFile,
238  PreambleCallbacks &Callbacks)
239  : Buffer(std::move(Buffer)), WritePCHFile(WritePCHFile),
240  Callbacks(Callbacks) {}
241 
242  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
243  StringRef InFile) override;
244 
245  bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
246 
247  void setEmittedPreamblePCH(ASTWriter &Writer) {
248  if (FileOS) {
249  *FileOS << Buffer->Data;
250  // Make sure it hits disk now.
251  FileOS.reset();
252  }
253 
254  this->HasEmittedPreamblePCH = true;
255  Callbacks.AfterPCHEmitted(Writer);
256  }
257 
258  bool BeginSourceFileAction(CompilerInstance &CI) override {
259  assert(CI.getLangOpts().CompilingPCH);
261  }
262 
263  bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
264  bool hasCodeCompletionSupport() const override { return false; }
265  bool hasASTFileSupport() const override { return false; }
266  TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
267 
268 private:
269  friend class PrecompilePreambleConsumer;
270 
271  bool HasEmittedPreamblePCH = false;
272  std::shared_ptr<PCHBuffer> Buffer;
273  bool WritePCHFile; // otherwise the PCH is written into the PCHBuffer only.
274  std::unique_ptr<llvm::raw_pwrite_stream> FileOS; // null if in-memory
275  PreambleCallbacks &Callbacks;
276 };
277 
278 class PrecompilePreambleConsumer : public PCHGenerator {
279 public:
280  PrecompilePreambleConsumer(PrecompilePreambleAction &Action,
281  const Preprocessor &PP,
282  InMemoryModuleCache &ModuleCache,
283  StringRef isysroot,
284  std::shared_ptr<PCHBuffer> Buffer)
285  : PCHGenerator(PP, ModuleCache, "", isysroot, std::move(Buffer),
286  ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
287  /*AllowASTWithErrors=*/true),
288  Action(Action) {}
289 
290  bool HandleTopLevelDecl(DeclGroupRef DG) override {
291  Action.Callbacks.HandleTopLevelDecl(DG);
292  return true;
293  }
294 
295  void HandleTranslationUnit(ASTContext &Ctx) override {
297  if (!hasEmittedPCH())
298  return;
299  Action.setEmittedPreamblePCH(getWriter());
300  }
301 
302  bool shouldSkipFunctionBody(Decl *D) override {
303  return Action.Callbacks.shouldSkipFunctionBody(D);
304  }
305 
306 private:
307  PrecompilePreambleAction &Action;
308 };
309 
310 std::unique_ptr<ASTConsumer>
311 PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
312  StringRef InFile) {
313  std::string Sysroot;
315  return nullptr;
316 
317  if (WritePCHFile) {
318  std::string OutputFile; // unused
319  FileOS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
320  if (!FileOS)
321  return nullptr;
322  }
323 
325  Sysroot.clear();
326 
327  return std::make_unique<PrecompilePreambleConsumer>(
328  *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, Buffer);
329 }
330 
331 template <class T> bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
332  if (!Val)
333  return false;
334  Output = std::move(*Val);
335  return true;
336 }
337 
338 } // namespace
339 
341  const llvm::MemoryBufferRef &Buffer,
342  unsigned MaxLines) {
343  return Lexer::ComputePreamble(Buffer.getBuffer(), LangOpts, MaxLines);
344 }
345 
347 public:
348  static std::unique_ptr<PCHStorage> file(std::unique_ptr<TempPCHFile> File) {
349  assert(File);
350  std::unique_ptr<PCHStorage> S(new PCHStorage());
351  S->File = std::move(File);
352  return S;
353  }
354  static std::unique_ptr<PCHStorage> inMemory(std::shared_ptr<PCHBuffer> Buf) {
355  std::unique_ptr<PCHStorage> S(new PCHStorage());
356  S->Memory = std::move(Buf);
357  return S;
358  }
359 
360  enum class Kind { InMemory, TempFile };
361  Kind getKind() const {
362  if (Memory)
363  return Kind::InMemory;
364  if (File)
365  return Kind::TempFile;
366  llvm_unreachable("Neither Memory nor File?");
367  }
368  llvm::StringRef filePath() const {
369  assert(getKind() == Kind::TempFile);
370  return File->getFilePath();
371  }
372  llvm::StringRef memoryContents() const {
373  assert(getKind() == Kind::InMemory);
374  return StringRef(Memory->Data.data(), Memory->Data.size());
375  }
376 
377  // Shrink in-memory buffers to fit.
378  // This incurs a copy, but preambles tend to be long-lived.
379  // Only safe to call once nothing can alias the buffer.
380  void shrink() {
381  if (!Memory)
382  return;
383  Memory->Data = decltype(Memory->Data)(Memory->Data);
384  }
385 
386 private:
387  PCHStorage() = default;
388  PCHStorage(const PCHStorage &) = delete;
389  PCHStorage &operator=(const PCHStorage &) = delete;
390 
391  std::shared_ptr<PCHBuffer> Memory;
392  std::unique_ptr<TempPCHFile> File;
393 };
394 
399 
400 llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
401  const CompilerInvocation &Invocation,
402  const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds,
403  DiagnosticsEngine &Diagnostics,
405  std::shared_ptr<PCHContainerOperations> PCHContainerOps, bool StoreInMemory,
406  PreambleCallbacks &Callbacks) {
407  assert(VFS && "VFS is null");
408 
409  auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
410  FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
411  PreprocessorOptions &PreprocessorOpts =
412  PreambleInvocation->getPreprocessorOpts();
413 
414  std::shared_ptr<PCHBuffer> Buffer = std::make_shared<PCHBuffer>();
415  std::unique_ptr<PCHStorage> Storage;
416  if (StoreInMemory) {
417  Storage = PCHStorage::inMemory(Buffer);
418  } else {
419  // Create a temporary file for the precompiled preamble. In rare
420  // circumstances, this can fail.
421  std::unique_ptr<TempPCHFile> PreamblePCHFile = TempPCHFile::create();
422  if (!PreamblePCHFile)
424  Storage = PCHStorage::file(std::move(PreamblePCHFile));
425  }
426 
427  // Save the preamble text for later; we'll need to compare against it for
428  // subsequent reparses.
429  std::vector<char> PreambleBytes(MainFileBuffer->getBufferStart(),
430  MainFileBuffer->getBufferStart() +
431  Bounds.Size);
432  bool PreambleEndsAtStartOfLine = Bounds.PreambleEndsAtStartOfLine;
433 
434  // Tell the compiler invocation to generate a temporary precompiled header.
435  FrontendOpts.ProgramAction = frontend::GeneratePCH;
436  FrontendOpts.OutputFile = std::string(
437  StoreInMemory ? getInMemoryPreamblePath() : Storage->filePath());
438  PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
439  PreprocessorOpts.PrecompiledPreambleBytes.second = false;
440  // Inform preprocessor to record conditional stack when building the preamble.
441  PreprocessorOpts.GeneratePreamble = true;
442 
443  // Create the compiler instance to use for building the precompiled preamble.
444  std::unique_ptr<CompilerInstance> Clang(
445  new CompilerInstance(std::move(PCHContainerOps)));
446 
447  // Recover resources if we crash before exiting this method.
448  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> CICleanup(
449  Clang.get());
450 
451  Clang->setInvocation(std::move(PreambleInvocation));
452  Clang->setDiagnostics(&Diagnostics);
453 
454  // Create the target instance.
455  if (!Clang->createTarget())
457 
458  if (Clang->getFrontendOpts().Inputs.size() != 1 ||
459  Clang->getFrontendOpts().Inputs[0].getKind().getFormat() !=
461  Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() ==
464  }
465 
466  // Clear out old caches and data.
467  Diagnostics.Reset();
468  ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts());
469 
470  VFS =
471  createVFSFromCompilerInvocation(Clang->getInvocation(), Diagnostics, VFS);
472 
473  // Create a file manager object to provide access to and cache the filesystem.
474  Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
475 
476  // Create the source manager.
477  Clang->setSourceManager(
478  new SourceManager(Diagnostics, Clang->getFileManager()));
479 
480  auto PreambleDepCollector = std::make_shared<PreambleDependencyCollector>();
481  Clang->addDependencyCollector(PreambleDepCollector);
482 
483  Clang->getLangOpts().CompilingPCH = true;
484 
485  // Remap the main source file to the preamble buffer.
486  StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
487  auto PreambleInputBuffer = llvm::MemoryBuffer::getMemBufferCopy(
488  MainFileBuffer->getBuffer().slice(0, Bounds.Size), MainFilePath);
489  if (PreprocessorOpts.RetainRemappedFileBuffers) {
490  // MainFileBuffer will be deleted by unique_ptr after leaving the method.
491  PreprocessorOpts.addRemappedFile(MainFilePath, PreambleInputBuffer.get());
492  } else {
493  // In that case, remapped buffer will be deleted by CompilerInstance on
494  // BeginSourceFile, so we call release() to avoid double deletion.
495  PreprocessorOpts.addRemappedFile(MainFilePath,
496  PreambleInputBuffer.release());
497  }
498 
499  auto Act = std::make_unique<PrecompilePreambleAction>(
500  std::move(Buffer),
501  /*WritePCHFile=*/Storage->getKind() == PCHStorage::Kind::TempFile,
502  Callbacks);
503  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
505 
506  // Performed after BeginSourceFile to ensure Clang->Preprocessor can be
507  // referenced in the callback.
508  Callbacks.BeforeExecute(*Clang);
509 
510  std::unique_ptr<PPCallbacks> DelegatedPPCallbacks =
511  Callbacks.createPPCallbacks();
512  if (DelegatedPPCallbacks)
513  Clang->getPreprocessor().addPPCallbacks(std::move(DelegatedPPCallbacks));
514  if (auto CommentHandler = Callbacks.getCommentHandler())
515  Clang->getPreprocessor().addCommentHandler(CommentHandler);
516  llvm::StringSet<> MissingFiles;
517  Clang->getPreprocessor().addPPCallbacks(
518  std::make_unique<MissingFileCollector>(
519  MissingFiles, Clang->getPreprocessor().getHeaderSearchInfo(),
520  Clang->getSourceManager()));
521 
522  if (llvm::Error Err = Act->Execute())
523  return errorToErrorCode(std::move(Err));
524 
525  // Run the callbacks.
526  Callbacks.AfterExecute(*Clang);
527 
528  Act->EndSourceFile();
529 
530  if (!Act->hasEmittedPreamblePCH())
532  Act.reset(); // Frees the PCH buffer, unless Storage keeps it in memory.
533 
534  // Keep track of all of the files that the source manager knows about,
535  // so we can verify whether they have changed or not.
536  llvm::StringMap<PrecompiledPreamble::PreambleFileHash> FilesInPreamble;
537 
538  SourceManager &SourceMgr = Clang->getSourceManager();
539  for (auto &Filename : PreambleDepCollector->getDependencies()) {
540  auto FileOrErr = Clang->getFileManager().getFile(Filename);
541  if (!FileOrErr ||
542  *FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
543  continue;
544  auto File = *FileOrErr;
545  if (time_t ModTime = File->getModificationTime()) {
546  FilesInPreamble[File->getName()] =
547  PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
548  ModTime);
549  } else {
550  llvm::MemoryBufferRef Buffer =
552  FilesInPreamble[File->getName()] =
553  PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
554  }
555  }
556 
557  // Shrinking the storage requires extra temporary memory.
558  // Destroying clang first reduces peak memory usage.
559  CICleanup.unregister();
560  Clang.reset();
561  Storage->shrink();
562  return PrecompiledPreamble(
563  std::move(Storage), std::move(PreambleBytes), PreambleEndsAtStartOfLine,
564  std::move(FilesInPreamble), std::move(MissingFiles));
565 }
566 
568  return PreambleBounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
569 }
570 
572  switch (Storage->getKind()) {
573  case PCHStorage::Kind::InMemory:
574  return Storage->memoryContents().size();
575  case PCHStorage::Kind::TempFile: {
576  uint64_t Result;
577  if (llvm::sys::fs::file_size(Storage->filePath(), Result))
578  return 0;
579 
580  assert(Result <= std::numeric_limits<std::size_t>::max() &&
581  "file size did not fit into size_t");
582  return Result;
583  }
584  }
585  llvm_unreachable("Unhandled storage kind");
586 }
587 
589  const llvm::MemoryBufferRef &MainFileBuffer,
590  PreambleBounds Bounds,
591  llvm::vfs::FileSystem &VFS) const {
592 
593  assert(
594  Bounds.Size <= MainFileBuffer.getBufferSize() &&
595  "Buffer is too large. Bounds were calculated from a different buffer?");
596 
597  auto PreambleInvocation = std::make_shared<CompilerInvocation>(Invocation);
598  PreprocessorOptions &PreprocessorOpts =
599  PreambleInvocation->getPreprocessorOpts();
600 
601  // We've previously computed a preamble. Check whether we have the same
602  // preamble now that we did before, and that there's enough space in
603  // the main-file buffer within the precompiled preamble to fit the
604  // new main file.
605  if (PreambleBytes.size() != Bounds.Size ||
606  PreambleEndsAtStartOfLine != Bounds.PreambleEndsAtStartOfLine ||
607  !std::equal(PreambleBytes.begin(), PreambleBytes.end(),
608  MainFileBuffer.getBuffer().begin()))
609  return false;
610  // The preamble has not changed. We may be able to re-use the precompiled
611  // preamble.
612 
613  // Check that none of the files used by the preamble have changed.
614  // First, make a record of those files that have been overridden via
615  // remapping or unsaved_files.
616  std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
617  llvm::StringSet<> OverriddenAbsPaths; // Either by buffers or files.
618  for (const auto &R : PreprocessorOpts.RemappedFiles) {
619  llvm::vfs::Status Status;
620  if (!moveOnNoError(VFS.status(R.second), Status)) {
621  // If we can't stat the file we're remapping to, assume that something
622  // horrible happened.
623  return false;
624  }
625  // If a mapped file was previously missing, then it has changed.
626  llvm::SmallString<128> MappedPath(R.first);
627  if (!VFS.makeAbsolute(MappedPath))
628  OverriddenAbsPaths.insert(MappedPath);
629 
630  OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
631  Status.getSize(), llvm::sys::toTimeT(Status.getLastModificationTime()));
632  }
633 
634  // OverridenFileBuffers tracks only the files not found in VFS.
635  llvm::StringMap<PreambleFileHash> OverridenFileBuffers;
636  for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
637  const PrecompiledPreamble::PreambleFileHash PreambleHash =
638  PreambleFileHash::createForMemoryBuffer(RB.second->getMemBufferRef());
639  llvm::vfs::Status Status;
640  if (moveOnNoError(VFS.status(RB.first), Status))
641  OverriddenFiles[Status.getUniqueID()] = PreambleHash;
642  else
643  OverridenFileBuffers[RB.first] = PreambleHash;
644 
645  llvm::SmallString<128> MappedPath(RB.first);
646  if (!VFS.makeAbsolute(MappedPath))
647  OverriddenAbsPaths.insert(MappedPath);
648  }
649 
650  // Check whether anything has changed.
651  for (const auto &F : FilesInPreamble) {
652  auto OverridenFileBuffer = OverridenFileBuffers.find(F.first());
653  if (OverridenFileBuffer != OverridenFileBuffers.end()) {
654  // The file's buffer was remapped and the file was not found in VFS.
655  // Check whether it matches up with the previous mapping.
656  if (OverridenFileBuffer->second != F.second)
657  return false;
658  continue;
659  }
660 
661  llvm::vfs::Status Status;
662  if (!moveOnNoError(VFS.status(F.first()), Status)) {
663  // If the file's buffer is not remapped and we can't stat it,
664  // assume that something horrible happened.
665  return false;
666  }
667 
668  std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden =
669  OverriddenFiles.find(Status.getUniqueID());
670  if (Overridden != OverriddenFiles.end()) {
671  // This file was remapped; check whether the newly-mapped file
672  // matches up with the previous mapping.
673  if (Overridden->second != F.second)
674  return false;
675  continue;
676  }
677 
678  // Neither the file's buffer nor the file itself was remapped;
679  // check whether it has changed on disk.
680  if (Status.getSize() != uint64_t(F.second.Size) ||
681  llvm::sys::toTimeT(Status.getLastModificationTime()) !=
682  F.second.ModTime)
683  return false;
684  }
685  for (const auto &F : MissingFiles) {
686  // A missing file may be "provided" by an override buffer or file.
687  if (OverriddenAbsPaths.count(F.getKey()))
688  return false;
689  // If a file previously recorded as missing exists as a regular file, then
690  // consider the preamble out-of-date.
691  if (auto Status = VFS.status(F.getKey())) {
692  if (Status->isRegularFile())
693  return false;
694  }
695  }
696  return true;
697 }
698 
701  llvm::MemoryBuffer *MainFileBuffer) const {
702  PreambleBounds Bounds(PreambleBytes.size(), PreambleEndsAtStartOfLine);
703  configurePreamble(Bounds, CI, VFS, MainFileBuffer);
704 }
705 
708  llvm::MemoryBuffer *MainFileBuffer) const {
709  auto Bounds = ComputePreambleBounds(*CI.getLangOpts(), *MainFileBuffer, 0);
710  configurePreamble(Bounds, CI, VFS, MainFileBuffer);
711 }
712 
714  std::unique_ptr<PCHStorage> Storage, std::vector<char> PreambleBytes,
715  bool PreambleEndsAtStartOfLine,
716  llvm::StringMap<PreambleFileHash> FilesInPreamble,
717  llvm::StringSet<> MissingFiles)
718  : Storage(std::move(Storage)), FilesInPreamble(std::move(FilesInPreamble)),
719  MissingFiles(std::move(MissingFiles)),
720  PreambleBytes(std::move(PreambleBytes)),
721  PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {
722  assert(this->Storage != nullptr);
723 }
724 
725 PrecompiledPreamble::PreambleFileHash
726 PrecompiledPreamble::PreambleFileHash::createForFile(off_t Size,
727  time_t ModTime) {
728  PreambleFileHash Result;
729  Result.Size = Size;
730  Result.ModTime = ModTime;
731  Result.MD5 = {};
732  return Result;
733 }
734 
735 PrecompiledPreamble::PreambleFileHash
736 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
737  const llvm::MemoryBufferRef &Buffer) {
738  PreambleFileHash Result;
739  Result.Size = Buffer.getBufferSize();
740  Result.ModTime = 0;
741 
742  llvm::MD5 MD5Ctx;
743  MD5Ctx.update(Buffer.getBuffer().data());
744  MD5Ctx.final(Result.MD5);
745 
746  return Result;
747 }
748 
749 void PrecompiledPreamble::configurePreamble(
752  llvm::MemoryBuffer *MainFileBuffer) const {
753  assert(VFS);
754 
755  auto &PreprocessorOpts = CI.getPreprocessorOpts();
756 
757  // Remap main file to point to MainFileBuffer.
758  auto MainFilePath = CI.getFrontendOpts().Inputs[0].getFile();
759  PreprocessorOpts.addRemappedFile(MainFilePath, MainFileBuffer);
760 
761  // Configure ImpicitPCHInclude.
762  PreprocessorOpts.PrecompiledPreambleBytes.first = Bounds.Size;
763  PreprocessorOpts.PrecompiledPreambleBytes.second =
765  PreprocessorOpts.DisablePCHOrModuleValidation =
767 
768  // Don't bother generating the long version of the predefines buffer.
769  // The preamble is going to overwrite it anyway.
770  PreprocessorOpts.UsePredefines = false;
771 
772  setupPreambleStorage(*Storage, PreprocessorOpts, VFS);
773 }
774 
775 void PrecompiledPreamble::setupPreambleStorage(
776  const PCHStorage &Storage, PreprocessorOptions &PreprocessorOpts,
778  if (Storage.getKind() == PCHStorage::Kind::TempFile) {
779  llvm::StringRef PCHPath = Storage.filePath();
780  PreprocessorOpts.ImplicitPCHInclude = PCHPath.str();
781 
782  // Make sure we can access the PCH file even if we're using a VFS
784  llvm::vfs::getRealFileSystem();
785  if (VFS == RealFS || VFS->exists(PCHPath))
786  return;
787  auto Buf = RealFS->getBufferForFile(PCHPath);
788  if (!Buf) {
789  // We can't read the file even from RealFS, this is clearly an error,
790  // but we'll just leave the current VFS as is and let clang's code
791  // figure out what to do with missing PCH.
792  return;
793  }
794 
795  // We have a slight inconsistency here -- we're using the VFS to
796  // read files, but the PCH was generated in the real file system.
797  VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(*Buf), VFS);
798  } else {
799  assert(Storage.getKind() == PCHStorage::Kind::InMemory);
800  // For in-memory preamble, we have to provide a VFS overlay that makes it
801  // accessible.
802  StringRef PCHPath = getInMemoryPreamblePath();
803  PreprocessorOpts.ImplicitPCHInclude = std::string(PCHPath);
804 
805  auto Buf = llvm::MemoryBuffer::getMemBuffer(
806  Storage.memoryContents(), PCHPath, /*RequiresNullTerminator=*/false);
807  VFS = createVFSOverlayForPreamblePCH(PCHPath, std::move(Buf), VFS);
808  }
809 }
810 
815 std::unique_ptr<PPCallbacks> PreambleCallbacks::createPPCallbacks() {
816  return nullptr;
817 }
819 
820 static llvm::ManagedStatic<BuildPreambleErrorCategory> BuildPreambleErrCategory;
821 
823  return std::error_code(static_cast<int>(Error), *BuildPreambleErrCategory);
824 }
825 
826 const char *BuildPreambleErrorCategory::name() const noexcept {
827  return "build-preamble.error";
828 }
829 
831  switch (static_cast<BuildPreambleError>(condition)) {
833  return "Could not create temporary file for PCH";
835  return "CreateTargetInfo() return null";
837  return "BeginSourceFile() return an error";
839  return "Could not emit PCH";
841  return "Command line arguments must contain exactly one source file";
842  }
843  llvm_unreachable("unexpected BuildPreambleError");
844 }
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::PreambleCallbacks
A set of callbacks to gather useful information while building a preamble.
Definition: PrecompiledPreamble.h:206
clang::PrecompiledPreamble
A class holding a PCH and all information to check whether it is valid to reuse the PCH for the subse...
Definition: PrecompiledPreamble.h:51
clang::DeclaratorContext::File
@ File
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::PreprocessorOptions
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Definition: PreprocessorOptions.h:65
clang::ProcessWarningOptions
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:44
clang::FrontendOptions::ProgramAction
frontend::ActionKind ProgramAction
The frontend action to perform.
Definition: FrontendOptions.h:445
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::PPCallbacks
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition: PPCallbacks.h:35
clang::PrecompiledPreamble::PrecompiledPreamble
PrecompiledPreamble(PrecompiledPreamble &&)
clang::PrecompiledPreamble::PCHStorage::inMemory
static std::unique_ptr< PCHStorage > inMemory(std::shared_ptr< PCHBuffer > Buf)
Definition: PrecompiledPreamble.cpp:354
clang::CompilerInstance::getLangOpts
LangOptions & getLangOpts()
Definition: CompilerInstance.h:299
Filename
StringRef Filename
Definition: Format.cpp:2715
clang::PreambleCallbacks::createPPCallbacks
virtual std::unique_ptr< PPCallbacks > createPPCallbacks()
Creates wrapper class for PPCallbacks so we can also process information about includes that are insi...
Definition: PrecompiledPreamble.cpp:815
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::PrecompiledPreamble::PCHStorage
Definition: PrecompiledPreamble.cpp:346
clang::PreambleCallbacks::HandleTopLevelDecl
virtual void HandleTopLevelDecl(DeclGroupRef DG)
Called for each TopLevelDecl.
Definition: PrecompiledPreamble.cpp:814
clang::ModuleFileExtension
An abstract superclass that describes a custom extension to the module/precompiled header file format...
Definition: ModuleFileExtension.h:66
BuildPreambleErrCategory
static llvm::ManagedStatic< BuildPreambleErrorCategory > BuildPreambleErrCategory
Definition: PrecompiledPreamble.cpp:820
llvm::Optional< FileEntryRef >
clang::PrecompiledPreamble::PCHStorage::filePath
llvm::StringRef filePath() const
Definition: PrecompiledPreamble.cpp:368
clang::SrcMgr::CharacteristicKind
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:79
clang::DiagnosticsEngine::Reset
void Reset(bool soft=false)
Reset the state of the diagnostic object to its initial configuration.
Definition: Diagnostic.cpp:134
ASTWriter.h
clang::make_error_code
std::error_code make_error_code(BuildPreambleError Error)
Definition: PrecompiledPreamble.cpp:822
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
clang::CommentHandler
Abstract base class that describes a handler that will receive source ranges for each of the comments...
Definition: Preprocessor.h:2696
clang::InputKind::Source
@ Source
Definition: FrontendOptions.h:159
CompilerInvocation.h
clang::PrecompiledPreamble::getSize
std::size_t getSize() const
Returns the size, in bytes, that preamble takes on disk or in memory.
Definition: PrecompiledPreamble.cpp:571
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:637
clang::FrontendOptions::Inputs
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
Definition: FrontendOptions.h:426
Preprocessor.h
clang::HeaderSearch::angled_dir_begin
ConstSearchDirIterator angled_dir_begin() const
Definition: HeaderSearch.h:830
clang::HeaderSearch
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:223
clang::TU_Prefix
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:920
clang::PrecompiledPreamble::getBounds
PreambleBounds getBounds() const
PreambleBounds used to build the preamble.
Definition: PrecompiledPreamble.cpp:567
clang::frontend::GeneratePCH
@ GeneratePCH
Generate pre-compiled header.
Definition: FrontendOptions.h:94
clang::BuildPreambleErrorCategory::message
std::string message(int condition) const override
Definition: PrecompiledPreamble.cpp:830
clang::PrecompiledPreamble::~PrecompiledPreamble
~PrecompiledPreamble()
clang::GeneratePCHAction::CreateOutputFile
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.
Definition: FrontendActions.cpp:162
size_t
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c-base.h:118
clang::HeaderSearch::search_dir_end
SearchDirIterator search_dir_end()
Definition: HeaderSearch.h:810
clang::Module
Describes a module or submodule.
Definition: Module.h:98
clang::CompilerInvocationValueBase::getFrontendOpts
FrontendOptions & getFrontendOpts()
Definition: CompilerInvocation.h:176
FrontendOptions.h
clang::FrontendOptions::OutputFile
std::string OutputFile
The output file, if any.
Definition: FrontendOptions.h:433
clang::DirectoryEntry
Cached information about one directory (either on disk or in the virtual file system).
Definition: DirectoryEntry.h:36
hlsl::uint64_t
unsigned long uint64_t
Definition: hlsl_basic_types.h:25
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
clang::SourceManager::getMainFileID
FileID getMainFileID() const
Returns the FileID of the main source file.
Definition: SourceManager.h:851
clang::FrontendOptions
FrontendOptions - Options for controlling the behavior of the frontend.
Definition: FrontendOptions.h:265
PrecompiledPreamble.h
clang::PrecompiledPreamble::AddImplicitPreamble
void AddImplicitPreamble(CompilerInvocation &CI, IntrusiveRefCntPtr< llvm::vfs::FileSystem > &VFS, llvm::MemoryBuffer *MainFileBuffer) const
Changes options inside CI to use PCH from this preamble.
Definition: PrecompiledPreamble.cpp:699
llvm::SmallString
Definition: LLVM.h:37
clang::CompilerInvocationRefBase::getLangOpts
LangOptions * getLangOpts()
Definition: CompilerInvocation.h:104
clang::PreambleBounds
Describes the bounds (start, size) of the preamble and a flag required by PreprocessorOptions::Precom...
Definition: Lexer.h:60
clang::PreambleBounds::Size
unsigned Size
Size of the preamble in bytes.
Definition: Lexer.h:62
clang::CompilerInstance::getPreprocessor
Preprocessor & getPreprocessor() const
Return the current preprocessor.
Definition: CompilerInstance.h:442
clang::PreambleCallbacks::getCommentHandler
virtual CommentHandler * getCommentHandler()
The returned CommentHandler will be added to the preprocessor if not null.
Definition: PrecompiledPreamble.cpp:818
clang::ASTWriter
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:85
clang::DependencyCollector
An interface for collecting the dependencies of a compilation.
Definition: Utils.h:61
clang::PrecompiledPreamble::OverridePreamble
void OverridePreamble(CompilerInvocation &CI, IntrusiveRefCntPtr< llvm::vfs::FileSystem > &VFS, llvm::MemoryBuffer *MainFileBuffer) const
Configure CI to use this preamble.
Definition: PrecompiledPreamble.cpp:706
clang::CompilerInstance
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Definition: CompilerInstance.h:72
clang::HeaderSearch::search_dir_begin
SearchDirIterator search_dir_begin()
Definition: HeaderSearch.h:809
clang::FileEntry
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:366
clang::DisableValidationForModuleKind::PCH
@ PCH
Disable validation for a precompiled header and the modules it depends on.
clang::PrecompiledPreamble::PCHStorage::Kind
Kind
Definition: PrecompiledPreamble.cpp:360
clang::BuildPreambleErrorCategory::name
const char * name() const noexcept override
Definition: PrecompiledPreamble.cpp:826
clang::CompilerInstance::getModuleCache
InMemoryModuleCache & getModuleCache() const
Definition: CompilerInstance.h:817
clang::PrecompiledPreamble::PCHStorage::getKind
Kind getKind() const
Definition: PrecompiledPreamble.cpp:361
clang::PreambleCallbacks::AfterExecute
virtual void AfterExecute(CompilerInstance &CI)
Called after FrontendAction::Execute(), but before FrontendAction::EndSourceFile().
Definition: PrecompiledPreamble.cpp:812
clang::transformer::remove
ASTEdit remove(RangeSelector S)
Removes the source selected by S.
Definition: RewriteRule.cpp:163
clang::BuildPreambleError::BadInputs
@ BadInputs
clang::CompilerInvocationRefBase::getPreprocessorOpts
PreprocessorOptions & getPreprocessorOpts()
Definition: CompilerInvocation.h:126
moveOnNoError
static bool moveOnNoError(llvm::ErrorOr< T > Val, T &Output)
Definition: ASTUnit.cpp:150
clang::PreprocessorOptions::GeneratePreamble
bool GeneratePreamble
True indicates that a preamble is being generated.
Definition: PreprocessorOptions.h:134
clang::InclusionDirective
Record the location of an inclusion directive, such as an #include or #import statement.
Definition: PreprocessingRecord.h:207
clang::PrecompiledPreamble::PCHStorage::file
static std::unique_ptr< PCHStorage > file(std::unique_ptr< TempPCHFile > File)
Definition: PrecompiledPreamble.cpp:348
clang::PreprocessorOptions::RetainRemappedFileBuffers
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
Definition: PreprocessorOptions.h:172
clang::serialized_diags::create
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
Definition: SerializedDiagnosticPrinter.cpp:301
clang::GeneratePCHAction::ComputeASTConsumerArguments
static bool ComputeASTConsumerArguments(CompilerInstance &CI, std::string &Sysroot)
Compute the AST consumer arguments that will be used to create the PCHGenerator instance returned by ...
Definition: FrontendActions.cpp:150
LangStandard.h
clang::PrecompiledPreamble::PCHStorage::memoryContents
llvm::StringRef memoryContents() const
Definition: PrecompiledPreamble.cpp:372
clang::BuildPreambleError::BeginSourceFileFailed
@ BeginSourceFileFailed
llvm::ArrayRef
Definition: LLVM.h:34
clang::Language::LLVM_IR
@ LLVM_IR
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
Lexer.h
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::PreprocessorOptions::RemappedFileBuffers
std::vector< std::pair< std::string, llvm::MemoryBuffer * > > RemappedFileBuffers
The set of file-to-buffer remappings, which take existing files on the system (the first part of each...
Definition: PreprocessorOptions.h:164
clang::BuildPreambleError
BuildPreambleError
Definition: PrecompiledPreamble.h:237
HeaderSearch.h
clang::DeclGroupRef
Definition: DeclGroup.h:51
clang::PreambleCallbacks::AfterPCHEmitted
virtual void AfterPCHEmitted(ASTWriter &Writer)
Called after PCH has been emitted.
Definition: PrecompiledPreamble.cpp:813
clang::CharSourceRange
Represents a character-granular source range.
Definition: SourceLocation.h:253
clang::PreprocessorOptions::PrecompiledPreambleBytes
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Definition: PreprocessorOptions.h:126
FrontendActions.h
clang::PCHBuffer
Definition: PCHContainerOperations.h:27
clang::PCHGenerator::HandleTranslationUnit
void HandleTranslationUnit(ASTContext &Ctx) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
Definition: GeneratePCH.cpp:41
clang::createVFSFromCompilerInvocation
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
Definition: CompilerInvocation.cpp:4732
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:126
clang::PreprocessorOptions::RemappedFiles
std::vector< std::pair< std::string, std::string > > RemappedFiles
The set of file remappings, which take existing files on the system (the first part of each pair) and...
Definition: PreprocessorOptions.h:159
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:81
clang::PrecompiledPreamble::operator=
PrecompiledPreamble & operator=(PrecompiledPreamble &&)
std
Definition: Format.h:4477
clang::BuildPreambleError::CouldntEmitPCH
@ CouldntEmitPCH
clang::TranslationUnitKind
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:914
clang::PrecompiledPreamble::PCHStorage::shrink
void shrink()
Definition: PrecompiledPreamble.cpp:380
clang::SourceManager::getMemoryBufferForFileOrFake
llvm::MemoryBufferRef getMemoryBufferForFileOrFake(const FileEntry *File)
Retrieve the memory buffer associated with the given file.
Definition: SourceManager.h:949
clang
Definition: CalledOnceCheck.h:17
clang::FileManager
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
clang::PreambleBounds::PreambleEndsAtStartOfLine
bool PreambleEndsAtStartOfLine
Whether the preamble ends at the start of a new line.
Definition: Lexer.h:68
clang::BuildPreambleError::CouldntCreateTargetInfo
@ CouldntCreateTargetInfo
clang::CompilerInvocation
Helper class for holding the data necessary to invoke the compiler.
Definition: CompilerInvocation.h:193
clang::SourceManager::getFileEntryForID
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
Definition: SourceManager.h:1045
clang::InMemoryModuleCache
In-memory cache for modules.
Definition: InMemoryModuleCache.h:29
clang::FrontendAction::BeginSourceFileAction
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
Definition: FrontendAction.h:85
clang::PrecompiledPreamble::CanReuse
bool CanReuse(const CompilerInvocation &Invocation, const llvm::MemoryBufferRef &MainFileBuffer, PreambleBounds Bounds, llvm::vfs::FileSystem &VFS) const
Check whether PrecompiledPreamble can be reused for the new contents(MainFileBuffer) of the main file...
Definition: PrecompiledPreamble.cpp:588
clang::SourceManager::getFileManager
FileManager & getFileManager() const
Definition: SourceManager.h:817
clang::FileManager::getFile
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Definition: FileManager.cpp:197
CompilerInstance.h
clang::PCHGenerator
AST and semantic-analysis consumer that generates a precompiled header from the parsed source code.
Definition: ASTWriter.h:791
clang::CompilerInstance::getFrontendOpts
FrontendOptions & getFrontendOpts()
Definition: CompilerInstance.h:282
clang::FrontendOptions::RelocatablePCH
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
Definition: FrontendOptions.h:272
clang::Lexer::ComputePreamble
static PreambleBounds ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
Definition: Lexer.cpp:589
clang::ASTFrontendAction
Abstract base class to use for AST consumer-based frontend actions.
Definition: FrontendAction.h:243
clang::PreambleCallbacks::BeforeExecute
virtual void BeforeExecute(CompilerInstance &CI)
Called before FrontendAction::Execute.
Definition: PrecompiledPreamble.cpp:811
FileManager.h
true
#define true
Definition: stdbool.h:21
clang::ComputePreambleBounds
PreambleBounds ComputePreambleBounds(const LangOptions &LangOpts, const llvm::MemoryBufferRef &Buffer, unsigned MaxLines)
Runs lexer to compute suggested preamble bounds.
Definition: PrecompiledPreamble.cpp:340
clang::PreprocessorOptions::addRemappedFile
void addRemappedFile(StringRef From, StringRef To)
Definition: PreprocessorOptions.h:236
PreprocessorOptions.h
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:129
SM
#define SM(sm)
Definition: Cuda.cpp:79
clang::PrecompiledPreamble::Build
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.
Definition: PrecompiledPreamble.cpp:400
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem >
clang::PreprocessorOptions::ImplicitPCHInclude
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
Definition: PreprocessorOptions.h:97
clang::BuildPreambleError::CouldntCreateTempFile
@ CouldntCreateTempFile