clang  10.0.0git
CompilerInstance.h
Go to the documentation of this file.
1 //===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
10 #define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
11 
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Frontend/Utils.h"
19 #include "clang/Lex/ModuleLoader.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/IntrusiveRefCntPtr.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/BuryPointer.h"
25 #include <cassert>
26 #include <list>
27 #include <memory>
28 #include <string>
29 #include <utility>
30 
31 namespace llvm {
32 class raw_fd_ostream;
33 class Timer;
34 class TimerGroup;
35 }
36 
37 namespace clang {
38 class ASTContext;
39 class ASTReader;
40 class CodeCompleteConsumer;
41 class DiagnosticsEngine;
42 class DiagnosticConsumer;
43 class ExternalASTSource;
44 class FileEntry;
45 class FileManager;
46 class FrontendAction;
47 class InMemoryModuleCache;
48 class Module;
49 class Preprocessor;
50 class Sema;
51 class SourceManager;
52 class TargetInfo;
53 
54 /// CompilerInstance - Helper class for managing a single instance of the Clang
55 /// compiler.
56 ///
57 /// The CompilerInstance serves two purposes:
58 /// (1) It manages the various objects which are necessary to run the compiler,
59 /// for example the preprocessor, the target information, and the AST
60 /// context.
61 /// (2) It provides utility routines for constructing and manipulating the
62 /// common Clang objects.
63 ///
64 /// The compiler instance generally owns the instance of all the objects that it
65 /// manages. However, clients can still share objects by manually setting the
66 /// object and retaking ownership prior to destroying the CompilerInstance.
67 ///
68 /// The compiler instance is intended to simplify clients, but not to lock them
69 /// in to the compiler instance for everything. When possible, utility functions
70 /// come in two forms; a short form that reuses the CompilerInstance objects,
71 /// and a long form that takes explicit instances of any required objects.
73  /// The options used in this compiler instance.
74  std::shared_ptr<CompilerInvocation> Invocation;
75 
76  /// The diagnostics engine instance.
78 
79  /// The target being compiled for.
81 
82  /// Auxiliary Target info.
84 
85  /// The file manager.
87 
88  /// The source manager.
90 
91  /// The cache of PCM files.
93 
94  /// The preprocessor.
95  std::shared_ptr<Preprocessor> PP;
96 
97  /// The AST context.
99 
100  /// An optional sema source that will be attached to sema.
102 
103  /// The AST consumer.
104  std::unique_ptr<ASTConsumer> Consumer;
105 
106  /// The code completion consumer.
107  std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
108 
109  /// The semantic analysis object.
110  std::unique_ptr<Sema> TheSema;
111 
112  /// The frontend timer group.
113  std::unique_ptr<llvm::TimerGroup> FrontendTimerGroup;
114 
115  /// The frontend timer.
116  std::unique_ptr<llvm::Timer> FrontendTimer;
117 
118  /// The ASTReader, if one exists.
119  IntrusiveRefCntPtr<ASTReader> TheASTReader;
120 
121  /// The module dependency collector for crashdumps
122  std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
123 
124  /// The module provider.
125  std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
126 
127  std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
128 
129  /// The set of top-level modules that has already been built on the
130  /// fly as part of this overall compilation action.
131  std::map<std::string, std::string> BuiltModules;
132 
133  /// Should we delete the BuiltModules when we're done?
134  bool DeleteBuiltModules = true;
135 
136  /// The location of the module-import keyword for the last module
137  /// import.
138  SourceLocation LastModuleImportLoc;
139 
140  /// The result of the last module import.
141  ///
142  ModuleLoadResult LastModuleImportResult;
143 
144  /// Whether we should (re)build the global module index once we
145  /// have finished with this translation unit.
146  bool BuildGlobalModuleIndex = false;
147 
148  /// We have a full global module index, with all modules.
149  bool HaveFullGlobalModuleIndex = false;
150 
151  /// One or more modules failed to build.
152  bool ModuleBuildFailed = false;
153 
154  /// The stream for verbose output if owned, otherwise nullptr.
155  std::unique_ptr<raw_ostream> OwnedVerboseOutputStream;
156 
157  /// The stream for verbose output.
158  raw_ostream *VerboseOutputStream = &llvm::errs();
159 
160  /// Holds information about the output file.
161  ///
162  /// If TempFilename is not empty we must rename it to Filename at the end.
163  /// TempFilename may be empty and Filename non-empty if creating the temporary
164  /// failed.
165  struct OutputFile {
166  std::string Filename;
167  std::string TempFilename;
168 
169  OutputFile(std::string filename, std::string tempFilename)
170  : Filename(std::move(filename)), TempFilename(std::move(tempFilename)) {
171  }
172  };
173 
174  /// If the output doesn't support seeking (terminal, pipe). we switch
175  /// the stream to a buffer_ostream. These are the buffer and the original
176  /// stream.
177  std::unique_ptr<llvm::raw_fd_ostream> NonSeekStream;
178 
179  /// The list of active output files.
180  std::list<OutputFile> OutputFiles;
181 
182  /// Force an output buffer.
183  std::unique_ptr<llvm::raw_pwrite_stream> OutputStream;
184 
185  CompilerInstance(const CompilerInstance &) = delete;
186  void operator=(const CompilerInstance &) = delete;
187 public:
188  explicit CompilerInstance(
189  std::shared_ptr<PCHContainerOperations> PCHContainerOps =
190  std::make_shared<PCHContainerOperations>(),
191  InMemoryModuleCache *SharedModuleCache = nullptr);
192  ~CompilerInstance() override;
193 
194  /// @name High-Level Operations
195  /// {
196 
197  /// ExecuteAction - Execute the provided action against the compiler's
198  /// CompilerInvocation object.
199  ///
200  /// This function makes the following assumptions:
201  ///
202  /// - The invocation options should be initialized. This function does not
203  /// handle the '-help' or '-version' options, clients should handle those
204  /// directly.
205  ///
206  /// - The diagnostics engine should have already been created by the client.
207  ///
208  /// - No other CompilerInstance state should have been initialized (this is
209  /// an unchecked error).
210  ///
211  /// - Clients should have initialized any LLVM target features that may be
212  /// required.
213  ///
214  /// - Clients should eventually call llvm_shutdown() upon the completion of
215  /// this routine to ensure that any managed objects are properly destroyed.
216  ///
217  /// Note that this routine may write output to 'stderr'.
218  ///
219  /// \param Act - The action to execute.
220  /// \return - True on success.
221  //
222  // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
223  // of the context or else not CompilerInstance specific.
224  bool ExecuteAction(FrontendAction &Act);
225 
226  /// }
227  /// @name Compiler Invocation and Options
228  /// {
229 
230  bool hasInvocation() const { return Invocation != nullptr; }
231 
233  assert(Invocation && "Compiler instance has no invocation!");
234  return *Invocation;
235  }
236 
237  /// setInvocation - Replace the current invocation.
238  void setInvocation(std::shared_ptr<CompilerInvocation> Value);
239 
240  /// Indicates whether we should (re)build the global module index.
241  bool shouldBuildGlobalModuleIndex() const;
242 
243  /// Set the flag indicating whether we should (re)build the global
244  /// module index.
245  void setBuildGlobalModuleIndex(bool Build) {
246  BuildGlobalModuleIndex = Build;
247  }
248 
249  /// }
250  /// @name Forwarding Methods
251  /// {
252 
254  return Invocation->getAnalyzerOpts();
255  }
256 
258  return Invocation->getCodeGenOpts();
259  }
261  return Invocation->getCodeGenOpts();
262  }
263 
265  return Invocation->getDependencyOutputOpts();
266  }
268  return Invocation->getDependencyOutputOpts();
269  }
270 
272  return Invocation->getDiagnosticOpts();
273  }
275  return Invocation->getDiagnosticOpts();
276  }
277 
279  return Invocation->getFileSystemOpts();
280  }
282  return Invocation->getFileSystemOpts();
283  }
284 
286  return Invocation->getFrontendOpts();
287  }
289  return Invocation->getFrontendOpts();
290  }
291 
293  return Invocation->getHeaderSearchOpts();
294  }
296  return Invocation->getHeaderSearchOpts();
297  }
298  std::shared_ptr<HeaderSearchOptions> getHeaderSearchOptsPtr() const {
299  return Invocation->getHeaderSearchOptsPtr();
300  }
301 
303  return *Invocation->getLangOpts();
304  }
305  const LangOptions &getLangOpts() const {
306  return *Invocation->getLangOpts();
307  }
308 
310  return Invocation->getPreprocessorOpts();
311  }
313  return Invocation->getPreprocessorOpts();
314  }
315 
317  return Invocation->getPreprocessorOutputOpts();
318  }
320  return Invocation->getPreprocessorOutputOpts();
321  }
322 
324  return Invocation->getTargetOpts();
325  }
326  const TargetOptions &getTargetOpts() const {
327  return Invocation->getTargetOpts();
328  }
329 
330  /// }
331  /// @name Diagnostics Engine
332  /// {
333 
334  bool hasDiagnostics() const { return Diagnostics != nullptr; }
335 
336  /// Get the current diagnostics engine.
338  assert(Diagnostics && "Compiler instance has no diagnostics!");
339  return *Diagnostics;
340  }
341 
342  /// setDiagnostics - Replace the current diagnostics engine.
343  void setDiagnostics(DiagnosticsEngine *Value);
344 
346  assert(Diagnostics && Diagnostics->getClient() &&
347  "Compiler instance has no diagnostic client!");
348  return *Diagnostics->getClient();
349  }
350 
351  /// }
352  /// @name VerboseOutputStream
353  /// }
354 
355  /// Replace the current stream for verbose output.
356  void setVerboseOutputStream(raw_ostream &Value);
357 
358  /// Replace the current stream for verbose output.
359  void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
360 
361  /// Get the current stream for verbose output.
362  raw_ostream &getVerboseOutputStream() {
363  return *VerboseOutputStream;
364  }
365 
366  /// }
367  /// @name Target Info
368  /// {
369 
370  bool hasTarget() const { return Target != nullptr; }
371 
373  assert(Target && "Compiler instance has no target!");
374  return *Target;
375  }
376 
377  /// Replace the current Target.
378  void setTarget(TargetInfo *Value);
379 
380  /// }
381  /// @name AuxTarget Info
382  /// {
383 
384  TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
385 
386  /// Replace the current AuxTarget.
387  void setAuxTarget(TargetInfo *Value);
388 
389  /// }
390  /// @name Virtual File System
391  /// {
392 
393  llvm::vfs::FileSystem &getVirtualFileSystem() const {
394  return getFileManager().getVirtualFileSystem();
395  }
396 
397  /// }
398  /// @name File Manager
399  /// {
400 
401  bool hasFileManager() const { return FileMgr != nullptr; }
402 
403  /// Return the current file manager to the caller.
405  assert(FileMgr && "Compiler instance has no file manager!");
406  return *FileMgr;
407  }
408 
410  llvm::BuryPointer(FileMgr.get());
411  FileMgr.resetWithoutRelease();
412  }
413 
414  /// Replace the current file manager and virtual file system.
415  void setFileManager(FileManager *Value);
416 
417  /// }
418  /// @name Source Manager
419  /// {
420 
421  bool hasSourceManager() const { return SourceMgr != nullptr; }
422 
423  /// Return the current source manager.
425  assert(SourceMgr && "Compiler instance has no source manager!");
426  return *SourceMgr;
427  }
428 
430  llvm::BuryPointer(SourceMgr.get());
431  SourceMgr.resetWithoutRelease();
432  }
433 
434  /// setSourceManager - Replace the current source manager.
435  void setSourceManager(SourceManager *Value);
436 
437  /// }
438  /// @name Preprocessor
439  /// {
440 
441  bool hasPreprocessor() const { return PP != nullptr; }
442 
443  /// Return the current preprocessor.
445  assert(PP && "Compiler instance has no preprocessor!");
446  return *PP;
447  }
448 
449  std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; }
450 
452  llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP));
453  }
454 
455  /// Replace the current preprocessor.
456  void setPreprocessor(std::shared_ptr<Preprocessor> Value);
457 
458  /// }
459  /// @name ASTContext
460  /// {
461 
462  bool hasASTContext() const { return Context != nullptr; }
463 
465  assert(Context && "Compiler instance has no AST context!");
466  return *Context;
467  }
468 
470  llvm::BuryPointer(Context.get());
471  Context.resetWithoutRelease();
472  }
473 
474  /// setASTContext - Replace the current AST context.
475  void setASTContext(ASTContext *Value);
476 
477  /// Replace the current Sema; the compiler instance takes ownership
478  /// of S.
479  void setSema(Sema *S);
480 
481  /// }
482  /// @name ASTConsumer
483  /// {
484 
485  bool hasASTConsumer() const { return (bool)Consumer; }
486 
488  assert(Consumer && "Compiler instance has no AST consumer!");
489  return *Consumer;
490  }
491 
492  /// takeASTConsumer - Remove the current AST consumer and give ownership to
493  /// the caller.
494  std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
495 
496  /// setASTConsumer - Replace the current AST consumer; the compiler instance
497  /// takes ownership of \p Value.
498  void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
499 
500  /// }
501  /// @name Semantic analysis
502  /// {
503  bool hasSema() const { return (bool)TheSema; }
504 
505  Sema &getSema() const {
506  assert(TheSema && "Compiler instance has no Sema object!");
507  return *TheSema;
508  }
509 
510  std::unique_ptr<Sema> takeSema();
511  void resetAndLeakSema();
512 
513  /// }
514  /// @name Module Management
515  /// {
516 
517  IntrusiveRefCntPtr<ASTReader> getASTReader() const;
518  void setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader);
519 
520  std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
521  void setModuleDepCollector(
522  std::shared_ptr<ModuleDependencyCollector> Collector);
523 
524  std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
525  return ThePCHContainerOperations;
526  }
527 
528  /// Return the appropriate PCHContainerWriter depending on the
529  /// current CodeGenOptions.
531  assert(Invocation && "cannot determine module format without invocation");
532  StringRef Format = getHeaderSearchOpts().ModuleFormat;
533  auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
534  if (!Writer) {
535  if (Diagnostics)
536  Diagnostics->Report(diag::err_module_format_unhandled) << Format;
537  llvm::report_fatal_error("unknown module format");
538  }
539  return *Writer;
540  }
541 
542  /// Return the appropriate PCHContainerReader depending on the
543  /// current CodeGenOptions.
545  assert(Invocation && "cannot determine module format without invocation");
546  StringRef Format = getHeaderSearchOpts().ModuleFormat;
547  auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
548  if (!Reader) {
549  if (Diagnostics)
550  Diagnostics->Report(diag::err_module_format_unhandled) << Format;
551  llvm::report_fatal_error("unknown module format");
552  }
553  return *Reader;
554  }
555 
556  /// }
557  /// @name Code Completion
558  /// {
559 
560  bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
561 
563  assert(CompletionConsumer &&
564  "Compiler instance has no code completion consumer!");
565  return *CompletionConsumer;
566  }
567 
568  /// setCodeCompletionConsumer - Replace the current code completion consumer;
569  /// the compiler instance takes ownership of \p Value.
570  void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
571 
572  /// }
573  /// @name Frontend timer
574  /// {
575 
576  bool hasFrontendTimer() const { return (bool)FrontendTimer; }
577 
578  llvm::Timer &getFrontendTimer() const {
579  assert(FrontendTimer && "Compiler instance has no frontend timer!");
580  return *FrontendTimer;
581  }
582 
583  /// }
584  /// @name Output Files
585  /// {
586 
587  /// addOutputFile - Add an output file onto the list of tracked output files.
588  ///
589  /// \param OutFile - The output file info.
590  void addOutputFile(OutputFile &&OutFile);
591 
592  /// clearOutputFiles - Clear the output file list. The underlying output
593  /// streams must have been closed beforehand.
594  ///
595  /// \param EraseFiles - If true, attempt to erase the files from disk.
596  void clearOutputFiles(bool EraseFiles);
597 
598  /// }
599  /// @name Construction Utility Methods
600  /// {
601 
602  /// Create the diagnostics engine using the invocation's diagnostic options
603  /// and replace any existing one with it.
604  ///
605  /// Note that this routine also replaces the diagnostic client,
606  /// allocating one if one is not provided.
607  ///
608  /// \param Client If non-NULL, a diagnostic client that will be
609  /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
610  /// unit.
611  ///
612  /// \param ShouldOwnClient If Client is non-NULL, specifies whether
613  /// the diagnostic object should take ownership of the client.
614  void createDiagnostics(DiagnosticConsumer *Client = nullptr,
615  bool ShouldOwnClient = true);
616 
617  /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
618  ///
619  /// If no diagnostic client is provided, this creates a
620  /// DiagnosticConsumer that is owned by the returned diagnostic
621  /// object, if using directly the caller is responsible for
622  /// releasing the returned DiagnosticsEngine's client eventually.
623  ///
624  /// \param Opts - The diagnostic options; note that the created text
625  /// diagnostic object contains a reference to these options.
626  ///
627  /// \param Client If non-NULL, a diagnostic client that will be
628  /// attached to (and, then, owned by) the returned DiagnosticsEngine
629  /// object.
630  ///
631  /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
632  /// used by some diagnostics printers (for logging purposes only).
633  ///
634  /// \return The new object on success, or null on failure.
636  createDiagnostics(DiagnosticOptions *Opts,
637  DiagnosticConsumer *Client = nullptr,
638  bool ShouldOwnClient = true,
639  const CodeGenOptions *CodeGenOpts = nullptr);
640 
641  /// Create the file manager and replace any existing one with it.
642  ///
643  /// \return The new file manager on success, or null on failure.
644  FileManager *
645  createFileManager(IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
646 
647  /// Create the source manager and replace any existing one with it.
648  void createSourceManager(FileManager &FileMgr);
649 
650  /// Create the preprocessor, using the invocation, file, and source managers,
651  /// and replace any existing one with it.
652  void createPreprocessor(TranslationUnitKind TUKind);
653 
654  std::string getSpecificModuleCachePath();
655 
656  /// Create the AST context.
657  void createASTContext();
658 
659  /// Create an external AST source to read a PCH file and attach it to the AST
660  /// context.
661  void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation,
662  bool AllowPCHWithCompilerErrors,
663  void *DeserializationListener,
664  bool OwnDeserializationListener);
665 
666  /// Create an external AST source to read a PCH file.
667  ///
668  /// \return - The new object on success, or null on failure.
669  static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
670  StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
671  bool AllowPCHWithCompilerErrors, Preprocessor &PP,
672  InMemoryModuleCache &ModuleCache, ASTContext &Context,
673  const PCHContainerReader &PCHContainerRdr,
674  ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
675  ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
676  void *DeserializationListener, bool OwnDeserializationListener,
677  bool Preamble, bool UseGlobalModuleIndex);
678 
679  /// Create a code completion consumer using the invocation; note that this
680  /// will cause the source manager to truncate the input source file at the
681  /// completion point.
682  void createCodeCompletionConsumer();
683 
684  /// Create a code completion consumer to print code completion results, at
685  /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
686  static CodeCompleteConsumer *createCodeCompletionConsumer(
687  Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
688  const CodeCompleteOptions &Opts, raw_ostream &OS);
689 
690  /// Create the Sema object to be used for parsing.
691  void createSema(TranslationUnitKind TUKind,
692  CodeCompleteConsumer *CompletionConsumer);
693 
694  /// Create the frontend timer and replace any existing one with it.
695  void createFrontendTimer();
696 
697  /// Create the default output file (from the invocation's options) and add it
698  /// to the list of tracked output files.
699  ///
700  /// The files created by this function always use temporary files to write to
701  /// their result (that is, the data is written to a temporary file which will
702  /// atomically replace the target output on success).
703  ///
704  /// \return - Null on error.
705  std::unique_ptr<raw_pwrite_stream>
706  createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
707  StringRef Extension = "");
708 
709  /// Create a new output file and add it to the list of tracked output files,
710  /// optionally deriving the output path name.
711  ///
712  /// \return - Null on error.
713  std::unique_ptr<raw_pwrite_stream>
714  createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
715  StringRef BaseInput, StringRef Extension, bool UseTemporary,
716  bool CreateMissingDirectories = false);
717 
718  /// Create a new output file, optionally deriving the output path name.
719  ///
720  /// If \p OutputPath is empty, then createOutputFile will derive an output
721  /// path location as \p BaseInput, with any suffix removed, and \p Extension
722  /// appended. If \p OutputPath is not stdout and \p UseTemporary
723  /// is true, createOutputFile will create a new temporary file that must be
724  /// renamed to \p OutputPath in the end.
725  ///
726  /// \param OutputPath - If given, the path to the output file.
727  /// \param Error [out] - On failure, the error.
728  /// \param BaseInput - If \p OutputPath is empty, the input path name to use
729  /// for deriving the output path.
730  /// \param Extension - The extension to use for derived output names.
731  /// \param Binary - The mode to open the file in.
732  /// \param RemoveFileOnSignal - Whether the file should be registered with
733  /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
734  /// multithreaded use, as the underlying signal mechanism is not reentrant
735  /// \param UseTemporary - Create a new temporary file that must be renamed to
736  /// OutputPath in the end.
737  /// \param CreateMissingDirectories - When \p UseTemporary is true, create
738  /// missing directories in the output path.
739  /// \param ResultPathName [out] - If given, the result path name will be
740  /// stored here on success.
741  /// \param TempPathName [out] - If given, the temporary file path name
742  /// will be stored here on success.
743  std::unique_ptr<raw_pwrite_stream>
744  createOutputFile(StringRef OutputPath, std::error_code &Error, bool Binary,
745  bool RemoveFileOnSignal, StringRef BaseInput,
746  StringRef Extension, bool UseTemporary,
747  bool CreateMissingDirectories, std::string *ResultPathName,
748  std::string *TempPathName);
749 
750  std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
751 
752  /// }
753  /// @name Initialization Utility Methods
754  /// {
755 
756  /// InitializeSourceManager - Initialize the source manager to set InputFile
757  /// as the main file.
758  ///
759  /// \return True on success.
760  bool InitializeSourceManager(const FrontendInputFile &Input);
761 
762  /// InitializeSourceManager - Initialize the source manager to set InputFile
763  /// as the main file.
764  ///
765  /// \return True on success.
766  static bool InitializeSourceManager(const FrontendInputFile &Input,
767  DiagnosticsEngine &Diags,
768  FileManager &FileMgr,
769  SourceManager &SourceMgr,
770  HeaderSearch *HS,
771  DependencyOutputOptions &DepOpts,
772  const FrontendOptions &Opts);
773 
774  /// }
775 
776  void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) {
777  OutputStream = std::move(OutStream);
778  }
779 
780  std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() {
781  return std::move(OutputStream);
782  }
783 
784  // Create module manager.
785  void createASTReader();
786 
787  bool loadModuleFile(StringRef FileName);
788 
789 private:
790  /// Find a module, potentially compiling it, before reading its AST. This is
791  /// the guts of loadModule.
792  ///
793  /// For prebuilt modules, the Module is not expected to exist in
794  /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the
795  /// ModuleManager, then it will be loaded and looked up.
796  ///
797  /// For implicit modules, the Module is expected to already be in the
798  /// ModuleMap. First attempt to load it from the given path on disk. If that
799  /// fails, defer to compileModuleAndReadAST, which will first build and then
800  /// load it.
801  ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
802  SourceLocation ImportLoc,
803  SourceLocation ModuleNameLoc,
804  bool IsInclusionDirective);
805 
806 public:
807  ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
809  bool IsInclusionDirective) override;
810 
811  void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName,
812  StringRef Source) override;
813 
814  void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
815  SourceLocation ImportLoc) override;
816 
818  return ModuleLoader::HadFatalFailure;
819  }
820 
821  GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override;
822 
823  bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
824 
825  void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
826  DependencyCollectors.push_back(std::move(Listener));
827  }
828 
829  void setExternalSemaSource(IntrusiveRefCntPtr<ExternalSemaSource> ESS);
830 
831  InMemoryModuleCache &getModuleCache() const { return *ModuleCache; }
832 };
833 
834 } // end namespace clang
835 
836 #endif
LangOptions & getLangOpts()
CompilerInvocation & getInvocation()
PreprocessorOptions & getPreprocessorOpts()
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:171
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs...
Definition: ASTConsumer.h:33
const TargetOptions & getTargetOpts() const
Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be placed into a PointerUnion...
Definition: Dominators.h:30
Defines the SourceManager interface.
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
Abstract base class for actions which can be performed by the frontend.
DiagnosticOptions & getDiagnosticOpts()
std::shared_ptr< HeaderSearchOptions > getHeaderSearchOptsPtr() const
const HeaderSearchOptions & getHeaderSearchOpts() const
static ASTReader * createASTReader(CompilerInstance &CI, StringRef pchFile, SmallVectorImpl< std::unique_ptr< llvm::MemoryBuffer >> &MemBufs, SmallVectorImpl< std::string > &bufNames, ASTDeserializationListener *deserialListener=nullptr)
InMemoryModuleCache & getModuleCache() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
ASTContext & getASTContext() const
const FrontendOptions & getFrontendOpts() const
Options for controlling the target.
Definition: TargetOptions.h:26
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Definition: Diagnostic.h:1499
DependencyOutputOptions & getDependencyOutputOpts()
const FileSystemOptions & getFileSystemOpts() const
const DependencyOutputOptions & getDependencyOutputOpts() const
void setOutputStream(std::unique_ptr< llvm::raw_pwrite_stream > OutStream)
}
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
raw_ostream & getVerboseOutputStream()
Get the current stream for verbose output.
CodeGenOptions & getCodeGenOpts()
const PreprocessorOutputOptions & getPreprocessorOutputOpts() const
std::shared_ptr< Preprocessor > getPreprocessorPtr()
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:53
Describes a module or submodule.
Definition: Module.h:64
const PCHContainerWriter & getPCHContainerWriter() const
Return the appropriate PCHContainerWriter depending on the current CodeGenOptions.
void setBuildGlobalModuleIndex(bool Build)
Set the flag indicating whether we should (re)build the global module index.
This abstract interface provides operations for creating containers for serialized ASTs (precompiled ...
FrontendOptions & getFrontendOpts()
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:33
PreprocessorOutputOptions & getPreprocessorOutputOpts()
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
ASTConsumer & getASTConsumer() const
llvm::Error Error
Defines the Diagnostic-related interfaces.
HeaderSearchOptions & getHeaderSearchOpts()
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
AnalyzerOptionsRef getAnalyzerOpts()
CodeCompleteConsumer & getCodeCompletionConsumer() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
Encapsulates the information needed to find the file referenced by a #include or #include_next, (sub-)framework lookup, etc.
Definition: HeaderSearch.h:158
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:336
Describes the result of attempting to load a module.
Definition: ModuleLoader.h:35
StringRef Filename
Definition: Format.cpp:1825
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g., -E).
Exposes information about the current target.
Definition: TargetInfo.h:164
void addDependencyCollector(std::shared_ptr< DependencyCollector > Listener)
const AnnotatedLine * Line
TargetInfo * getAuxTarget() const
const CodeGenOptions & getCodeGenOpts() const
An input file for the front end.
In-memory cache for modules.
FileSystemOptions & getFileSystemOpts()
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
Options for controlling the compiler diagnostics engine.
const DiagnosticOptions & getDiagnosticOpts() const
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
const PreprocessorOptions & getPreprocessorOpts() const
A global index for a set of module files, providing information about the identifiers within those mo...
Abstract interface for a consumer of code-completion information.
Options controlling the behavior of code completion.
Dataflow Directional Tag Classes.
FileManager & getFileManager() const
Return the current file manager to the caller.
llvm::Timer & getFrontendTimer() const
Helper class for holding the data necessary to invoke the compiler.
SourceManager & getSourceManager() const
Return the current source manager.
FrontendOptions - Options for controlling the behavior of the frontend.
Abstract interface for a module loader.
Definition: ModuleLoader.h:80
TargetInfo & getTarget() const
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
const LangOptions & getLangOpts() const
Keeps track of options that affect how file operations are performed.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
bool hasCodeCompletionConsumer() const
DiagnosticConsumer & getDiagnosticClient() const
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:412
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
bool hadModuleLoaderFatalFailure() const
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:273
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
TargetOptions & getTargetOpts()
This class handles loading and caching of source files into memory.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128