9#ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
10#define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/IntrusiveRefCntPtr.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Support/BuryPointer.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/LibraryOptionsContext.h"
30#include "llvm/Support/VirtualFileSystem.h"
31#include "llvm/Support/VirtualOutputBackend.h"
87 std::shared_ptr<CompilerInvocation> Invocation;
99 std::unique_ptr<TargetOptions> AuxTargetOpts;
114 std::shared_ptr<ModuleCache> ModCache;
119 std::vector<std::string> InheritedDirectoryDependencies;
122 std::unique_ptr<DependencyDirectivesGetter> GetDependencyDirectives;
125 std::shared_ptr<Preprocessor> PP;
134 std::unique_ptr<ASTConsumer> Consumer;
137 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
140 std::unique_ptr<Sema> TheSema;
143 std::vector<std::unique_ptr<llvm::PassPlugin>> PassPlugins;
146 std::unique_ptr<llvm::TimerGroup> timerGroup;
149 std::unique_ptr<llvm::Timer> FrontendTimer;
153 llvm::cl::LibraryOptionsContext LibraryOptions;
159 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
162 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
164 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
172 llvm::StringSet<> FailedModules;
176 std::map<std::string, std::string, std::less<>> BuiltModules;
179 bool DeleteBuiltModules =
true;
184 llvm::SmallDenseMap<SourceLocation, ModuleLoadResult, 4> ModuleImportResults;
188 bool BuildGlobalModuleIndex =
false;
191 bool HaveFullGlobalModuleIndex =
false;
194 bool DisableGeneratingGlobalModuleIndex =
false;
197 std::unique_ptr<raw_ostream> OwnedVerboseOutputStream;
200 raw_ostream *VerboseOutputStream = &llvm::errs();
203 std::list<llvm::vfs::OutputFile> OutputFiles;
206 std::unique_ptr<llvm::raw_pwrite_stream> OutputStream;
208 using GenModuleActionWrapperFunc =
214 GenModuleActionWrapperFunc GenModuleActionWrapper;
216 CompilerInstance(
const CompilerInstance &) =
delete;
217 void operator=(
const CompilerInstance &) =
delete;
219 explicit CompilerInstance(
220 std::shared_ptr<CompilerInvocation> Invocation =
221 std::make_shared<CompilerInvocation>(),
222 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
223 std::make_shared<PCHContainerOperations>(),
224 std::shared_ptr<ModuleCache> ModCache =
nullptr);
278 return LibraryOptions;
295 BuildGlobalModuleIndex = Build;
305 return Invocation->getCodeGenOpts();
308 return Invocation->getCodeGenOpts();
312 return Invocation->getDependencyOutputOpts();
315 return Invocation->getDependencyOutputOpts();
319 return Invocation->getDiagnosticOpts();
322 return Invocation->getDiagnosticOpts();
326 return Invocation->getFileSystemOpts();
329 return Invocation->getFileSystemOpts();
333 return Invocation->getFrontendOpts();
336 return Invocation->getFrontendOpts();
341 return Invocation->getSSAFOpts();
345 return Invocation->getHeaderSearchOpts();
348 return Invocation->getHeaderSearchOpts();
353 return Invocation->getAPINotesOpts();
360 return Invocation->getPreprocessorOpts();
363 return Invocation->getPreprocessorOpts();
367 return Invocation->getPreprocessorOutputOpts();
370 return Invocation->getPreprocessorOutputOpts();
374 return Invocation->getTargetOpts();
377 return Invocation->getTargetOpts();
388 assert(Diagnostics &&
"Compiler instance has no diagnostics!");
393 assert(Diagnostics &&
"Compiler instance has no diagnostics!");
401 assert(Diagnostics && Diagnostics->getClient() &&
402 "Compiler instance has no diagnostic client!");
403 return *Diagnostics->getClient();
418 return *VerboseOutputStream;
428 assert(Target &&
"Compiler instance has no target!");
433 assert(Target &&
"Compiler instance has no target!");
468 BaseFS = llvm::vfs::getRealFileSystem(),
490 assert(FileMgr &&
"Compiler instance has no file manager!");
495 assert(FileMgr &&
"Compiler instance has no file manager!");
500 llvm::BuryPointer(FileMgr.get());
501 FileMgr.resetWithoutRelease();
531 assert(SourceMgr &&
"Compiler instance has no source manager!");
536 assert(SourceMgr &&
"Compiler instance has no source manager!");
541 llvm::BuryPointer(SourceMgr.get());
542 SourceMgr.resetWithoutRelease();
556 assert(PP &&
"Compiler instance has no preprocessor!");
563 llvm::BuryPointer(
new std::shared_ptr<Preprocessor>(PP));
576 assert(Context &&
"Compiler instance has no AST context!");
583 llvm::BuryPointer(Context.get());
584 Context.resetWithoutRelease();
601 assert(Consumer &&
"Compiler instance has no AST consumer!");
616 bool hasSema()
const {
return (
bool)TheSema; }
619 assert(TheSema &&
"Compiler instance has no Sema object!");
635 std::shared_ptr<ModuleDependencyCollector> Collector);
638 return ThePCHContainerOperations;
644 assert(Invocation &&
"cannot determine module format without invocation");
646 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
649 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
650 llvm::report_fatal_error(
"unknown module format");
658 assert(Invocation &&
"cannot determine module format without invocation");
660 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
663 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
664 llvm::report_fatal_error(
"unknown module format");
676 assert(CompletionConsumer &&
677 "Compiler instance has no code completion consumer!");
678 return *CompletionConsumer;
700 assert(FrontendTimer &&
"Compiler instance has no frontend timer!");
701 return *FrontendTimer;
731 bool ShouldOwnClient =
true);
757 bool ShouldOwnClient =
true,
771 std::unique_ptr<DependencyDirectivesGetter> Getter) {
772 GetDependencyDirectives = std::move(Getter);
782 bool AllowPCHWithCompilerErrors,
void *DeserializationListener,
783 bool OwnDeserializationListener);
789 StringRef Path, StringRef Sysroot,
794 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
795 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
796 void *DeserializationListener,
bool OwnDeserializationListener,
797 bool Preamble,
bool UseGlobalModuleIndex);
827 bool Binary =
true, StringRef BaseInput =
"", StringRef Extension =
"",
828 bool RemoveFileOnSignal =
true,
bool CreateMissingDirectories =
false,
829 bool ForceUseTemporary =
false,
bool SetOnlyIfDifferent =
false);
835 std::unique_ptr<raw_pwrite_stream>
837 bool UseTemporary,
bool CreateMissingDirectories =
false,
838 bool SetOnlyIfDifferent =
false);
846 void PrepareForExecution();
866 createOutputFileImpl(StringRef OutputPath,
bool Binary,
867 bool RemoveFileOnSignal,
bool UseTemporary,
868 bool CreateMissingDirectories,
bool SetOnlyIfDifferent);
895 OutputStream = std::move(OutStream);
899 return std::move(OutputStream);
912 std::shared_ptr<ModuleCache> ModCache;
913 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
919 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector =
nullptr)
920 : VFS(
std::move(VFS)), DiagConsumer(DiagConsumer),
921 ModCache(
std::move(ModCache)),
922 ModuleDepCollector(
std::move(ModuleDepCollector)) {
923 assert(this->VFS &&
"Clone config requires non-null VFS");
924 assert(this->ModCache &&
"Clone config requires non-null ModuleCache");
931 return ModuleDepCollector;
950 bool IsInclusionDirective);
956 std::unique_ptr<CompilerInstance> cloneForModuleCompileImpl(
960 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
971 SourceLocation ImportLoc,
const Module *Module, StringRef ModuleFileName,
972 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
979 std::unique_ptr<llvm::MemoryBuffer>
compileModule(SourceLocation ImportLoc,
980 StringRef ModuleName,
981 StringRef ModuleFileName,
982 CompilerInstance &Instance);
986 bool IsInclusionDirective)
override;
989 StringRef Source)
override;
992 SourceLocation ImportLoc)
override;
1003 GenModuleActionWrapper = Wrapper;
1007 return GenModuleActionWrapper;
1011 DependencyCollectors.push_back(std::move(Listener));
1017 return DependencyCollectors;
1027 return InheritedDirectoryDependencies;
1030 InheritedDirectoryDependencies.assign(Dirs.begin(), Dirs.end());
Defines the Diagnostic-related interfaces.
This is the interface for scanning header and source files to get the minimum necessary preprocessor ...
Defines the SourceManager interface.
Tracks various options which control how API notes are found and handled.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Reads an AST files chain containing the contents of a translation unit.
Stores options for the analyzer from the command line.
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::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVFS() const
std::shared_ptr< ModuleCache > getModuleCache() const
ThreadSafeCloneConfig(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, DiagnosticConsumer &DiagConsumer, std::shared_ptr< ModuleCache > ModCache, std::shared_ptr< ModuleDependencyCollector > ModuleDepCollector=nullptr)
DiagnosticConsumer & getDiagConsumer() const
bool hasOutputManager() const
const ssaf::SSAFOptions & getSSAFOpts() const
bool loadModuleFile(ModuleFileName FileName, serialization::ModuleFile *&LoadedModuleFile)
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.
DiagnosticConsumer & getDiagnosticClient() const
~CompilerInstance() override
void createPreprocessor(TranslationUnitKind TUKind)
Create the preprocessor, using the invocation, file, and source managers, and replace any existing on...
void clearDependencyCollectors()
AnalyzerOptions & getAnalyzerOpts()
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
Check global module index for missing imports.
void setOutputManager(IntrusiveRefCntPtr< llvm::vfs::OutputBackend > NewOutputs)
Set the output manager.
void createDiagnostics(DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false, bool SetOnlyIfDifferent=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
const HeaderSearchOptions & getHeaderSearchOpts() const
DependencyOutputOptions & getDependencyOutputOpts()
bool hasFileManager() const
const DependencyOutputOptions & getDependencyOutputOpts() const
std::shared_ptr< Preprocessor > getPreprocessorPtr()
TargetInfo * getAuxTarget() const
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
GlobalModuleIndex * loadGlobalModuleIndex(SourceLocation TriggerLoc) override
Load, create, or return global module.
raw_ostream & getVerboseOutputStream()
Get the current stream for verbose output.
llvm::TimerGroup & getTimerGroup() const
void setExternalSemaSource(IntrusiveRefCntPtr< ExternalSemaSource > ESS)
GenModuleActionWrapperFunc getGenModuleActionWrapper() const
const DiagnosticOptions & getDiagnosticOpts() const
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
const CodeGenOptions & getCodeGenOpts() const
FileSystemOptions & getFileSystemOpts()
llvm::Timer & getFrontendTimer() const
const TargetOptions & getTargetOpts() const
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file.
void createFileManager()
Create the file manager and replace any existing one with it.
void setVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
Use the given file system.
void setOutputStream(std::unique_ptr< llvm::raw_pwrite_stream > OutStream)
FileManager & getFileManager() const
Return the current file manager to the caller.
void setBuildGlobalModuleIndex(bool Build)
Set the flag indicating whether we should (re)build the global module index.
IntrusiveRefCntPtr< DiagnosticsEngine > getDiagnosticsPtr() const
void createOutputManager()
Create an output manager.
std::unique_ptr< Sema > takeSema()
const PreprocessorOptions & getPreprocessorOpts() const
std::unique_ptr< llvm::MemoryBuffer > compileModule(SourceLocation ImportLoc, StringRef ModuleName, StringRef ModuleFileName, CompilerInstance &Instance)
Compile a module file for the given module, using the options provided by the importing compiler inst...
void printDiagnosticStats()
At the end of a compilation, print the number of warnings/errors.
void resetAndLeakSourceManager()
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
IntrusiveRefCntPtr< FileManager > getFileManagerPtr() const
ModuleCache & getModuleCache() const
const PreprocessorOutputOptions & getPreprocessorOutputOpts() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
void setTarget(TargetInfo *Value)
Replace the current Target.
void setModuleDepCollector(std::shared_ptr< ModuleDependencyCollector > Collector)
std::shared_ptr< ModuleCache > getModuleCachePtr() const
void addDependencyCollector(std::shared_ptr< DependencyCollector > Listener)
void createASTContext()
Create the AST context.
bool hasASTContext() const
void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, StringRef Source) override
Attempt to create the given module from the specified source buffer.
void resetAndLeakFileManager()
ssaf::SSAFOptions & getSSAFOpts()
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
const llvm::cl::LibraryOptionsContext & getLibraryOptions() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
void setInheritedDirectoryDependencies(ArrayRef< std::string > Dirs)
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
TargetOptions & getTargetOpts()
IntrusiveRefCntPtr< TargetInfo > getTargetPtr() const
void createVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS=llvm::vfs::getRealFileSystem(), DiagnosticConsumer *DC=nullptr)
Create a virtual file system instance based on the invocation.
void setASTReader(IntrusiveRefCntPtr< ASTReader > Reader)
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
const FrontendOptions & getFrontendOpts() const
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
std::shared_ptr< CompilerInvocation > getInvocationPtr()
bool hasDiagnostics() const
bool hadModuleLoaderFatalFailure() const
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
std::unique_ptr< CompilerInstance > cloneForModuleCompile(SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName, std::optional< ThreadSafeCloneConfig > ThreadSafeConfig=std::nullopt)
Creates a new CompilerInstance for compiling a module.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, bool UseTemporary, bool CreateMissingDirectories=false, bool SetOnlyIfDifferent=false)
Create a new output file, optionally deriving the output path name, and add it to the list of tracked...
void setSourceManager(llvm::IntrusiveRefCntPtr< SourceManager > Value)
setSourceManager - Replace the current source manager.
void setASTContext(llvm::IntrusiveRefCntPtr< ASTContext > Value)
setASTContext - Replace the current AST context.
HeaderSearchOptions & getHeaderSearchOpts()
void createFrontendTimer()
Create the frontend timer and replace any existing one with it.
bool hasCodeCompletionConsumer() const
void resetAndLeakASTContext()
std::vector< std::shared_ptr< DependencyCollector > > & getDependencyCollectors()
const LangOptions & getLangOpts() const
ArrayRef< std::string > getInheritedDirectoryDependencies() const
See InheritedDirectoryDependencies.
void parseLLVMArgs()
Parse and apply LLVM command line arguments from FrontendOptions.
void createSourceManager()
Create the source manager and replace any existing one with it.
CompilerInvocation & getInvocation()
const PCHContainerWriter & getPCHContainerWriter() const
Return the appropriate PCHContainerWriter depending on the current CodeGenOptions.
void setVerboseOutputStream(raw_ostream &Value)
Replace the current stream for verbose output.
void resetAndLeakPreprocessor()
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
PreprocessorOptions & getPreprocessorOpts()
IntrusiveRefCntPtr< ASTContext > getASTContextPtr() const
ASTConsumer & getASTConsumer() const
void setFileManager(IntrusiveRefCntPtr< FileManager > Value)
Replace the current file manager.
TargetInfo & getTarget() const
llvm::vfs::OutputBackend & getOutputManager()
llvm::vfs::FileSystem & getVirtualFileSystem() const
const FileSystemOptions & getFileSystemOpts() const
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
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.
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
DiagnosticOptions & getDiagnosticOpts()
LangOptions & getLangOpts()
llvm::ArrayRef< std::unique_ptr< llvm::PassPlugin > > getPassPlugins() const
llvm::vfs::OutputBackend & getOrCreateOutputManager()
const APINotesOptions & getAPINotesOpts() const
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
IntrusiveRefCntPtr< SourceManager > getSourceManagerPtr() const
CodeCompleteConsumer & getCodeCompletionConsumer() const
void setDiagnostics(llvm::IntrusiveRefCntPtr< DiagnosticsEngine > Value)
setDiagnostics - Replace the current diagnostics engine.
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
void setGenModuleActionWrapper(GenModuleActionWrapperFunc Wrapper)
bool hasSourceManager() const
bool hasASTConsumer() const
APINotesOptions & getAPINotesOpts()
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.
void setDependencyDirectivesGetter(std::unique_ptr< DependencyDirectivesGetter > Getter)
bool hasPreprocessor() const
void setPreprocessor(std::shared_ptr< Preprocessor > Value)
Replace the current preprocessor.
bool hasVirtualFileSystem() const
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.
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Options for controlling the compiler diagnostics engine.
Concrete class used by the front-end to report problems and issues.
Implements support for file system lookup, file system caching, and directory search management.
Keeps track of options that affect how file operations are performed.
Abstract base class for actions which can be performed by the frontend.
FrontendOptions - Options for controlling the behavior of the frontend.
A global index for a set of module files, providing information about the identifiers within those mo...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
The module cache used for compiling modules implicitly.
Identifies a module file to be loaded.
Describes the result of attempting to load a module.
ModuleLoader(bool BuildingModule=false)
Describes a module or submodule.
NameVisibilityKind
Describes the visibility of the various names within a particular module.
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
This abstract interface provides operations for creating containers for serialized ASTs (precompiled ...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g....
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Sema - This implements semantic analysis and AST building for C.
Encodes a location in the source.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Exposes information about the current target.
Options for controlling the target.
Information about a module that has been loaded by the ASTReader.
Defines the clang::TargetInfo interface.
Top level wrappers for InstallAPI frontend operations.
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
TranslationUnitKind
Describes the kind of translation unit being processed.
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
Visibility
Describes the different kinds of visibility that a declaration may have.
Diagnostic wrappers for TextAPI types for error reporting.
int const char * function