clang  19.0.0git
CompilerInstance.cpp
Go to the documentation of this file.
1 //===--- CompilerInstance.cpp ---------------------------------------------===//
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 
10 #include "clang/AST/ASTConsumer.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/Diagnostic.h"
19 #include "clang/Basic/Stack.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Basic/Version.h"
22 #include "clang/Config/config.h"
32 #include "clang/Frontend/Utils.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Sema/Sema.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/ScopeExit.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Config/llvm-config.h"
46 #include "llvm/Support/BuryPointer.h"
47 #include "llvm/Support/CrashRecoveryContext.h"
48 #include "llvm/Support/Errc.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/LockFileManager.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/Path.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/Signals.h"
55 #include "llvm/Support/TimeProfiler.h"
56 #include "llvm/Support/Timer.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/TargetParser/Host.h"
59 #include <optional>
60 #include <time.h>
61 #include <utility>
62 
63 using namespace clang;
64 
65 CompilerInstance::CompilerInstance(
66  std::shared_ptr<PCHContainerOperations> PCHContainerOps,
67  InMemoryModuleCache *SharedModuleCache)
68  : ModuleLoader(/* BuildingModule = */ SharedModuleCache),
69  Invocation(new CompilerInvocation()),
70  ModuleCache(SharedModuleCache ? SharedModuleCache
71  : new InMemoryModuleCache),
72  ThePCHContainerOperations(std::move(PCHContainerOps)) {}
73 
75  assert(OutputFiles.empty() && "Still output files in flight?");
76 }
77 
79  std::shared_ptr<CompilerInvocation> Value) {
80  Invocation = std::move(Value);
81 }
82 
84  return (BuildGlobalModuleIndex ||
85  (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
86  getFrontendOpts().GenerateGlobalModuleIndex)) &&
87  !DisableGeneratingGlobalModuleIndex;
88 }
89 
91  Diagnostics = Value;
92 }
93 
95  OwnedVerboseOutputStream.reset();
96  VerboseOutputStream = &Value;
97 }
98 
99 void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
100  OwnedVerboseOutputStream.swap(Value);
101  VerboseOutputStream = OwnedVerboseOutputStream.get();
102 }
103 
106 
108  // Create the target instance.
110  getInvocation().TargetOpts));
111  if (!hasTarget())
112  return false;
113 
114  // Check whether AuxTarget exists, if not, then create TargetInfo for the
115  // other side of CUDA/OpenMP/SYCL compilation.
116  if (!getAuxTarget() &&
117  (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
118  getLangOpts().isSYCL()) &&
119  !getFrontendOpts().AuxTriple.empty()) {
120  auto TO = std::make_shared<TargetOptions>();
121  TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
122  if (getFrontendOpts().AuxTargetCPU)
123  TO->CPU = *getFrontendOpts().AuxTargetCPU;
124  if (getFrontendOpts().AuxTargetFeatures)
125  TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
126  TO->HostTriple = getTarget().getTriple().str();
128  }
129 
130  if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
131  if (getLangOpts().RoundingMath) {
132  getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
133  getLangOpts().RoundingMath = false;
134  }
135  auto FPExc = getLangOpts().getFPExceptionMode();
136  if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
137  getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
138  getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
139  }
140  // FIXME: can we disable FEnvAccess?
141  }
142 
143  // We should do it here because target knows nothing about
144  // language options when it's being created.
145  if (getLangOpts().OpenCL &&
146  !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
147  return false;
148 
149  // Inform the target of the language options.
150  // FIXME: We shouldn't need to do this, the target should be immutable once
151  // created. This complexity should be lifted elsewhere.
153 
154  if (auto *Aux = getAuxTarget()) {
155  Aux->adjust(getDiagnostics(), getLangOpts());
156  getTarget().setAuxTarget(Aux);
157  }
158 
159  return true;
160 }
161 
162 llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const {
164 }
165 
167  FileMgr = Value;
168 }
169 
171  SourceMgr = Value;
172 }
173 
174 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
175  PP = std::move(Value);
176 }
177 
179  Context = Value;
180 
181  if (Context && Consumer)
183 }
184 
186  TheSema.reset(S);
187 }
188 
189 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
190  Consumer = std::move(Value);
191 
192  if (Context && Consumer)
194 }
195 
197  CompletionConsumer.reset(Value);
198 }
199 
200 std::unique_ptr<Sema> CompilerInstance::takeSema() {
201  return std::move(TheSema);
202 }
203 
205  return TheASTReader;
206 }
208  assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
209  "Expected ASTReader to use the same PCM cache");
210  TheASTReader = std::move(Reader);
211 }
212 
213 std::shared_ptr<ModuleDependencyCollector>
215  return ModuleDepCollector;
216 }
217 
219  std::shared_ptr<ModuleDependencyCollector> Collector) {
220  ModuleDepCollector = std::move(Collector);
221 }
222 
223 static void collectHeaderMaps(const HeaderSearch &HS,
224  std::shared_ptr<ModuleDependencyCollector> MDC) {
225  SmallVector<std::string, 4> HeaderMapFileNames;
226  HS.getHeaderMapFileNames(HeaderMapFileNames);
227  for (auto &Name : HeaderMapFileNames)
228  MDC->addFile(Name);
229 }
230 
232  std::shared_ptr<ModuleDependencyCollector> MDC) {
233  const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
234  if (PPOpts.ImplicitPCHInclude.empty())
235  return;
236 
237  StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
238  FileManager &FileMgr = CI.getFileManager();
239  auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
240  if (!PCHDir) {
241  MDC->addFile(PCHInclude);
242  return;
243  }
244 
245  std::error_code EC;
246  SmallString<128> DirNative;
247  llvm::sys::path::native(PCHDir->getName(), DirNative);
248  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
250  for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
251  Dir != DirEnd && !EC; Dir.increment(EC)) {
252  // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
253  // used here since we're not interested in validating the PCH at this time,
254  // but only to check whether this is a file containing an AST.
256  Dir->path(), FileMgr, CI.getModuleCache(),
258  /*FindModuleFileExtensions=*/false, Validator,
259  /*ValidateDiagnosticOptions=*/false))
260  MDC->addFile(Dir->path());
261  }
262 }
263 
265  std::shared_ptr<ModuleDependencyCollector> MDC) {
266  if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
267  return;
268 
269  // Collect all VFS found.
271  for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
272  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
273  llvm::MemoryBuffer::getFile(VFSFile);
274  if (!Buffer)
275  return;
276  llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
277  /*DiagHandler*/ nullptr, VFSFile, VFSEntries);
278  }
279 
280  for (auto &E : VFSEntries)
281  MDC->addFile(E.VPath, E.RPath);
282 }
283 
284 // Diagnostics
285 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
286  const CodeGenOptions *CodeGenOpts,
287  DiagnosticsEngine &Diags) {
288  std::error_code EC;
289  std::unique_ptr<raw_ostream> StreamOwner;
290  raw_ostream *OS = &llvm::errs();
291  if (DiagOpts->DiagnosticLogFile != "-") {
292  // Create the output stream.
293  auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
294  DiagOpts->DiagnosticLogFile, EC,
295  llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
296  if (EC) {
297  Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
298  << DiagOpts->DiagnosticLogFile << EC.message();
299  } else {
300  FileOS->SetUnbuffered();
301  OS = FileOS.get();
302  StreamOwner = std::move(FileOS);
303  }
304  }
305 
306  // Chain in the diagnostic client which will log the diagnostics.
307  auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
308  std::move(StreamOwner));
309  if (CodeGenOpts)
310  Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
311  if (Diags.ownsClient()) {
312  Diags.setClient(
313  new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
314  } else {
315  Diags.setClient(
316  new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
317  }
318 }
319 
321  DiagnosticsEngine &Diags,
322  StringRef OutputFile) {
323  auto SerializedConsumer =
324  clang::serialized_diags::create(OutputFile, DiagOpts);
325 
326  if (Diags.ownsClient()) {
328  Diags.takeClient(), std::move(SerializedConsumer)));
329  } else {
331  Diags.getClient(), std::move(SerializedConsumer)));
332  }
333 }
334 
336  bool ShouldOwnClient) {
337  Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
338  ShouldOwnClient, &getCodeGenOpts());
339 }
340 
343  DiagnosticConsumer *Client,
344  bool ShouldOwnClient,
345  const CodeGenOptions *CodeGenOpts) {
348  Diags(new DiagnosticsEngine(DiagID, Opts));
349 
350  // Create the diagnostic client for reporting errors or for
351  // implementing -verify.
352  if (Client) {
353  Diags->setClient(Client, ShouldOwnClient);
354  } else if (Opts->getFormat() == DiagnosticOptions::SARIF) {
355  Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
356  } else
357  Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
358 
359  // Chain in -verify checker, if requested.
360  if (Opts->VerifyDiagnostics)
361  Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
362 
363  // Chain in -diagnostic-log-file dumper, if requested.
364  if (!Opts->DiagnosticLogFile.empty())
365  SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
366 
367  if (!Opts->DiagnosticSerializationFile.empty())
368  SetupSerializedDiagnostics(Opts, *Diags,
370 
371  // Configure our handling of diagnostics.
372  ProcessWarningOptions(*Diags, *Opts);
373 
374  return Diags;
375 }
376 
377 // File Manager
378 
381  if (!VFS)
382  VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
384  getDiagnostics());
385  assert(VFS && "FileManager has no VFS?");
386  FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
387  return FileMgr.get();
388 }
389 
390 // Source Manager
391 
393  SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
394 }
395 
396 // Initialize the remapping of files to alternative contents, e.g.,
397 // those specified through other files.
399  SourceManager &SourceMgr,
400  FileManager &FileMgr,
401  const PreprocessorOptions &InitOpts) {
402  // Remap files in the source manager (with buffers).
403  for (const auto &RB : InitOpts.RemappedFileBuffers) {
404  // Create the file entry for the file that we're mapping from.
405  FileEntryRef FromFile =
406  FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
407 
408  // Override the contents of the "from" file with the contents of the
409  // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
410  // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
411  // to the SourceManager.
412  if (InitOpts.RetainRemappedFileBuffers)
413  SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
414  else
415  SourceMgr.overrideFileContents(
416  FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
417  }
418 
419  // Remap files in the source manager (with other files).
420  for (const auto &RF : InitOpts.RemappedFiles) {
421  // Find the file that we're mapping to.
422  OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
423  if (!ToFile) {
424  Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
425  continue;
426  }
427 
428  // Create the file entry for the file that we're mapping from.
429  const FileEntry *FromFile =
430  FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
431  if (!FromFile) {
432  Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
433  continue;
434  }
435 
436  // Override the contents of the "from" file with the contents of
437  // the "to" file.
438  SourceMgr.overrideFileContents(FromFile, *ToFile);
439  }
440 
443 }
444 
445 // Preprocessor
446 
448  const PreprocessorOptions &PPOpts = getPreprocessorOpts();
449 
450  // The AST reader holds a reference to the old preprocessor (if any).
451  TheASTReader.reset();
452 
453  // Create the Preprocessor.
454  HeaderSearch *HeaderInfo =
457  PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
459  getSourceManager(), *HeaderInfo, *this,
460  /*IdentifierInfoLookup=*/nullptr,
461  /*OwnsHeaderSearch=*/true, TUKind);
463  PP->Initialize(getTarget(), getAuxTarget());
464 
465  if (PPOpts.DetailedRecord)
466  PP->createPreprocessingRecord();
467 
468  // Apply remappings to the source manager.
469  InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
470  PP->getFileManager(), PPOpts);
471 
472  // Predefine macros and configure the preprocessor.
475 
476  // Initialize the header search object. In CUDA compilations, we use the aux
477  // triple (the host triple) to initialize our header search, since we need to
478  // find the host headers in order to compile the CUDA code.
479  const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
480  if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
481  PP->getAuxTargetInfo())
482  HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
483 
484  ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
485  PP->getLangOpts(), *HeaderSearchTriple);
486 
487  PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
488 
489  if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
490  std::string ModuleHash = getInvocation().getModuleHash();
491  PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
492  PP->getHeaderSearchInfo().setModuleCachePath(
493  getSpecificModuleCachePath(ModuleHash));
494  }
495 
496  // Handle generating dependencies, if requested.
498  if (!DepOpts.OutputFile.empty())
499  addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
500  if (!DepOpts.DOTOutputFile.empty())
502  getHeaderSearchOpts().Sysroot);
503 
504  // If we don't have a collector, but we are collecting module dependencies,
505  // then we're the top level compiler instance and need to create one.
506  if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
507  ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
508  DepOpts.ModuleDependencyOutputDir);
509  }
510 
511  // If there is a module dep collector, register with other dep collectors
512  // and also (a) collect header maps and (b) TODO: input vfs overlay files.
513  if (ModuleDepCollector) {
514  addDependencyCollector(ModuleDepCollector);
515  collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
516  collectIncludePCH(*this, ModuleDepCollector);
517  collectVFSEntries(*this, ModuleDepCollector);
518  }
519 
520  for (auto &Listener : DependencyCollectors)
521  Listener->attachToPreprocessor(*PP);
522 
523  // Handle generating header include information, if requested.
524  if (DepOpts.ShowHeaderIncludes)
525  AttachHeaderIncludeGen(*PP, DepOpts);
526  if (!DepOpts.HeaderIncludeOutputFile.empty()) {
527  StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
528  if (OutputPath == "-")
529  OutputPath = "";
530  AttachHeaderIncludeGen(*PP, DepOpts,
531  /*ShowAllHeaders=*/true, OutputPath,
532  /*ShowDepth=*/false);
533  }
534 
536  AttachHeaderIncludeGen(*PP, DepOpts,
537  /*ShowAllHeaders=*/true, /*OutputPath=*/"",
538  /*ShowDepth=*/true, /*MSStyle=*/true);
539  }
540 }
541 
542 std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
543  // Set up the module path, including the hash for the module-creation options.
544  SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
545  if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
546  llvm::sys::path::append(SpecificModuleCache, ModuleHash);
547  return std::string(SpecificModuleCache);
548 }
549 
550 // ASTContext
551 
554  auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
556  PP.getBuiltinInfo(), PP.TUKind);
557  Context->InitBuiltinTypes(getTarget(), getAuxTarget());
558  setASTContext(Context);
559 }
560 
561 // ExternalASTSource
562 
563 namespace {
564 // Helper to recursively read the module names for all modules we're adding.
565 // We mark these as known and redirect any attempt to load that module to
566 // the files we were handed.
567 struct ReadModuleNames : ASTReaderListener {
568  Preprocessor &PP;
569  llvm::SmallVector<std::string, 8> LoadedModules;
570 
571  ReadModuleNames(Preprocessor &PP) : PP(PP) {}
572 
573  void ReadModuleName(StringRef ModuleName) override {
574  // Keep the module name as a string for now. It's not safe to create a new
575  // IdentifierInfo from an ASTReader callback.
576  LoadedModules.push_back(ModuleName.str());
577  }
578 
579  void registerAll() {
581  for (const std::string &LoadedModule : LoadedModules)
582  MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
583  MM.findModule(LoadedModule));
584  LoadedModules.clear();
585  }
586 
587  void markAllUnavailable() {
588  for (const std::string &LoadedModule : LoadedModules) {
590  LoadedModule)) {
591  M->HasIncompatibleModuleFile = true;
592 
593  // Mark module as available if the only reason it was unavailable
594  // was missing headers.
596  Stack.push_back(M);
597  while (!Stack.empty()) {
598  Module *Current = Stack.pop_back_val();
599  if (Current->IsUnimportable) continue;
600  Current->IsAvailable = true;
601  auto SubmodulesRange = Current->submodules();
602  Stack.insert(Stack.end(), SubmodulesRange.begin(),
603  SubmodulesRange.end());
604  }
605  }
606  }
607  LoadedModules.clear();
608  }
609 };
610 } // namespace
611 
613  StringRef Path, DisableValidationForModuleKind DisableValidation,
614  bool AllowPCHWithCompilerErrors, void *DeserializationListener,
615  bool OwnDeserializationListener) {
617  TheASTReader = createPCHExternalASTSource(
618  Path, getHeaderSearchOpts().Sysroot, DisableValidation,
619  AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
621  getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
622  DeserializationListener, OwnDeserializationListener, Preamble,
623  getFrontendOpts().UseGlobalModuleIndex);
624 }
625 
627  StringRef Path, StringRef Sysroot,
628  DisableValidationForModuleKind DisableValidation,
629  bool AllowPCHWithCompilerErrors, Preprocessor &PP,
630  InMemoryModuleCache &ModuleCache, ASTContext &Context,
631  const PCHContainerReader &PCHContainerRdr,
632  ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
633  ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
634  void *DeserializationListener, bool OwnDeserializationListener,
635  bool Preamble, bool UseGlobalModuleIndex) {
637 
639  PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
640  Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
641  AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
643  UseGlobalModuleIndex));
644 
645  // We need the external source to be set up before we read the AST, because
646  // eagerly-deserialized declarations may use it.
647  Context.setExternalSource(Reader.get());
648 
649  Reader->setDeserializationListener(
650  static_cast<ASTDeserializationListener *>(DeserializationListener),
651  /*TakeOwnership=*/OwnDeserializationListener);
652 
653  for (auto &Listener : DependencyCollectors)
654  Listener->attachToASTReader(*Reader);
655 
656  auto Listener = std::make_unique<ReadModuleNames>(PP);
657  auto &ListenerRef = *Listener;
658  ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
659  std::move(Listener));
660 
661  switch (Reader->ReadAST(Path,
664  SourceLocation(),
666  case ASTReader::Success:
667  // Set the predefines buffer as suggested by the PCH reader. Typically, the
668  // predefines buffer will be empty.
669  PP.setPredefines(Reader->getSuggestedPredefines());
670  ListenerRef.registerAll();
671  return Reader;
672 
673  case ASTReader::Failure:
674  // Unrecoverable failure: don't even try to process the input file.
675  break;
676 
677  case ASTReader::Missing:
682  // No suitable PCH file could be found. Return an error.
683  break;
684  }
685 
686  ListenerRef.markAllUnavailable();
687  Context.setExternalSource(nullptr);
688  return nullptr;
689 }
690 
691 // Code Completion
692 
694  StringRef Filename,
695  unsigned Line,
696  unsigned Column) {
697  // Tell the source manager to chop off the given file at a specific
698  // line and column.
699  auto Entry = PP.getFileManager().getOptionalFileRef(Filename);
700  if (!Entry) {
701  PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
702  << Filename;
703  return true;
704  }
705 
706  // Truncate the named file at the given line/column.
707  PP.SetCodeCompletionPoint(*Entry, Line, Column);
708  return false;
709 }
710 
713  if (!CompletionConsumer) {
715  getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
716  getFrontendOpts().CodeCompleteOpts, llvm::outs()));
717  return;
718  } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
719  Loc.Line, Loc.Column)) {
720  setCodeCompletionConsumer(nullptr);
721  return;
722  }
723 }
724 
726  FrontendTimerGroup.reset(
727  new llvm::TimerGroup("frontend", "Clang front-end time report"));
728  FrontendTimer.reset(
729  new llvm::Timer("frontend", "Clang front-end timer",
730  *FrontendTimerGroup));
731 }
732 
735  StringRef Filename,
736  unsigned Line,
737  unsigned Column,
738  const CodeCompleteOptions &Opts,
739  raw_ostream &OS) {
740  if (EnableCodeCompletion(PP, Filename, Line, Column))
741  return nullptr;
742 
743  // Set up the creation routine for code-completion.
744  return new PrintingCodeCompleteConsumer(Opts, OS);
745 }
746 
748  CodeCompleteConsumer *CompletionConsumer) {
749  TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
750  TUKind, CompletionConsumer));
751 
752  // Set up API notes.
753  TheSema->APINotes.setSwiftVersion(getAPINotesOpts().SwiftVersion);
754 
755  // Attach the external sema source if there is any.
756  if (ExternalSemaSrc) {
757  TheSema->addExternalSource(ExternalSemaSrc.get());
758  ExternalSemaSrc->InitializeSema(*TheSema);
759  }
760 
761  // If we're building a module and are supposed to load API notes,
762  // notify the API notes manager.
763  if (auto *currentModule = getPreprocessor().getCurrentModule()) {
764  (void)TheSema->APINotes.loadCurrentModuleAPINotes(
765  currentModule, getLangOpts().APINotesModules,
767  }
768 }
769 
770 // Output Files
771 
772 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
773  // The ASTConsumer can own streams that write to the output files.
774  assert(!hasASTConsumer() && "ASTConsumer should be reset");
775  // Ignore errors that occur when trying to discard the temp file.
776  for (OutputFile &OF : OutputFiles) {
777  if (EraseFiles) {
778  if (OF.File)
779  consumeError(OF.File->discard());
780  if (!OF.Filename.empty())
781  llvm::sys::fs::remove(OF.Filename);
782  continue;
783  }
784 
785  if (!OF.File)
786  continue;
787 
788  if (OF.File->TmpName.empty()) {
789  consumeError(OF.File->discard());
790  continue;
791  }
792 
793  llvm::Error E = OF.File->keep(OF.Filename);
794  if (!E)
795  continue;
796 
797  getDiagnostics().Report(diag::err_unable_to_rename_temp)
798  << OF.File->TmpName << OF.Filename << std::move(E);
799 
800  llvm::sys::fs::remove(OF.File->TmpName);
801  }
802  OutputFiles.clear();
803  if (DeleteBuiltModules) {
804  for (auto &Module : BuiltModules)
806  BuiltModules.clear();
807  }
808 }
809 
810 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
811  bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
812  bool CreateMissingDirectories, bool ForceUseTemporary) {
813  StringRef OutputPath = getFrontendOpts().OutputFile;
814  std::optional<SmallString<128>> PathStorage;
815  if (OutputPath.empty()) {
816  if (InFile == "-" || Extension.empty()) {
817  OutputPath = "-";
818  } else {
819  PathStorage.emplace(InFile);
820  llvm::sys::path::replace_extension(*PathStorage, Extension);
821  OutputPath = *PathStorage;
822  }
823  }
824 
825  return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
826  getFrontendOpts().UseTemporary || ForceUseTemporary,
827  CreateMissingDirectories);
828 }
829 
830 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
831  return std::make_unique<llvm::raw_null_ostream>();
832 }
833 
834 std::unique_ptr<raw_pwrite_stream>
835 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
836  bool RemoveFileOnSignal, bool UseTemporary,
837  bool CreateMissingDirectories) {
839  createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
840  CreateMissingDirectories);
841  if (OS)
842  return std::move(*OS);
843  getDiagnostics().Report(diag::err_fe_unable_to_open_output)
844  << OutputPath << errorToErrorCode(OS.takeError()).message();
845  return nullptr;
846 }
847 
849 CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
850  bool RemoveFileOnSignal,
851  bool UseTemporary,
852  bool CreateMissingDirectories) {
853  assert((!CreateMissingDirectories || UseTemporary) &&
854  "CreateMissingDirectories is only allowed when using temporary files");
855 
856  // If '-working-directory' was passed, the output filename should be
857  // relative to that.
858  std::optional<SmallString<128>> AbsPath;
859  if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
860  assert(hasFileManager() &&
861  "File Manager is required to fix up relative path.\n");
862 
863  AbsPath.emplace(OutputPath);
864  FileMgr->FixupRelativePath(*AbsPath);
865  OutputPath = *AbsPath;
866  }
867 
868  std::unique_ptr<llvm::raw_fd_ostream> OS;
869  std::optional<StringRef> OSFile;
870 
871  if (UseTemporary) {
872  if (OutputPath == "-")
873  UseTemporary = false;
874  else {
875  llvm::sys::fs::file_status Status;
876  llvm::sys::fs::status(OutputPath, Status);
877  if (llvm::sys::fs::exists(Status)) {
878  // Fail early if we can't write to the final destination.
879  if (!llvm::sys::fs::can_write(OutputPath))
880  return llvm::errorCodeToError(
881  make_error_code(llvm::errc::operation_not_permitted));
882 
883  // Don't use a temporary if the output is a special file. This handles
884  // things like '-o /dev/null'
885  if (!llvm::sys::fs::is_regular_file(Status))
886  UseTemporary = false;
887  }
888  }
889  }
890 
891  std::optional<llvm::sys::fs::TempFile> Temp;
892  if (UseTemporary) {
893  // Create a temporary file.
894  // Insert -%%%%%%%% before the extension (if any), and because some tools
895  // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
896  // artifacts, also append .tmp.
897  StringRef OutputExtension = llvm::sys::path::extension(OutputPath);
898  SmallString<128> TempPath =
899  StringRef(OutputPath).drop_back(OutputExtension.size());
900  TempPath += "-%%%%%%%%";
901  TempPath += OutputExtension;
902  TempPath += ".tmp";
903  llvm::sys::fs::OpenFlags BinaryFlags =
904  Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text;
905  Expected<llvm::sys::fs::TempFile> ExpectedFile =
907  TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
908  BinaryFlags);
909 
910  llvm::Error E = handleErrors(
911  ExpectedFile.takeError(), [&](const llvm::ECError &E) -> llvm::Error {
912  std::error_code EC = E.convertToErrorCode();
913  if (CreateMissingDirectories &&
914  EC == llvm::errc::no_such_file_or_directory) {
915  StringRef Parent = llvm::sys::path::parent_path(OutputPath);
916  EC = llvm::sys::fs::create_directories(Parent);
917  if (!EC) {
918  ExpectedFile = llvm::sys::fs::TempFile::create(
919  TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
920  BinaryFlags);
921  if (!ExpectedFile)
922  return llvm::errorCodeToError(
923  llvm::errc::no_such_file_or_directory);
924  }
925  }
926  return llvm::errorCodeToError(EC);
927  });
928 
929  if (E) {
930  consumeError(std::move(E));
931  } else {
932  Temp = std::move(ExpectedFile.get());
933  OS.reset(new llvm::raw_fd_ostream(Temp->FD, /*shouldClose=*/false));
934  OSFile = Temp->TmpName;
935  }
936  // If we failed to create the temporary, fallback to writing to the file
937  // directly. This handles the corner case where we cannot write to the
938  // directory, but can write to the file.
939  }
940 
941  if (!OS) {
942  OSFile = OutputPath;
943  std::error_code EC;
944  OS.reset(new llvm::raw_fd_ostream(
945  *OSFile, EC,
946  (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF)));
947  if (EC)
948  return llvm::errorCodeToError(EC);
949  }
950 
951  // Add the output file -- but don't try to remove "-", since this means we are
952  // using stdin.
953  OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(),
954  std::move(Temp));
955 
956  if (!Binary || OS->supportsSeeking())
957  return std::move(OS);
958 
959  return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS));
960 }
961 
962 // Initialization Utilities
963 
964 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
966  getSourceManager());
967 }
968 
969 // static
971  DiagnosticsEngine &Diags,
972  FileManager &FileMgr,
973  SourceManager &SourceMgr) {
979 
980  if (Input.isBuffer()) {
981  SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
982  assert(SourceMgr.getMainFileID().isValid() &&
983  "Couldn't establish MainFileID!");
984  return true;
985  }
986 
987  StringRef InputFile = Input.getFile();
988 
989  // Figure out where to get and map in the main file.
990  auto FileOrErr = InputFile == "-"
991  ? FileMgr.getSTDIN()
992  : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
993  if (!FileOrErr) {
994  auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
995  if (InputFile != "-")
996  Diags.Report(diag::err_fe_error_reading) << InputFile << EC.message();
997  else
998  Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
999  return false;
1000  }
1001 
1002  SourceMgr.setMainFileID(
1003  SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
1004 
1005  assert(SourceMgr.getMainFileID().isValid() &&
1006  "Couldn't establish MainFileID!");
1007  return true;
1008 }
1009 
1010 // High-Level Operations
1011 
1013  assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
1014  assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
1015  assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
1016 
1017  // Mark this point as the bottom of the stack if we don't have somewhere
1018  // better. We generally expect frontend actions to be invoked with (nearly)
1019  // DesiredStackSpace available.
1021 
1022  auto FinishDiagnosticClient = llvm::make_scope_exit([&]() {
1023  // Notify the diagnostic client that all files were processed.
1025  });
1026 
1027  raw_ostream &OS = getVerboseOutputStream();
1028 
1029  if (!Act.PrepareToExecute(*this))
1030  return false;
1031 
1032  if (!createTarget())
1033  return false;
1034 
1035  // rewriter project will change target built-in bool type from its default.
1036  if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
1038 
1039  // Validate/process some options.
1040  if (getHeaderSearchOpts().Verbose)
1041  OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
1042  << LLVM_VERSION_STRING << " default target "
1043  << llvm::sys::getDefaultTargetTriple() << "\n";
1044 
1045  if (getCodeGenOpts().TimePasses)
1047 
1048  if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
1049  llvm::EnableStatistics(false);
1050 
1051  // Sort vectors containing toc data and no toc data variables to facilitate
1052  // binary search later.
1053  llvm::sort(getCodeGenOpts().TocDataVarsUserSpecified);
1054  llvm::sort(getCodeGenOpts().NoTocDataVars);
1055 
1056  for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
1057  // Reset the ID tables if we are reusing the SourceManager and parsing
1058  // regular files.
1059  if (hasSourceManager() && !Act.isModelParsingAction())
1061 
1062  if (Act.BeginSourceFile(*this, FIF)) {
1063  if (llvm::Error Err = Act.Execute()) {
1064  consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1065  }
1066  Act.EndSourceFile();
1067  }
1068  }
1069 
1071 
1072  if (getFrontendOpts().ShowStats) {
1073  if (hasFileManager()) {
1075  OS << '\n';
1076  }
1077  llvm::PrintStatistics(OS);
1078  }
1079  StringRef StatsFile = getFrontendOpts().StatsFile;
1080  if (!StatsFile.empty()) {
1081  llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1082  if (getFrontendOpts().AppendStats)
1083  FileFlags |= llvm::sys::fs::OF_Append;
1084  std::error_code EC;
1085  auto StatS =
1086  std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1087  if (EC) {
1088  getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1089  << StatsFile << EC.message();
1090  } else {
1091  llvm::PrintStatisticsJSON(*StatS);
1092  }
1093  }
1094 
1095  return !getDiagnostics().getClient()->getNumErrors();
1096 }
1097 
1099  if (!getDiagnosticOpts().ShowCarets)
1100  return;
1101 
1102  raw_ostream &OS = getVerboseOutputStream();
1103 
1104  // We can have multiple diagnostics sharing one diagnostic client.
1105  // Get the total number of warnings/errors from the client.
1106  unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1107  unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1108 
1109  if (NumWarnings)
1110  OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1111  if (NumWarnings && NumErrors)
1112  OS << " and ";
1113  if (NumErrors)
1114  OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1115  if (NumWarnings || NumErrors) {
1116  OS << " generated";
1117  if (getLangOpts().CUDA) {
1118  if (!getLangOpts().CUDAIsDevice) {
1119  OS << " when compiling for host";
1120  } else {
1121  OS << " when compiling for " << getTargetOpts().CPU;
1122  }
1123  }
1124  OS << ".\n";
1125  }
1126 }
1127 
1129  // Load any requested plugins.
1130  for (const std::string &Path : getFrontendOpts().Plugins) {
1131  std::string Error;
1132  if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
1133  getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1134  << Path << Error;
1135  }
1136 
1137  // Check if any of the loaded plugins replaces the main AST action
1138  for (const FrontendPluginRegistry::entry &Plugin :
1139  FrontendPluginRegistry::entries()) {
1140  std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1141  if (P->getActionType() == PluginASTAction::ReplaceAction) {
1143  getFrontendOpts().ActionName = Plugin.getName().str();
1144  break;
1145  }
1146  }
1147 }
1148 
1149 /// Determine the appropriate source input kind based on language
1150 /// options.
1152  if (LangOpts.OpenCL)
1153  return Language::OpenCL;
1154  if (LangOpts.CUDA)
1155  return Language::CUDA;
1156  if (LangOpts.ObjC)
1157  return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1158  return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1159 }
1160 
1161 /// Compile a module file for the given module, using the options
1162 /// provided by the importing compiler instance. Returns true if the module
1163 /// was built without errors.
1164 static bool
1165 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1166  StringRef ModuleName, FrontendInputFile Input,
1167  StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1168  llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
1169  [](CompilerInstance &) {},
1170  llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1171  [](CompilerInstance &) {}) {
1172  llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1173 
1174  // Never compile a module that's already finalized - this would cause the
1175  // existing module to be freed, causing crashes if it is later referenced
1176  if (ImportingInstance.getModuleCache().isPCMFinal(ModuleFileName)) {
1177  ImportingInstance.getDiagnostics().Report(
1178  ImportLoc, diag::err_module_rebuild_finalized)
1179  << ModuleName;
1180  return false;
1181  }
1182 
1183  // Construct a compiler invocation for creating this module.
1184  auto Invocation =
1185  std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
1186 
1187  PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1188 
1189  // For any options that aren't intended to affect how a module is built,
1190  // reset them to their default values.
1191  Invocation->resetNonModularOptions();
1192 
1193  // Remove any macro definitions that are explicitly ignored by the module.
1194  // They aren't supposed to affect how the module is built anyway.
1195  HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1196  llvm::erase_if(PPOpts.Macros,
1197  [&HSOpts](const std::pair<std::string, bool> &def) {
1198  StringRef MacroDef = def.first;
1199  return HSOpts.ModulesIgnoreMacros.contains(
1200  llvm::CachedHashString(MacroDef.split('=').first));
1201  });
1202 
1203  // If the original compiler invocation had -fmodule-name, pass it through.
1204  Invocation->getLangOpts().ModuleName =
1205  ImportingInstance.getInvocation().getLangOpts().ModuleName;
1206 
1207  // Note the name of the module we're building.
1208  Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1209 
1210  // If there is a module map file, build the module using the module map.
1211  // Set up the inputs/outputs so that we build the module from its umbrella
1212  // header.
1213  FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1214  FrontendOpts.OutputFile = ModuleFileName.str();
1215  FrontendOpts.DisableFree = false;
1216  FrontendOpts.GenerateGlobalModuleIndex = false;
1217  FrontendOpts.BuildingImplicitModule = true;
1218  FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1219  // Force implicitly-built modules to hash the content of the module file.
1220  HSOpts.ModulesHashContent = true;
1221  FrontendOpts.Inputs = {Input};
1222 
1223  // Don't free the remapped file buffers; they are owned by our caller.
1224  PPOpts.RetainRemappedFileBuffers = true;
1225 
1226  DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1227 
1228  DiagOpts.VerifyDiagnostics = 0;
1229  assert(ImportingInstance.getInvocation().getModuleHash() ==
1230  Invocation->getModuleHash() && "Module hash mismatch!");
1231 
1232  // Construct a compiler instance that will be used to actually create the
1233  // module. Since we're sharing an in-memory module cache,
1234  // CompilerInstance::CompilerInstance is responsible for finalizing the
1235  // buffers to prevent use-after-frees.
1236  CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
1237  &ImportingInstance.getModuleCache());
1238  auto &Inv = *Invocation;
1239  Instance.setInvocation(std::move(Invocation));
1240 
1241  Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
1242  ImportingInstance.getDiagnosticClient()),
1243  /*ShouldOwnClient=*/true);
1244 
1245  if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
1246  Instance.getDiagnostics().setSuppressSystemWarnings(false);
1247 
1248  if (FrontendOpts.ModulesShareFileManager) {
1249  Instance.setFileManager(&ImportingInstance.getFileManager());
1250  } else {
1251  Instance.createFileManager(&ImportingInstance.getVirtualFileSystem());
1252  }
1253  Instance.createSourceManager(Instance.getFileManager());
1254  SourceManager &SourceMgr = Instance.getSourceManager();
1255 
1256  // Note that this module is part of the module build stack, so that we
1257  // can detect cycles in the module graph.
1258  SourceMgr.setModuleBuildStack(
1259  ImportingInstance.getSourceManager().getModuleBuildStack());
1260  SourceMgr.pushModuleBuildStack(ModuleName,
1261  FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
1262 
1263  // Make sure that the failed-module structure has been allocated in
1264  // the importing instance, and propagate the pointer to the newly-created
1265  // instance.
1266  if (!ImportingInstance.hasFailedModulesSet())
1267  ImportingInstance.createFailedModulesSet();
1268  Instance.setFailedModulesSet(ImportingInstance.getFailedModulesSetPtr());
1269 
1270  // If we're collecting module dependencies, we need to share a collector
1271  // between all of the module CompilerInstances. Other than that, we don't
1272  // want to produce any dependency output from the module build.
1273  Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
1274  Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1275 
1276  ImportingInstance.getDiagnostics().Report(ImportLoc,
1277  diag::remark_module_build)
1278  << ModuleName << ModuleFileName;
1279 
1280  PreBuildStep(Instance);
1281 
1282  // Execute the action to actually build the module in-place. Use a separate
1283  // thread so that we get a stack large enough.
1284  bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread(
1285  [&]() {
1287  Instance.ExecuteAction(Action);
1288  },
1290 
1291  PostBuildStep(Instance);
1292 
1293  ImportingInstance.getDiagnostics().Report(ImportLoc,
1294  diag::remark_module_build_done)
1295  << ModuleName;
1296 
1297  // Propagate the statistics to the parent FileManager.
1298  if (!FrontendOpts.ModulesShareFileManager)
1299  ImportingInstance.getFileManager().AddStats(Instance.getFileManager());
1300 
1301  if (Crashed) {
1302  // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1303  // that must be closed before clearing output files.
1304  Instance.setSema(nullptr);
1305  Instance.setASTConsumer(nullptr);
1306 
1307  // Delete any remaining temporary files related to Instance.
1308  Instance.clearOutputFiles(/*EraseFiles=*/true);
1309  }
1310 
1311  // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1312  // occurred.
1313  return !Instance.getDiagnostics().hasErrorOccurred() ||
1314  Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1315 }
1316 
1318  FileManager &FileMgr) {
1319  StringRef Filename = llvm::sys::path::filename(File.getName());
1320  SmallString<128> PublicFilename(File.getDir().getName());
1321  if (Filename == "module_private.map")
1322  llvm::sys::path::append(PublicFilename, "module.map");
1323  else if (Filename == "module.private.modulemap")
1324  llvm::sys::path::append(PublicFilename, "module.modulemap");
1325  else
1326  return std::nullopt;
1327  return FileMgr.getOptionalFileRef(PublicFilename);
1328 }
1329 
1330 /// Compile a module file for the given module in a separate compiler instance,
1331 /// using the options provided by the importing compiler instance. Returns true
1332 /// if the module was built without errors.
1333 static bool compileModule(CompilerInstance &ImportingInstance,
1334  SourceLocation ImportLoc, Module *Module,
1335  StringRef ModuleFileName) {
1336  InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
1338 
1339  // Get or create the module map that we'll use to build this module.
1340  ModuleMap &ModMap
1341  = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1342  SourceManager &SourceMgr = ImportingInstance.getSourceManager();
1343  bool Result;
1344  if (FileID ModuleMapFID = ModMap.getContainingModuleMapFileID(Module);
1345  ModuleMapFID.isValid()) {
1346  // We want to use the top-level module map. If we don't, the compiling
1347  // instance may think the containing module map is a top-level one, while
1348  // the importing instance knows it's included from a parent module map via
1349  // the extern directive. This mismatch could bite us later.
1350  SourceLocation Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1351  while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1352  ModuleMapFID = SourceMgr.getFileID(Loc);
1353  Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1354  }
1355 
1356  OptionalFileEntryRef ModuleMapFile =
1357  SourceMgr.getFileEntryRefForID(ModuleMapFID);
1358  assert(ModuleMapFile && "Top-level module map with no FileID");
1359 
1360  // Canonicalize compilation to start with the public module map. This is
1361  // vital for submodules declarations in the private module maps to be
1362  // correctly parsed when depending on a top level module in the public one.
1363  if (OptionalFileEntryRef PublicMMFile = getPublicModuleMap(
1364  *ModuleMapFile, ImportingInstance.getFileManager()))
1365  ModuleMapFile = PublicMMFile;
1366 
1367  StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1368 
1369  // Use the module map where this module resides.
1370  Result = compileModuleImpl(
1371  ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1372  FrontendInputFile(ModuleMapFilePath, IK, +Module->IsSystem),
1373  ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName);
1374  } else {
1375  // FIXME: We only need to fake up an input file here as a way of
1376  // transporting the module's directory to the module map parser. We should
1377  // be able to do that more directly, and parse from a memory buffer without
1378  // inventing this file.
1379  SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1380  llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1381 
1382  std::string InferredModuleMapContent;
1383  llvm::raw_string_ostream OS(InferredModuleMapContent);
1384  Module->print(OS);
1385  OS.flush();
1386 
1387  Result = compileModuleImpl(
1388  ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1389  FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1391  ModuleFileName,
1392  [&](CompilerInstance &Instance) {
1393  std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1394  llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1395  FileEntryRef ModuleMapFile = Instance.getFileManager().getVirtualFileRef(
1396  FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1397  Instance.getSourceManager().overrideFileContents(
1398  ModuleMapFile, std::move(ModuleMapBuffer));
1399  });
1400  }
1401 
1402  // We've rebuilt a module. If we're allowed to generate or update the global
1403  // module index, record that fact in the importing compiler instance.
1404  if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1405  ImportingInstance.setBuildGlobalModuleIndex(true);
1406  }
1407 
1408  return Result;
1409 }
1410 
1411 /// Read the AST right after compiling the module.
1412 static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1413  SourceLocation ImportLoc,
1414  SourceLocation ModuleNameLoc,
1415  Module *Module, StringRef ModuleFileName,
1416  bool *OutOfDate) {
1417  DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1418 
1419  unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1420  if (OutOfDate)
1421  ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1422 
1423  // Try to read the module file, now that we've compiled it.
1424  ASTReader::ASTReadResult ReadResult =
1425  ImportingInstance.getASTReader()->ReadAST(
1426  ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1427  ModuleLoadCapabilities);
1428  if (ReadResult == ASTReader::Success)
1429  return true;
1430 
1431  // The caller wants to handle out-of-date failures.
1432  if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1433  *OutOfDate = true;
1434  return false;
1435  }
1436 
1437  // The ASTReader didn't diagnose the error, so conservatively report it.
1438  if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1439  Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1440  << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1441 
1442  return false;
1443 }
1444 
1445 /// Compile a module in a separate compiler instance and read the AST,
1446 /// returning true if the module compiles without errors.
1447 static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
1448  SourceLocation ImportLoc,
1449  SourceLocation ModuleNameLoc,
1450  Module *Module,
1451  StringRef ModuleFileName) {
1452  if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
1453  ModuleFileName)) {
1454  ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1455  diag::err_module_not_built)
1456  << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1457  return false;
1458  }
1459 
1460  return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1461  Module, ModuleFileName,
1462  /*OutOfDate=*/nullptr);
1463 }
1464 
1465 /// Compile a module in a separate compiler instance and read the AST,
1466 /// returning true if the module compiles without errors, using a lock manager
1467 /// to avoid building the same module in multiple compiler instances.
1468 ///
1469 /// Uses a lock file manager and exponential backoff to reduce the chances that
1470 /// multiple instances will compete to create the same module. On timeout,
1471 /// deletes the lock file in order to avoid deadlock from crashing processes or
1472 /// bugs in the lock file manager.
1474  CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1475  SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
1476  DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1477 
1478  Diags.Report(ModuleNameLoc, diag::remark_module_lock)
1479  << ModuleFileName << Module->Name;
1480 
1481  // FIXME: have LockFileManager return an error_code so that we can
1482  // avoid the mkdir when the directory already exists.
1483  StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1484  llvm::sys::fs::create_directories(Dir);
1485 
1486  while (true) {
1487  llvm::LockFileManager Locked(ModuleFileName);
1488  switch (Locked) {
1489  case llvm::LockFileManager::LFS_Error:
1490  // ModuleCache takes care of correctness and locks are only necessary for
1491  // performance. Fallback to building the module in case of any lock
1492  // related errors.
1493  Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1494  << Module->Name << Locked.getErrorMessage();
1495  // Clear out any potential leftover.
1496  Locked.unsafeRemoveLockFile();
1497  [[fallthrough]];
1498  case llvm::LockFileManager::LFS_Owned:
1499  // We're responsible for building the module ourselves.
1500  return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1501  ModuleNameLoc, Module, ModuleFileName);
1502 
1503  case llvm::LockFileManager::LFS_Shared:
1504  break; // The interesting case.
1505  }
1506 
1507  // Someone else is responsible for building the module. Wait for them to
1508  // finish.
1509  switch (Locked.waitForUnlock()) {
1510  case llvm::LockFileManager::Res_Success:
1511  break; // The interesting case.
1512  case llvm::LockFileManager::Res_OwnerDied:
1513  continue; // try again to get the lock.
1514  case llvm::LockFileManager::Res_Timeout:
1515  // Since ModuleCache takes care of correctness, we try waiting for
1516  // another process to complete the build so clang does not do it done
1517  // twice. If case of timeout, build it ourselves.
1518  Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1519  << Module->Name;
1520  // Clear the lock file so that future invocations can make progress.
1521  Locked.unsafeRemoveLockFile();
1522  continue;
1523  }
1524 
1525  // Read the module that was just written by someone else.
1526  bool OutOfDate = false;
1527  if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1528  Module, ModuleFileName, &OutOfDate))
1529  return true;
1530  if (!OutOfDate)
1531  return false;
1532 
1533  // The module may be out of date in the presence of file system races,
1534  // or if one of its imports depends on header search paths that are not
1535  // consistent with this ImportingInstance. Try again...
1536  }
1537 }
1538 
1539 /// Compile a module in a separate compiler instance and read the AST,
1540 /// returning true if the module compiles without errors, potentially using a
1541 /// lock manager to avoid building the same module in multiple compiler
1542 /// instances.
1543 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1544  SourceLocation ImportLoc,
1545  SourceLocation ModuleNameLoc,
1546  Module *Module, StringRef ModuleFileName) {
1547  return ImportingInstance.getInvocation()
1548  .getFrontendOpts()
1550  ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
1551  ModuleNameLoc, Module,
1552  ModuleFileName)
1553  : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1554  ModuleNameLoc, Module,
1555  ModuleFileName);
1556 }
1557 
1558 /// Diagnose differences between the current definition of the given
1559 /// configuration macro and the definition provided on the command line.
1560 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1561  Module *Mod, SourceLocation ImportLoc) {
1562  IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1563  SourceManager &SourceMgr = PP.getSourceManager();
1564 
1565  // If this identifier has never had a macro definition, then it could
1566  // not have changed.
1567  if (!Id->hadMacroDefinition())
1568  return;
1569  auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1570 
1571  // Find the macro definition from the command line.
1572  MacroInfo *CmdLineDefinition = nullptr;
1573  for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1574  // We only care about the predefines buffer.
1575  FileID FID = SourceMgr.getFileID(MD->getLocation());
1576  if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1577  continue;
1578  if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1579  CmdLineDefinition = DMD->getMacroInfo();
1580  break;
1581  }
1582 
1583  auto *CurrentDefinition = PP.getMacroInfo(Id);
1584  if (CurrentDefinition == CmdLineDefinition) {
1585  // Macro matches. Nothing to do.
1586  } else if (!CurrentDefinition) {
1587  // This macro was defined on the command line, then #undef'd later.
1588  // Complain.
1589  PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1590  << true << ConfigMacro << Mod->getFullModuleName();
1591  auto LatestDef = LatestLocalMD->getDefinition();
1592  assert(LatestDef.isUndefined() &&
1593  "predefined macro went away with no #undef?");
1594  PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1595  << true;
1596  return;
1597  } else if (!CmdLineDefinition) {
1598  // There was no definition for this macro in the predefines buffer,
1599  // but there was a local definition. Complain.
1600  PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1601  << false << ConfigMacro << Mod->getFullModuleName();
1602  PP.Diag(CurrentDefinition->getDefinitionLoc(),
1603  diag::note_module_def_undef_here)
1604  << false;
1605  } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1606  /*Syntactically=*/true)) {
1607  // The macro definitions differ.
1608  PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1609  << false << ConfigMacro << Mod->getFullModuleName();
1610  PP.Diag(CurrentDefinition->getDefinitionLoc(),
1611  diag::note_module_def_undef_here)
1612  << false;
1613  }
1614 }
1615 
1617  SourceLocation ImportLoc) {
1618  clang::Module *TopModule = M->getTopLevelModule();
1619  for (const StringRef ConMacro : TopModule->ConfigMacros) {
1620  checkConfigMacro(PP, ConMacro, M, ImportLoc);
1621  }
1622 }
1623 
1624 /// Write a new timestamp file with the given path.
1625 static void writeTimestampFile(StringRef TimestampFile) {
1626  std::error_code EC;
1627  llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
1628 }
1629 
1630 /// Prune the module cache of modules that haven't been accessed in
1631 /// a long time.
1632 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1633  llvm::sys::fs::file_status StatBuf;
1634  llvm::SmallString<128> TimestampFile;
1635  TimestampFile = HSOpts.ModuleCachePath;
1636  assert(!TimestampFile.empty());
1637  llvm::sys::path::append(TimestampFile, "modules.timestamp");
1638 
1639  // Try to stat() the timestamp file.
1640  if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
1641  // If the timestamp file wasn't there, create one now.
1642  if (EC == std::errc::no_such_file_or_directory) {
1643  writeTimestampFile(TimestampFile);
1644  }
1645  return;
1646  }
1647 
1648  // Check whether the time stamp is older than our pruning interval.
1649  // If not, do nothing.
1650  time_t TimeStampModTime =
1651  llvm::sys::toTimeT(StatBuf.getLastModificationTime());
1652  time_t CurrentTime = time(nullptr);
1653  if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1654  return;
1655 
1656  // Write a new timestamp file so that nobody else attempts to prune.
1657  // There is a benign race condition here, if two Clang instances happen to
1658  // notice at the same time that the timestamp is out-of-date.
1659  writeTimestampFile(TimestampFile);
1660 
1661  // Walk the entire module cache, looking for unused module files and module
1662  // indices.
1663  std::error_code EC;
1664  SmallString<128> ModuleCachePathNative;
1665  llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1666  for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1667  Dir != DirEnd && !EC; Dir.increment(EC)) {
1668  // If we don't have a directory, there's nothing to look into.
1669  if (!llvm::sys::fs::is_directory(Dir->path()))
1670  continue;
1671 
1672  // Walk all of the files within this directory.
1673  for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1674  File != FileEnd && !EC; File.increment(EC)) {
1675  // We only care about module and global module index files.
1676  StringRef Extension = llvm::sys::path::extension(File->path());
1677  if (Extension != ".pcm" && Extension != ".timestamp" &&
1678  llvm::sys::path::filename(File->path()) != "modules.idx")
1679  continue;
1680 
1681  // Look at this file. If we can't stat it, there's nothing interesting
1682  // there.
1683  if (llvm::sys::fs::status(File->path(), StatBuf))
1684  continue;
1685 
1686  // If the file has been used recently enough, leave it there.
1687  time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
1688  if (CurrentTime - FileAccessTime <=
1689  time_t(HSOpts.ModuleCachePruneAfter)) {
1690  continue;
1691  }
1692 
1693  // Remove the file.
1694  llvm::sys::fs::remove(File->path());
1695 
1696  // Remove the timestamp file.
1697  std::string TimpestampFilename = File->path() + ".timestamp";
1698  llvm::sys::fs::remove(TimpestampFilename);
1699  }
1700 
1701  // If we removed all of the files in the directory, remove the directory
1702  // itself.
1703  if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1704  llvm::sys::fs::directory_iterator() && !EC)
1705  llvm::sys::fs::remove(Dir->path());
1706  }
1707 }
1708 
1710  if (TheASTReader)
1711  return;
1712 
1713  if (!hasASTContext())
1714  createASTContext();
1715 
1716  // If we're implicitly building modules but not currently recursively
1717  // building a module, check whether we need to prune the module cache.
1718  if (getSourceManager().getModuleBuildStack().empty() &&
1719  !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1720  getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1721  getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1723  }
1724 
1726  std::string Sysroot = HSOpts.Sysroot;
1727  const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1728  const FrontendOptions &FEOpts = getFrontendOpts();
1729  std::unique_ptr<llvm::Timer> ReadTimer;
1730 
1731  if (FrontendTimerGroup)
1732  ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1733  "Reading modules",
1734  *FrontendTimerGroup);
1735  TheASTReader = new ASTReader(
1737  getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
1738  Sysroot.empty() ? "" : Sysroot.c_str(),
1740  /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1741  /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders,
1743  getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1744  if (hasASTConsumer()) {
1745  TheASTReader->setDeserializationListener(
1746  getASTConsumer().GetASTDeserializationListener());
1748  getASTConsumer().GetASTMutationListener());
1749  }
1750  getASTContext().setExternalSource(TheASTReader);
1751  if (hasSema())
1752  TheASTReader->InitializeSema(getSema());
1753  if (hasASTConsumer())
1754  TheASTReader->StartTranslationUnit(&getASTConsumer());
1755 
1756  for (auto &Listener : DependencyCollectors)
1757  Listener->attachToASTReader(*TheASTReader);
1758 }
1759 
1761  StringRef FileName, serialization::ModuleFile *&LoadedModuleFile) {
1762  llvm::Timer Timer;
1763  if (FrontendTimerGroup)
1764  Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1765  *FrontendTimerGroup);
1766  llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1767 
1768  // If we don't already have an ASTReader, create one now.
1769  if (!TheASTReader)
1770  createASTReader();
1771 
1772  // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1773  // ASTReader to diagnose it, since it can produce better errors that we can.
1774  bool ConfigMismatchIsRecoverable =
1775  getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
1776  SourceLocation())
1778 
1779  auto Listener = std::make_unique<ReadModuleNames>(*PP);
1780  auto &ListenerRef = *Listener;
1781  ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1782  std::move(Listener));
1783 
1784  // Try to load the module file.
1785  switch (TheASTReader->ReadAST(
1787  ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0,
1788  &LoadedModuleFile)) {
1789  case ASTReader::Success:
1790  // We successfully loaded the module file; remember the set of provided
1791  // modules so that we don't try to load implicit modules for them.
1792  ListenerRef.registerAll();
1793  return true;
1794 
1796  // Ignore unusable module files.
1797  getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1798  << FileName;
1799  // All modules provided by any files we tried and failed to load are now
1800  // unavailable; includes of those modules should now be handled textually.
1801  ListenerRef.markAllUnavailable();
1802  return true;
1803 
1804  default:
1805  return false;
1806  }
1807 }
1808 
1809 namespace {
1810 enum ModuleSource {
1811  MS_ModuleNotFound,
1812  MS_ModuleCache,
1813  MS_PrebuiltModulePath,
1814  MS_ModuleBuildPragma
1815 };
1816 } // end namespace
1817 
1818 /// Select a source for loading the named module and compute the filename to
1819 /// load it from.
1820 static ModuleSource selectModuleSource(
1821  Module *M, StringRef ModuleName, std::string &ModuleFilename,
1822  const std::map<std::string, std::string, std::less<>> &BuiltModules,
1823  HeaderSearch &HS) {
1824  assert(ModuleFilename.empty() && "Already has a module source?");
1825 
1826  // Check to see if the module has been built as part of this compilation
1827  // via a module build pragma.
1828  auto BuiltModuleIt = BuiltModules.find(ModuleName);
1829  if (BuiltModuleIt != BuiltModules.end()) {
1830  ModuleFilename = BuiltModuleIt->second;
1831  return MS_ModuleBuildPragma;
1832  }
1833 
1834  // Try to load the module from the prebuilt module path.
1835  const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1836  if (!HSOpts.PrebuiltModuleFiles.empty() ||
1837  !HSOpts.PrebuiltModulePaths.empty()) {
1838  ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1839  if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1840  ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1841  if (!ModuleFilename.empty())
1842  return MS_PrebuiltModulePath;
1843  }
1844 
1845  // Try to load the module from the module cache.
1846  if (M) {
1847  ModuleFilename = HS.getCachedModuleFileName(M);
1848  return MS_ModuleCache;
1849  }
1850 
1851  return MS_ModuleNotFound;
1852 }
1853 
1854 ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1855  StringRef ModuleName, SourceLocation ImportLoc,
1856  SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
1857  // Search for a module with the given name.
1858  HeaderSearch &HS = PP->getHeaderSearchInfo();
1859  Module *M =
1860  HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1861 
1862  // Check for any configuration macros that have changed. This is done
1863  // immediately before potentially building a module in case this module
1864  // depends on having one of its configuration macros defined to successfully
1865  // build. If this is not done the user will never see the warning.
1866  if (M)
1867  checkConfigMacros(getPreprocessor(), M, ImportLoc);
1868 
1869  // Select the source and filename for loading the named module.
1870  std::string ModuleFilename;
1871  ModuleSource Source =
1872  selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1873  if (Source == MS_ModuleNotFound) {
1874  // We can't find a module, error out here.
1875  getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1876  << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1877  return nullptr;
1878  }
1879  if (ModuleFilename.empty()) {
1880  if (M && M->HasIncompatibleModuleFile) {
1881  // We tried and failed to load a module file for this module. Fall
1882  // back to textual inclusion for its headers.
1884  }
1885 
1886  getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1887  << ModuleName;
1888  return nullptr;
1889  }
1890 
1891  // Create an ASTReader on demand.
1892  if (!getASTReader())
1893  createASTReader();
1894 
1895  // Time how long it takes to load the module.
1896  llvm::Timer Timer;
1897  if (FrontendTimerGroup)
1898  Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
1899  *FrontendTimerGroup);
1900  llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1901  llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1902 
1903  // Try to load the module file. If we are not trying to load from the
1904  // module cache, we don't know how to rebuild modules.
1905  unsigned ARRFlags = Source == MS_ModuleCache
1908  : Source == MS_PrebuiltModulePath
1909  ? 0
1911  switch (getASTReader()->ReadAST(ModuleFilename,
1912  Source == MS_PrebuiltModulePath
1914  : Source == MS_ModuleBuildPragma
1917  ImportLoc, ARRFlags)) {
1918  case ASTReader::Success: {
1919  if (M)
1920  return M;
1921  assert(Source != MS_ModuleCache &&
1922  "missing module, but file loaded from cache");
1923 
1924  // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1925  // until the first call to ReadAST. Look it up now.
1926  M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1927 
1928  // Check whether M refers to the file in the prebuilt module path.
1929  if (M && M->getASTFile())
1930  if (auto ModuleFile = FileMgr->getFile(ModuleFilename))
1931  if (*ModuleFile == M->getASTFile())
1932  return M;
1933 
1934  getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1935  << ModuleName;
1936  return ModuleLoadResult();
1937  }
1938 
1939  case ASTReader::OutOfDate:
1940  case ASTReader::Missing:
1941  // The most interesting case.
1942  break;
1943 
1945  if (Source == MS_PrebuiltModulePath)
1946  // FIXME: We shouldn't be setting HadFatalFailure below if we only
1947  // produce a warning here!
1949  diag::warn_module_config_mismatch)
1950  << ModuleFilename;
1951  // Fall through to error out.
1952  [[fallthrough]];
1954  case ASTReader::HadErrors:
1956  // FIXME: The ASTReader will already have complained, but can we shoehorn
1957  // that diagnostic information into a more useful form?
1958  return ModuleLoadResult();
1959 
1960  case ASTReader::Failure:
1962  return ModuleLoadResult();
1963  }
1964 
1965  // ReadAST returned Missing or OutOfDate.
1966  if (Source != MS_ModuleCache) {
1967  // We don't know the desired configuration for this module and don't
1968  // necessarily even have a module map. Since ReadAST already produces
1969  // diagnostics for these two cases, we simply error out here.
1970  return ModuleLoadResult();
1971  }
1972 
1973  // The module file is missing or out-of-date. Build it.
1974  assert(M && "missing module, but trying to compile for cache");
1975 
1976  // Check whether there is a cycle in the module graph.
1978  ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1979  for (; Pos != PosEnd; ++Pos) {
1980  if (Pos->first == ModuleName)
1981  break;
1982  }
1983 
1984  if (Pos != PosEnd) {
1985  SmallString<256> CyclePath;
1986  for (; Pos != PosEnd; ++Pos) {
1987  CyclePath += Pos->first;
1988  CyclePath += " -> ";
1989  }
1990  CyclePath += ModuleName;
1991 
1992  getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1993  << ModuleName << CyclePath;
1994  return nullptr;
1995  }
1996 
1997  // Check whether we have already attempted to build this module (but failed).
1998  if (FailedModules && FailedModules->hasAlreadyFailed(ModuleName)) {
1999  getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
2000  << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
2001  return nullptr;
2002  }
2003 
2004  // Try to compile and then read the AST.
2005  if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
2006  ModuleFilename)) {
2007  assert(getDiagnostics().hasErrorOccurred() &&
2008  "undiagnosed error in compileModuleAndReadAST");
2009  if (FailedModules)
2010  FailedModules->addFailed(ModuleName);
2011  return nullptr;
2012  }
2013 
2014  // Okay, we've rebuilt and now loaded the module.
2015  return M;
2016 }
2017 
2020  ModuleIdPath Path,
2022  bool IsInclusionDirective) {
2023  // Determine what file we're searching from.
2024  StringRef ModuleName = Path[0].first->getName();
2025  SourceLocation ModuleNameLoc = Path[0].second;
2026 
2027  // If we've already handled this import, just return the cached result.
2028  // This one-element cache is important to eliminate redundant diagnostics
2029  // when both the preprocessor and parser see the same import declaration.
2030  if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
2031  // Make the named module visible.
2032  if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
2033  TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
2034  ImportLoc);
2035  return LastModuleImportResult;
2036  }
2037 
2038  // If we don't already have information on this module, load the module now.
2039  Module *Module = nullptr;
2041  if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) {
2042  // Use the cached result, which may be nullptr.
2043  Module = *MaybeModule;
2044  // Config macros are already checked before building a module, but they need
2045  // to be checked at each import location in case any of the config macros
2046  // have a new value at the current `ImportLoc`.
2047  if (Module)
2048  checkConfigMacros(getPreprocessor(), Module, ImportLoc);
2049  } else if (ModuleName == getLangOpts().CurrentModule) {
2050  // This is the module we're building.
2052  ModuleName, ImportLoc, /*AllowSearch*/ true,
2053  /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
2054 
2055  // Config macros do not need to be checked here for two reasons.
2056  // * This will always be textual inclusion, and thus the config macros
2057  // actually do impact the content of the header.
2058  // * `Preprocessor::HandleHeaderIncludeOrImport` will never call this
2059  // function as the `#include` or `#import` is textual.
2060 
2061  MM.cacheModuleLoad(*Path[0].first, Module);
2062  } else {
2063  ModuleLoadResult Result = findOrCompileModuleAndReadAST(
2064  ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
2065  if (!Result.isNormal())
2066  return Result;
2067  if (!Result)
2068  DisableGeneratingGlobalModuleIndex = true;
2069  Module = Result;
2070  MM.cacheModuleLoad(*Path[0].first, Module);
2071  }
2072 
2073  // If we never found the module, fail. Otherwise, verify the module and link
2074  // it up.
2075  if (!Module)
2076  return ModuleLoadResult();
2077 
2078  // Verify that the rest of the module path actually corresponds to
2079  // a submodule.
2080  bool MapPrivateSubModToTopLevel = false;
2081  for (unsigned I = 1, N = Path.size(); I != N; ++I) {
2082  StringRef Name = Path[I].first->getName();
2083  clang::Module *Sub = Module->findSubmodule(Name);
2084 
2085  // If the user is requesting Foo.Private and it doesn't exist, try to
2086  // match Foo_Private and emit a warning asking for the user to write
2087  // @import Foo_Private instead. FIXME: remove this when existing clients
2088  // migrate off of Foo.Private syntax.
2089  if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
2090  SmallString<128> PrivateModule(Module->Name);
2091  PrivateModule.append("_Private");
2092 
2094  auto &II = PP->getIdentifierTable().get(
2095  PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
2096  PrivPath.push_back(std::make_pair(&II, Path[0].second));
2097 
2098  std::string FileName;
2099  // If there is a modulemap module or prebuilt module, load it.
2100  if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
2101  !IsInclusionDirective) ||
2102  selectModuleSource(nullptr, PrivateModule, FileName, BuiltModules,
2103  PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2104  Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
2105  if (Sub) {
2106  MapPrivateSubModToTopLevel = true;
2108  if (!getDiagnostics().isIgnored(
2109  diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2110  getDiagnostics().Report(Path[I].second,
2111  diag::warn_no_priv_submodule_use_toplevel)
2112  << Path[I].first << Module->getFullModuleName() << PrivateModule
2113  << SourceRange(Path[0].second, Path[I].second)
2114  << FixItHint::CreateReplacement(SourceRange(Path[0].second),
2115  PrivateModule);
2116  getDiagnostics().Report(Sub->DefinitionLoc,
2117  diag::note_private_top_level_defined);
2118  }
2119  }
2120  }
2121 
2122  if (!Sub) {
2123  // Attempt to perform typo correction to find a module name that works.
2125  unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2126 
2127  for (class Module *SubModule : Module->submodules()) {
2128  unsigned ED =
2129  Name.edit_distance(SubModule->Name,
2130  /*AllowReplacements=*/true, BestEditDistance);
2131  if (ED <= BestEditDistance) {
2132  if (ED < BestEditDistance) {
2133  Best.clear();
2134  BestEditDistance = ED;
2135  }
2136 
2137  Best.push_back(SubModule->Name);
2138  }
2139  }
2140 
2141  // If there was a clear winner, user it.
2142  if (Best.size() == 1) {
2143  getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest)
2144  << Path[I].first << Module->getFullModuleName() << Best[0]
2145  << SourceRange(Path[0].second, Path[I - 1].second)
2146  << FixItHint::CreateReplacement(SourceRange(Path[I].second),
2147  Best[0]);
2148 
2149  Sub = Module->findSubmodule(Best[0]);
2150  }
2151  }
2152 
2153  if (!Sub) {
2154  // No submodule by this name. Complain, and don't look for further
2155  // submodules.
2156  getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
2157  << Path[I].first << Module->getFullModuleName()
2158  << SourceRange(Path[0].second, Path[I - 1].second);
2159  break;
2160  }
2161 
2162  Module = Sub;
2163  }
2164 
2165  // Make the named module visible, if it's not already part of the module
2166  // we are parsing.
2167  if (ModuleName != getLangOpts().CurrentModule) {
2168  if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2169  // We have an umbrella header or directory that doesn't actually include
2170  // all of the headers within the directory it covers. Complain about
2171  // this missing submodule and recover by forgetting that we ever saw
2172  // this submodule.
2173  // FIXME: Should we detect this at module load time? It seems fairly
2174  // expensive (and rare).
2175  getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2177  << SourceRange(Path.front().second, Path.back().second);
2178 
2180  }
2181 
2182  // Check whether this module is available.
2184  *Module, getDiagnostics())) {
2185  getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2186  << SourceRange(Path.front().second, Path.back().second);
2187  LastModuleImportLoc = ImportLoc;
2188  LastModuleImportResult = ModuleLoadResult();
2189  return ModuleLoadResult();
2190  }
2191 
2192  TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2193  }
2194 
2195  // Resolve any remaining module using export_as for this one.
2196  getPreprocessor()
2198  .getModuleMap()
2200 
2201  LastModuleImportLoc = ImportLoc;
2202  LastModuleImportResult = ModuleLoadResult(Module);
2203  return LastModuleImportResult;
2204 }
2205 
2207  StringRef ModuleName,
2208  StringRef Source) {
2209  // Avoid creating filenames with special characters.
2210  SmallString<128> CleanModuleName(ModuleName);
2211  for (auto &C : CleanModuleName)
2212  if (!isAlphanumeric(C))
2213  C = '_';
2214 
2215  // FIXME: Using a randomized filename here means that our intermediate .pcm
2216  // output is nondeterministic (as .pcm files refer to each other by name).
2217  // Can this affect the output in any way?
2218  SmallString<128> ModuleFileName;
2219  if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2220  CleanModuleName, "pcm", ModuleFileName)) {
2221  getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2222  << ModuleFileName << EC.message();
2223  return;
2224  }
2225  std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2226 
2227  FrontendInputFile Input(
2228  ModuleMapFileName,
2229  InputKind(getLanguageFromOptions(Invocation->getLangOpts()),
2230  InputKind::ModuleMap, /*Preprocessed*/true));
2231 
2232  std::string NullTerminatedSource(Source.str());
2233 
2234  auto PreBuildStep = [&](CompilerInstance &Other) {
2235  // Create a virtual file containing our desired source.
2236  // FIXME: We shouldn't need to do this.
2237  FileEntryRef ModuleMapFile = Other.getFileManager().getVirtualFileRef(
2238  ModuleMapFileName, NullTerminatedSource.size(), 0);
2239  Other.getSourceManager().overrideFileContents(
2240  ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2241 
2242  Other.BuiltModules = std::move(BuiltModules);
2243  Other.DeleteBuiltModules = false;
2244  };
2245 
2246  auto PostBuildStep = [this](CompilerInstance &Other) {
2247  BuiltModules = std::move(Other.BuiltModules);
2248  };
2249 
2250  // Build the module, inheriting any modules that we've built locally.
2251  if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
2252  ModuleFileName, PreBuildStep, PostBuildStep)) {
2253  BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName);
2254  llvm::sys::RemoveFileOnSignal(ModuleFileName);
2255  }
2256 }
2257 
2260  SourceLocation ImportLoc) {
2261  if (!TheASTReader)
2262  createASTReader();
2263  if (!TheASTReader)
2264  return;
2265 
2266  TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2267 }
2268 
2270  SourceLocation TriggerLoc) {
2271  if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2272  return nullptr;
2273  if (!TheASTReader)
2274  createASTReader();
2275  // Can't do anything if we don't have the module manager.
2276  if (!TheASTReader)
2277  return nullptr;
2278  // Get an existing global index. This loads it if not already
2279  // loaded.
2280  TheASTReader->loadGlobalIndex();
2281  GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2282  // If the global index doesn't exist, create it.
2283  if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2284  hasPreprocessor()) {
2285  llvm::sys::fs::create_directories(
2286  getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2287  if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2289  getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2290  // FIXME this drops the error on the floor. This code is only used for
2291  // typo correction and drops more than just this one source of errors
2292  // (such as the directory creation failure above). It should handle the
2293  // error.
2294  consumeError(std::move(Err));
2295  return nullptr;
2296  }
2297  TheASTReader->resetForReload();
2298  TheASTReader->loadGlobalIndex();
2299  GlobalIndex = TheASTReader->getGlobalIndex();
2300  }
2301  // For finding modules needing to be imported for fixit messages,
2302  // we need to make the global index cover all modules, so we do that here.
2303  if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2305  bool RecreateIndex = false;
2306  for (ModuleMap::module_iterator I = MMap.module_begin(),
2307  E = MMap.module_end(); I != E; ++I) {
2308  Module *TheModule = I->second;
2309  OptionalFileEntryRef Entry = TheModule->getASTFile();
2310  if (!Entry) {
2312  Path.push_back(std::make_pair(
2313  getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
2314  std::reverse(Path.begin(), Path.end());
2315  // Load a module as hidden. This also adds it to the global index.
2316  loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2317  RecreateIndex = true;
2318  }
2319  }
2320  if (RecreateIndex) {
2321  if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2323  getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2324  // FIXME As above, this drops the error on the floor.
2325  consumeError(std::move(Err));
2326  return nullptr;
2327  }
2328  TheASTReader->resetForReload();
2329  TheASTReader->loadGlobalIndex();
2330  GlobalIndex = TheASTReader->getGlobalIndex();
2331  }
2332  HaveFullGlobalModuleIndex = true;
2333  }
2334  return GlobalIndex;
2335 }
2336 
2337 // Check global module index for missing imports.
2338 bool
2340  SourceLocation TriggerLoc) {
2341  // Look for the symbol in non-imported modules, but only if an error
2342  // actually occurred.
2343  if (!buildingModule()) {
2344  // Load global module index, or retrieve a previously loaded one.
2346  TriggerLoc);
2347 
2348  // Only if we have a global index.
2349  if (GlobalIndex) {
2350  GlobalModuleIndex::HitSet FoundModules;
2351 
2352  // Find the modules that reference the identifier.
2353  // Note that this only finds top-level modules.
2354  // We'll let diagnoseTypo find the actual declaration module.
2355  if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2356  return true;
2357  }
2358  }
2359 
2360  return false;
2361 }
2362 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2363 
2366  ExternalSemaSrc = std::move(ESS);
2367 }
Defines the clang::ASTContext interface.
int Id
Definition: ASTDiff.cpp:190
StringRef P
Defines the Diagnostic-related interfaces.
static void collectVFSEntries(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
static bool compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input, StringRef OriginalModuleMapFile, StringRef ModuleFileName, llvm::function_ref< void(CompilerInstance &)> PreBuildStep=[](CompilerInstance &) {}, llvm::function_ref< void(CompilerInstance &)> PostBuildStep=[](CompilerInstance &) {})
Compile a module file for the given module, using the options provided by the importing compiler inst...
static bool EnableCodeCompletion(Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column)
static ModuleSource selectModuleSource(Module *M, StringRef ModuleName, std::string &ModuleFilename, const std::map< std::string, std::string, std::less<>> &BuiltModules, HeaderSearch &HS)
Select a source for loading the named module and compute the filename to load it from.
static void pruneModuleCache(const HeaderSearchOptions &HSOpts)
Prune the module cache of modules that haven't been accessed in a long time.
static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
static bool compileModuleAndReadASTBehindLock(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName, bool *OutOfDate)
Read the AST right after compiling the module.
static Language getLanguageFromOptions(const LangOptions &LangOpts)
Determine the appropriate source input kind based on language options.
static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, Module *Mod, SourceLocation ImportLoc)
Diagnose differences between the current definition of the given configuration macro and the definiti...
static void collectHeaderMaps(const HeaderSearch &HS, std::shared_ptr< ModuleDependencyCollector > MDC)
static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, const CodeGenOptions *CodeGenOpts, DiagnosticsEngine &Diags)
static void writeTimestampFile(StringRef TimestampFile)
Write a new timestamp file with the given path.
static void InitializeFileRemapping(DiagnosticsEngine &Diags, SourceManager &SourceMgr, FileManager &FileMgr, const PreprocessorOptions &InitOpts)
static bool compileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName)
Compile a module file for the given module in a separate compiler instance, using the options provide...
static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, DiagnosticsEngine &Diags, StringRef OutputFile)
static void collectIncludePCH(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File, FileManager &FileMgr)
static void checkConfigMacros(Preprocessor &PP, Module *M, SourceLocation ImportLoc)
static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
Defines the clang::FileManager interface and associated types.
StringRef Filename
Definition: Format.cpp:2976
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
llvm::MachO::Target Target
Definition: MachO.h:50
Defines the clang::Preprocessor interface.
SourceLocation Loc
Definition: SemaObjC.cpp:755
Defines the SourceManager interface.
Defines utilities for dealing with stack allocation and stack space.
Defines version macros and version-related utility functions for Clang.
__DEVICE__ int max(int __a, int __b)
std::vector< std::string > ModuleSearchPaths
The set of search paths where we API notes can be found for particular modules.
virtual void Initialize(ASTContext &Context)
Initialize - This is called to initialize the consumer, providing the ASTContext.
Definition: ASTConsumer.h:47
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
void setASTMutationListener(ASTMutationListener *Listener)
Attach an AST mutation listener to the AST context.
Definition: ASTContext.h:1212
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Definition: ASTContext.cpp:947
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:114
RAII object to temporarily add an AST callback listener.
Definition: ASTReader.h:1702
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:366
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1615
@ ARR_None
The client can't handle any AST loading failures.
Definition: ASTReader.h:1611
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1628
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
Definition: ASTReader.h:1619
@ ARR_TreatModuleWithErrorsAsOutOfDate
If a module file is marked with errors treat it as out-of-date so the caller can rebuild it.
Definition: ASTReader.h:1632
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
Definition: ASTReader.cpp:5397
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:384
@ Success
The control block was read successfully.
Definition: ASTReader.h:387
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:404
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:397
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:390
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:400
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:407
@ Missing
The AST file was missing.
Definition: ASTReader.h:393
ChainedDiagnosticConsumer - Chain two diagnostic clients so that diagnostics go to the first client a...
Abstract interface for a consumer of code-completion information.
Options controlling the behavior of code completion.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
CodeGenOptions & getCodeGenOpts()
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
void createPCHExternalASTSource(StringRef Path, DisableValidationForModuleKind DisableValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener)
Create an external AST source to read a PCH file and attach it to the AST context.
void createPreprocessor(TranslationUnitKind TUKind)
Create the preprocessor, using the invocation, file, and source managers, and replace any existing on...
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
Check global module index for missing imports.
void createSourceManager(FileManager &FileMgr)
Create the source manager and replace any existing one with it.
CompilerInvocation & getInvocation()
void createDiagnostics(DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
FileManager * createFileManager(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Create the file manager and replace any existing one with it.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
std::shared_ptr< FailedModulesSet > getFailedModulesSetPtr() const
TargetInfo & getTarget() const
GlobalModuleIndex * loadGlobalModuleIndex(SourceLocation TriggerLoc) override
Load, create, or return global module.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
void setExternalSemaSource(IntrusiveRefCntPtr< ExternalSemaSource > ESS)
std::string getSpecificModuleCachePath()
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
FrontendOptions & getFrontendOpts()
void setInvocation(std::shared_ptr< CompilerInvocation > Value)
setInvocation - Replace the current invocation.
PreprocessorOptions & getPreprocessorOpts()
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file.
InMemoryModuleCache & getModuleCache() const
DependencyOutputOptions & getDependencyOutputOpts()
void setBuildGlobalModuleIndex(bool Build)
Set the flag indicating whether we should (re)build the global module index.
std::unique_ptr< Sema > takeSema()
void printDiagnosticStats()
At the end of a compilation, print the number of warnings/errors.
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value.
IntrusiveRefCntPtr< ASTReader > getASTReader() const
FileSystemOptions & getFileSystemOpts()
ASTConsumer & getASTConsumer() const
void setTarget(TargetInfo *Value)
Replace the current Target.
void setModuleDepCollector(std::shared_ptr< ModuleDependencyCollector > Collector)
void addDependencyCollector(std::shared_ptr< DependencyCollector > Listener)
void createASTContext()
Create the AST context.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, bool UseTemporary, bool CreateMissingDirectories=false)
Create a new output file, optionally deriving the output path name, and add it to the list of tracked...
ASTContext & getASTContext() const
void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, StringRef Source) override
Attempt to create the given module from the specified source buffer.
SourceManager & getSourceManager() const
Return the current source manager.
TargetInfo * getAuxTarget() const
void setASTContext(ASTContext *Value)
setASTContext - Replace the current AST context.
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
void setASTReader(IntrusiveRefCntPtr< ASTReader > Reader)
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
FileManager & getFileManager() const
Return the current file manager to the caller.
APINotesOptions & getAPINotesOpts()
void createFrontendTimer()
Create the frontend timer and replace any existing one with it.
void setDiagnostics(DiagnosticsEngine *Value)
setDiagnostics - Replace the current diagnostics engine.
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
bool hasFailedModulesSet() const
TargetOptions & getTargetOpts()
void setVerboseOutputStream(raw_ostream &Value)
Replace the current stream for verbose output.
DiagnosticConsumer & getDiagnosticClient() const
HeaderSearchOptions & getHeaderSearchOpts()
raw_ostream & getVerboseOutputStream()
Get the current stream for verbose output.
std::shared_ptr< HeaderSearchOptions > getHeaderSearchOptsPtr() const
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
llvm::vfs::FileSystem & getVirtualFileSystem() const
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
LangOptions & getLangOpts()
void setCodeCompletionConsumer(CodeCompleteConsumer *Value)
setCodeCompletionConsumer - Replace the current code completion consumer; the compiler instance takes...
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
DiagnosticOptions & getDiagnosticOpts()
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
void setAuxTarget(TargetInfo *Value)
Replace the current AuxTarget.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc) override
Make the given module visible.
bool loadModuleFile(StringRef FileName, serialization::ModuleFile *&LoadedModuleFile)
void setPreprocessor(std::shared_ptr< Preprocessor > Value)
Replace the current preprocessor.
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
Helper class for holding the data necessary to invoke the compiler.
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
LangOptions & getLangOpts()
Mutable getters.
FrontendOptions & getFrontendOpts()
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
std::string DOTOutputFile
The file to write GraphViz-formatted header dependencies to.
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
std::string OutputFile
The file to write dependency output to.
std::string HeaderIncludeOutputFile
The file to write header include output to.
unsigned ShowHeaderIncludes
Show header inclusions (-H).
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Definition: Diagnostic.h:1751
unsigned getNumErrors() const
Definition: Diagnostic.h:1760
virtual void finish()
Callback to inform the diagnostic client that processing of all source files has ended.
Definition: Diagnostic.h:1787
unsigned getNumWarnings() const
Definition: Diagnostic.h:1761
Used for handling and querying diagnostic IDs.
Options for controlling the compiler diagnostics engine.
std::string DiagnosticLogFile
The file to log diagnostic output to.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-header-in-module=...
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:193
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1553
bool hasErrorOccurred() const
Definition: Diagnostic.h:849
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
Definition: Diagnostic.cpp:96
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:937
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
Definition: Diagnostic.h:582
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Definition: Diagnostic.h:586
DiagnosticConsumer * getClient()
Definition: Diagnostic.h:578
StringRef getName() const
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
off_t getSize() const
Definition: FileEntry.h:340
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
StringRef getNameAsRequested() const
The name of this FileEntry, as originally requested without applying any remappings for VFS 'use-exte...
Definition: FileEntry.h:68
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:300
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
void AddStats(const FileManager &Other)
Import statistics from a child FileManager and add them to this current FileManager.
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:240
llvm::Expected< FileEntryRef > getSTDIN()
Get the FileEntryRef for stdin, returning an error if stdin cannot be read.
const FileEntry * getVirtualFile(StringRef Filename, off_t Size, time_t ModificationTime)
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:251
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
void PrintStats() const
OptionalDirectoryEntryRef getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:175
llvm::Expected< FileEntryRef > getFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:135
Diagnostic consumer that forwards diagnostics along to an existing, already-initialized diagnostic co...
Definition: Diagnostic.h:1818
Abstract base class for actions which can be performed by the frontend.
virtual void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
bool PrepareToExecute(CompilerInstance &CI)
Prepare the action to execute on the given compiler instance.
llvm::Error Execute()
Set the source manager's main input file, and run the action.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
virtual bool isModelParsingAction() const
Is this action invoked on a model file?
An input file for the front end.
llvm::MemoryBufferRef getBuffer() const
InputKind getKind() const
StringRef getFile() const
FrontendOptions - Options for controlling the behavior of the frontend.
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
unsigned AllowPCMWithCompilerErrors
Output (and read) PCM files regardless of compiler errors.
unsigned BuildingImplicitModuleUsesLock
Whether to use a filesystem lock when building implicit modules.
unsigned ModulesShareFileManager
Whether to share the FileManager when building modules.
std::optional< std::string > AuxTargetCPU
Auxiliary target CPU for CUDA/HIP compilation.
std::string StatsFile
Filename to write statistics to.
std::string OutputFile
The output file, if any.
std::string ActionName
The name of the action to run when using a plugin action.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred,...
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
unsigned DisableFree
Disable memory freeing on exit.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
frontend::ActionKind ProgramAction
The frontend action to perform.
std::optional< std::vector< std::string > > AuxTargetFeatures
Auxiliary target features for CUDA/HIP compilation.
A SourceLocation and its associated SourceManager.
A global index for a set of module files, providing information about the identifiers within those mo...
bool lookupIdentifier(llvm::StringRef Name, HitSet &Hits)
Look for all of the module files with information about the given identifier, e.g....
static llvm::Error writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, llvm::StringRef Path)
Write a global index into the given.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
unsigned ModuleCachePruneInterval
The interval (in seconds) between pruning operations.
std::map< std::string, std::string, std::less<> > PrebuiltModuleFiles
The mapping of module names to prebuilt module files.
std::vector< std::string > PrebuiltModulePaths
The directories used to load prebuilt module files.
unsigned ModulesValidateSystemHeaders
Whether to validate system input files when a module is loaded.
unsigned EnablePrebuiltImplicitModules
Also search for prebuilt implicit modules in the prebuilt module cache path.
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::string ModuleCachePath
The directory used for the module cache.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned ModuleCachePruneAfter
The time (in seconds) after which an unused module file will be considered unused and will,...
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:253
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
void getHeaderMapFileNames(SmallVectorImpl< std::string > &Names) const
Get filenames for all registered header maps.
std::string getPrebuiltImplicitModuleFileName(Module *Module)
Retrieve the name of the prebuilt module file that should be used to load the given module.
std::string getCachedModuleFileName(Module *Module)
Retrieve the name of the cached module file that should be used to load the given module.
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
Definition: HeaderSearch.h:386
std::string getPrebuiltModuleFileName(StringRef ModuleName, bool FileMapOnly=false)
Retrieve the name of the prebuilt module file that should be used to load a module with the given nam...
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:837
One of these records is kept for each identifier that is lexed.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
In-memory cache for modules.
bool isPCMFinal(llvm::StringRef Filename) const
Check whether the PCM is final and has been shown to work.
The kind of a file that we've been handed as an input.
Format getFormat() const
@ FPE_Default
Used internally to represent initial unspecified value.
Definition: LangOptions.h:295
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:289
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:482
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
Definition: LangOptions.h:530
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
Describes the result of attempting to load a module.
Definition: ModuleLoader.h:35
Abstract interface for a module loader.
Definition: ModuleLoader.h:82
bool buildingModule() const
Returns true if this instance is building a module.
Definition: ModuleLoader.h:93
llvm::StringMap< Module * >::const_iterator module_iterator
Definition: ModuleMap.h:735
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
Definition: ModuleMap.cpp:826
module_iterator module_begin() const
Definition: ModuleMap.h:737
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
Definition: ModuleMap.cpp:1330
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
Definition: ModuleMap.h:749
module_iterator module_end() const
Definition: ModuleMap.h:738
FileID getContainingModuleMapFileID(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
Definition: ModuleMap.cpp:1309
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition: ModuleMap.cpp:58
void cacheModuleLoad(const IdentifierInfo &II, Module *M)
Cache a module load. M might be nullptr.
Definition: ModuleMap.h:744
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:676
Module * findSubmodule(StringRef Name) const
Find the submodule with the given name.
Definition: Module.cpp:357
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Module.h:472
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:387
@ Hidden
All of the names in this module are hidden.
Definition: Module.h:389
void print(raw_ostream &OS, unsigned Indent=0, bool Dump=false) const
Print the module map for this module to the given stream.
Definition: Module.cpp:482
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition: Module.h:333
std::string Name
The name of this module.
Definition: Module.h:108
llvm::iterator_range< submodule_iterator > submodules()
Definition: Module.h:783
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition: Module.h:159
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition: Module.h:320
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:666
unsigned HasIncompatibleModuleFile
Whether we tried and failed to load a module file for this module.
Definition: Module.h:309
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition: Module.h:681
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
@ ReplaceAction
Replace the main action.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
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...
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
void resetNonModularOptions()
Reset any options that are not considered when building a module.
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
DisableValidationForModuleKind DisablePCHOrModuleValidation
Whether to disable most of the normal validation performed on precompiled headers and module files.
std::vector< std::pair< std::string, bool > > Macros
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...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
void markClangModuleAsAffecting(Module *M)
Mark the given clang module as affecting the current clang module or translation unit.
SourceManager & getSourceManager() const
HeaderSearch & getHeaderSearchInfo() const
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
bool SetCodeCompletionPoint(FileEntryRef File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Preprocessor.h:285
DiagnosticsEngine & getDiagnostics() const
IdentifierTable & getIdentifierTable()
static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, const Module &M, DiagnosticsEngine &Diags)
Check that the given module is available, producing a diagnostic if not.
FileManager & getFileManager() const
SelectorTable & getSelectorTable()
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
void setPredefines(std::string P)
Set the predefines for this Preprocessor.
Builtin::Context & getBuiltinInfo()
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
A simple code-completion consumer that prints the results it receives in a simple format.
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:462
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition: ASTReader.h:321
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
void setModuleBuildStack(ModuleBuildStack stack)
Set the module build stack.
FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
void setOverridenFilesKeepOriginalName(bool value)
Set true if the SourceManager should report the original file name for contents of files that were ov...
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
FileID getMainFileID() const
Returns the FileID of the main source file.
void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc)
Push an entry to the module build stack.
void overrideFileContents(FileEntryRef SourceFile, const llvm::MemoryBufferRef &Buffer)
Override the contents of the given source file by providing an already-allocated buffer.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
void setMainFileID(FileID FID)
Set the file ID for the main source file.
SrcMgr::CharacteristicKind getFileCharacteristic(SourceLocation Loc) const
Return the file characteristic of the specified source location, indicating whether this is a normal ...
A trivial tuple used to represent a source range.
Exposes information about the current target.
Definition: TargetInfo.h:218
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
Definition: Targets.cpp:815
virtual void setAuxTarget(const TargetInfo *Aux)
Definition: TargetInfo.h:1794
void noSignedCharForObjCBool()
Definition: TargetInfo.h:917
virtual void adjust(DiagnosticsEngine &Diags, LangOptions &Opts)
Set forced language options.
Definition: TargetInfo.cpp:392
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
VerifyDiagnosticConsumer - Create a diagnostic client which will use markers in the input source to c...
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:124
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:81
bool isModuleMap(CharacteristicKind CK)
Determine whether a file characteristic is for a module map.
Definition: SourceManager.h:95
@ PluginAction
Run a plugin action,.
@ RewriteObjC
ObjC->C Rewriter.
bool Inv(InterpState &S, CodePtr OpPC)
Definition: Interp.h:474
@ MK_PCH
File is a PCH file treated as such.
Definition: ModuleFile.h:50
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition: ModuleFile.h:53
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition: ModuleFile.h:47
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition: ModuleFile.h:44
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition: ModuleFile.h:59
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
ASTEdit remove(RangeSelector S)
Removes the source selected by S.
The JSON file list parser is used to communicate input to InstallAPI.
@ OpenCL
Definition: LangStandard.h:65
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
void ApplyHeaderSearchOptions(HeaderSearch &HS, const HeaderSearchOptions &HSOpts, const LangOptions &Lang, const llvm::Triple &triple)
Apply the header search options to get given HeaderSearch object.
void noteBottomOfStack()
Call this once on each thread, as soon after starting the thread as feasible, to note the approximate...
Definition: Stack.cpp:40
void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts, const PCHContainerReader &PCHContainerRdr, const FrontendOptions &FEOpts, const CodeGenOptions &CodeGenOpts)
InitializePreprocessor - Initialize the preprocessor getting it and the environment ready to process ...
std::error_code make_error_code(BuildPreambleError Error)
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition: CharInfo.h:138
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
@ C
Languages that the frontend can parse and compile.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
constexpr size_t DesiredStackSize
The amount of stack space that Clang would like to be provided with.
Definition: Stack.h:26
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1074
void AttachHeaderIncludeGen(Preprocessor &PP, const DependencyOutputOptions &DepOpts, bool ShowAllHeaders=false, StringRef OutputPath={}, bool ShowDepth=true, bool MSStyle=false)
AttachHeaderIncludeGen - Create a header include list generator, and attach it to the given preproces...
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ Other
Other implicit parameter.
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:34
void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile, StringRef SysRoot)
AttachDependencyGraphGen - Create a dependency graph generator, and attach it to the given preprocess...
Definition: Format.h:5433
float __ovld __cnfn normalize(float)
Returns a vector in the same direction as p but with a length of 1.
A source location that has been parsed on the command line.