1 //===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
11 #define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/Frontend/PCHContainerOperations.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Frontend/CompilerInvocation.h"
18 #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"
40 class CodeCompleteConsumer;
41 class DiagnosticsEngine;
42 class DiagnosticConsumer;
43 class ExternalASTSource;
53 /// CompilerInstance - Helper class for managing a single instance of the Clang
56 /// The CompilerInstance serves two purposes:
57 /// (1) It manages the various objects which are necessary to run the compiler,
58 /// for example the preprocessor, the target information, and the AST
60 /// (2) It provides utility routines for constructing and manipulating the
61 /// common Clang objects.
63 /// The compiler instance generally owns the instance of all the objects that it
64 /// manages. However, clients can still share objects by manually setting the
65 /// object and retaking ownership prior to destroying the CompilerInstance.
67 /// The compiler instance is intended to simplify clients, but not to lock them
68 /// in to the compiler instance for everything. When possible, utility functions
69 /// come in two forms; a short form that reuses the CompilerInstance objects,
70 /// and a long form that takes explicit instances of any required objects.
71 class CompilerInstance : public ModuleLoader {
72 /// The options used in this compiler instance.
73 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
75 /// The diagnostics engine instance.
76 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
78 /// The target being compiled for.
79 IntrusiveRefCntPtr<TargetInfo> Target;
81 /// Auxiliary Target info.
82 IntrusiveRefCntPtr<TargetInfo> AuxTarget;
84 /// The virtual file system.
85 IntrusiveRefCntPtr<vfs::FileSystem> VirtualFileSystem;
88 IntrusiveRefCntPtr<FileManager> FileMgr;
90 /// The source manager.
91 IntrusiveRefCntPtr<SourceManager> SourceMgr;
94 IntrusiveRefCntPtr<Preprocessor> PP;
97 IntrusiveRefCntPtr<ASTContext> Context;
100 std::unique_ptr<ASTConsumer> Consumer;
102 /// The code completion consumer.
103 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
105 /// \brief The semantic analysis object.
106 std::unique_ptr<Sema> TheSema;
108 /// \brief The frontend timer group.
109 std::unique_ptr<llvm::TimerGroup> FrontendTimerGroup;
111 /// \brief The frontend timer.
112 std::unique_ptr<llvm::Timer> FrontendTimer;
114 /// \brief The ASTReader, if one exists.
115 IntrusiveRefCntPtr<ASTReader> ModuleManager;
117 /// \brief The module dependency collector for crashdumps
118 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
120 /// \brief The module provider.
121 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
123 /// \brief The dependency file generator.
124 std::unique_ptr<DependencyFileGenerator> TheDependencyFileGenerator;
126 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
128 /// \brief The set of top-level modules that has already been loaded,
129 /// along with the module map
130 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
132 /// \brief The location of the module-import keyword for the last module
134 SourceLocation LastModuleImportLoc;
136 /// \brief The result of the last module import.
138 ModuleLoadResult LastModuleImportResult;
140 /// \brief Whether we should (re)build the global module index once we
141 /// have finished with this translation unit.
142 bool BuildGlobalModuleIndex;
144 /// \brief We have a full global module index, with all modules.
145 bool HaveFullGlobalModuleIndex;
147 /// \brief One or more modules failed to build.
148 bool ModuleBuildFailed;
150 /// \brief Holds information about the output file.
152 /// If TempFilename is not empty we must rename it to Filename at the end.
153 /// TempFilename may be empty and Filename non-empty if creating the temporary
156 std::string Filename;
157 std::string TempFilename;
159 OutputFile(std::string filename, std::string tempFilename)
160 : Filename(std::move(filename)), TempFilename(std::move(tempFilename)) {
164 /// If the output doesn't support seeking (terminal, pipe). we switch
165 /// the stream to a buffer_ostream. These are the buffer and the original
167 std::unique_ptr<llvm::raw_fd_ostream> NonSeekStream;
169 /// The list of active output files.
170 std::list<OutputFile> OutputFiles;
172 CompilerInstance(const CompilerInstance &) = delete;
173 void operator=(const CompilerInstance &) = delete;
175 explicit CompilerInstance(
176 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
177 std::make_shared<PCHContainerOperations>(),
178 bool BuildingModule = false);
179 ~CompilerInstance() override;
181 /// @name High-Level Operations
184 /// ExecuteAction - Execute the provided action against the compiler's
185 /// CompilerInvocation object.
187 /// This function makes the following assumptions:
189 /// - The invocation options should be initialized. This function does not
190 /// handle the '-help' or '-version' options, clients should handle those
193 /// - The diagnostics engine should have already been created by the client.
195 /// - No other CompilerInstance state should have been initialized (this is
196 /// an unchecked error).
198 /// - Clients should have initialized any LLVM target features that may be
201 /// - Clients should eventually call llvm_shutdown() upon the completion of
202 /// this routine to ensure that any managed objects are properly destroyed.
204 /// Note that this routine may write output to 'stderr'.
206 /// \param Act - The action to execute.
207 /// \return - True on success.
209 // FIXME: This function should take the stream to write any debugging /
210 // verbose output to as an argument.
212 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
213 // of the context or else not CompilerInstance specific.
214 bool ExecuteAction(FrontendAction &Act);
217 /// @name Compiler Invocation and Options
220 bool hasInvocation() const { return Invocation != nullptr; }
222 CompilerInvocation &getInvocation() {
223 assert(Invocation && "Compiler instance has no invocation!");
227 /// setInvocation - Replace the current invocation.
228 void setInvocation(CompilerInvocation *Value);
230 /// \brief Indicates whether we should (re)build the global module index.
231 bool shouldBuildGlobalModuleIndex() const;
233 /// \brief Set the flag indicating whether we should (re)build the global
235 void setBuildGlobalModuleIndex(bool Build) {
236 BuildGlobalModuleIndex = Build;
240 /// @name Forwarding Methods
243 AnalyzerOptionsRef getAnalyzerOpts() {
244 return Invocation->getAnalyzerOpts();
247 CodeGenOptions &getCodeGenOpts() {
248 return Invocation->getCodeGenOpts();
250 const CodeGenOptions &getCodeGenOpts() const {
251 return Invocation->getCodeGenOpts();
254 DependencyOutputOptions &getDependencyOutputOpts() {
255 return Invocation->getDependencyOutputOpts();
257 const DependencyOutputOptions &getDependencyOutputOpts() const {
258 return Invocation->getDependencyOutputOpts();
261 DiagnosticOptions &getDiagnosticOpts() {
262 return Invocation->getDiagnosticOpts();
264 const DiagnosticOptions &getDiagnosticOpts() const {
265 return Invocation->getDiagnosticOpts();
268 FileSystemOptions &getFileSystemOpts() {
269 return Invocation->getFileSystemOpts();
271 const FileSystemOptions &getFileSystemOpts() const {
272 return Invocation->getFileSystemOpts();
275 FrontendOptions &getFrontendOpts() {
276 return Invocation->getFrontendOpts();
278 const FrontendOptions &getFrontendOpts() const {
279 return Invocation->getFrontendOpts();
282 HeaderSearchOptions &getHeaderSearchOpts() {
283 return Invocation->getHeaderSearchOpts();
285 const HeaderSearchOptions &getHeaderSearchOpts() const {
286 return Invocation->getHeaderSearchOpts();
289 LangOptions &getLangOpts() {
290 return *Invocation->getLangOpts();
292 const LangOptions &getLangOpts() const {
293 return *Invocation->getLangOpts();
296 PreprocessorOptions &getPreprocessorOpts() {
297 return Invocation->getPreprocessorOpts();
299 const PreprocessorOptions &getPreprocessorOpts() const {
300 return Invocation->getPreprocessorOpts();
303 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
304 return Invocation->getPreprocessorOutputOpts();
306 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
307 return Invocation->getPreprocessorOutputOpts();
310 TargetOptions &getTargetOpts() {
311 return Invocation->getTargetOpts();
313 const TargetOptions &getTargetOpts() const {
314 return Invocation->getTargetOpts();
318 /// @name Diagnostics Engine
321 bool hasDiagnostics() const { return Diagnostics != nullptr; }
323 /// Get the current diagnostics engine.
324 DiagnosticsEngine &getDiagnostics() const {
325 assert(Diagnostics && "Compiler instance has no diagnostics!");
329 /// setDiagnostics - Replace the current diagnostics engine.
330 void setDiagnostics(DiagnosticsEngine *Value);
332 DiagnosticConsumer &getDiagnosticClient() const {
333 assert(Diagnostics && Diagnostics->getClient() &&
334 "Compiler instance has no diagnostic client!");
335 return *Diagnostics->getClient();
339 /// @name Target Info
342 bool hasTarget() const { return Target != nullptr; }
344 TargetInfo &getTarget() const {
345 assert(Target && "Compiler instance has no target!");
349 /// Replace the current Target.
350 void setTarget(TargetInfo *Value);
353 /// @name AuxTarget Info
356 TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
358 /// Replace the current AuxTarget.
359 void setAuxTarget(TargetInfo *Value);
362 /// @name Virtual File System
365 bool hasVirtualFileSystem() const { return VirtualFileSystem != nullptr; }
367 vfs::FileSystem &getVirtualFileSystem() const {
368 assert(hasVirtualFileSystem() &&
369 "Compiler instance has no virtual file system");
370 return *VirtualFileSystem;
373 /// \brief Replace the current virtual file system.
375 /// \note Most clients should use setFileManager, which will implicitly reset
376 /// the virtual file system to the one contained in the file manager.
377 void setVirtualFileSystem(IntrusiveRefCntPtr<vfs::FileSystem> FS) {
378 VirtualFileSystem = std::move(FS);
382 /// @name File Manager
385 bool hasFileManager() const { return FileMgr != nullptr; }
387 /// Return the current file manager to the caller.
388 FileManager &getFileManager() const {
389 assert(FileMgr && "Compiler instance has no file manager!");
393 void resetAndLeakFileManager() {
394 BuryPointer(FileMgr.get());
395 FileMgr.resetWithoutRelease();
398 /// \brief Replace the current file manager and virtual file system.
399 void setFileManager(FileManager *Value);
402 /// @name Source Manager
405 bool hasSourceManager() const { return SourceMgr != nullptr; }
407 /// Return the current source manager.
408 SourceManager &getSourceManager() const {
409 assert(SourceMgr && "Compiler instance has no source manager!");
413 void resetAndLeakSourceManager() {
414 BuryPointer(SourceMgr.get());
415 SourceMgr.resetWithoutRelease();
418 /// setSourceManager - Replace the current source manager.
419 void setSourceManager(SourceManager *Value);
422 /// @name Preprocessor
425 bool hasPreprocessor() const { return PP != nullptr; }
427 /// Return the current preprocessor.
428 Preprocessor &getPreprocessor() const {
429 assert(PP && "Compiler instance has no preprocessor!");
433 void resetAndLeakPreprocessor() {
434 BuryPointer(PP.get());
435 PP.resetWithoutRelease();
438 /// Replace the current preprocessor.
439 void setPreprocessor(Preprocessor *Value);
445 bool hasASTContext() const { return Context != nullptr; }
447 ASTContext &getASTContext() const {
448 assert(Context && "Compiler instance has no AST context!");
452 void resetAndLeakASTContext() {
453 BuryPointer(Context.get());
454 Context.resetWithoutRelease();
457 /// setASTContext - Replace the current AST context.
458 void setASTContext(ASTContext *Value);
460 /// \brief Replace the current Sema; the compiler instance takes ownership
462 void setSema(Sema *S);
465 /// @name ASTConsumer
468 bool hasASTConsumer() const { return (bool)Consumer; }
470 ASTConsumer &getASTConsumer() const {
471 assert(Consumer && "Compiler instance has no AST consumer!");
475 /// takeASTConsumer - Remove the current AST consumer and give ownership to
477 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
479 /// setASTConsumer - Replace the current AST consumer; the compiler instance
480 /// takes ownership of \p Value.
481 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
484 /// @name Semantic analysis
486 bool hasSema() const { return (bool)TheSema; }
488 Sema &getSema() const {
489 assert(TheSema && "Compiler instance has no Sema object!");
493 std::unique_ptr<Sema> takeSema();
494 void resetAndLeakSema();
497 /// @name Module Management
500 IntrusiveRefCntPtr<ASTReader> getModuleManager() const;
501 void setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader);
503 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
504 void setModuleDepCollector(
505 std::shared_ptr<ModuleDependencyCollector> Collector);
507 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
508 return ThePCHContainerOperations;
511 /// Return the appropriate PCHContainerWriter depending on the
512 /// current CodeGenOptions.
513 const PCHContainerWriter &getPCHContainerWriter() const {
514 assert(Invocation && "cannot determine module format without invocation");
515 StringRef Format = getHeaderSearchOpts().ModuleFormat;
516 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
519 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
520 llvm::report_fatal_error("unknown module format");
525 /// Return the appropriate PCHContainerReader depending on the
526 /// current CodeGenOptions.
527 const PCHContainerReader &getPCHContainerReader() const {
528 assert(Invocation && "cannot determine module format without invocation");
529 StringRef Format = getHeaderSearchOpts().ModuleFormat;
530 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
533 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
534 llvm::report_fatal_error("unknown module format");
540 /// @name Code Completion
543 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
545 CodeCompleteConsumer &getCodeCompletionConsumer() const {
546 assert(CompletionConsumer &&
547 "Compiler instance has no code completion consumer!");
548 return *CompletionConsumer;
551 /// setCodeCompletionConsumer - Replace the current code completion consumer;
552 /// the compiler instance takes ownership of \p Value.
553 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
556 /// @name Frontend timer
559 bool hasFrontendTimer() const { return (bool)FrontendTimer; }
561 llvm::Timer &getFrontendTimer() const {
562 assert(FrontendTimer && "Compiler instance has no frontend timer!");
563 return *FrontendTimer;
567 /// @name Output Files
570 /// addOutputFile - Add an output file onto the list of tracked output files.
572 /// \param OutFile - The output file info.
573 void addOutputFile(OutputFile &&OutFile);
575 /// clearOutputFiles - Clear the output file list. The underlying output
576 /// streams must have been closed beforehand.
578 /// \param EraseFiles - If true, attempt to erase the files from disk.
579 void clearOutputFiles(bool EraseFiles);
582 /// @name Construction Utility Methods
585 /// Create the diagnostics engine using the invocation's diagnostic options
586 /// and replace any existing one with it.
588 /// Note that this routine also replaces the diagnostic client,
589 /// allocating one if one is not provided.
591 /// \param Client If non-NULL, a diagnostic client that will be
592 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
595 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
596 /// the diagnostic object should take ownership of the client.
597 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
598 bool ShouldOwnClient = true);
600 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
602 /// If no diagnostic client is provided, this creates a
603 /// DiagnosticConsumer that is owned by the returned diagnostic
604 /// object, if using directly the caller is responsible for
605 /// releasing the returned DiagnosticsEngine's client eventually.
607 /// \param Opts - The diagnostic options; note that the created text
608 /// diagnostic object contains a reference to these options.
610 /// \param Client If non-NULL, a diagnostic client that will be
611 /// attached to (and, then, owned by) the returned DiagnosticsEngine
614 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
615 /// used by some diagnostics printers (for logging purposes only).
617 /// \return The new object on success, or null on failure.
618 static IntrusiveRefCntPtr<DiagnosticsEngine>
619 createDiagnostics(DiagnosticOptions *Opts,
620 DiagnosticConsumer *Client = nullptr,
621 bool ShouldOwnClient = true,
622 const CodeGenOptions *CodeGenOpts = nullptr);
624 /// Create the file manager and replace any existing one with it.
625 void createFileManager();
627 /// Create the source manager and replace any existing one with it.
628 void createSourceManager(FileManager &FileMgr);
630 /// Create the preprocessor, using the invocation, file, and source managers,
631 /// and replace any existing one with it.
632 void createPreprocessor(TranslationUnitKind TUKind);
634 std::string getSpecificModuleCachePath();
636 /// Create the AST context.
637 void createASTContext();
639 /// Create an external AST source to read a PCH file and attach it to the AST
641 void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation,
642 bool AllowPCHWithCompilerErrors,
643 void *DeserializationListener,
644 bool OwnDeserializationListener);
646 /// Create an external AST source to read a PCH file.
648 /// \return - The new object on success, or null on failure.
649 static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
650 StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
651 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
652 const PCHContainerReader &PCHContainerRdr,
653 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
654 void *DeserializationListener, bool OwnDeserializationListener,
655 bool Preamble, bool UseGlobalModuleIndex);
657 /// Create a code completion consumer using the invocation; note that this
658 /// will cause the source manager to truncate the input source file at the
659 /// completion point.
660 void createCodeCompletionConsumer();
662 /// Create a code completion consumer to print code completion results, at
663 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
664 static CodeCompleteConsumer *createCodeCompletionConsumer(
665 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
666 const CodeCompleteOptions &Opts, raw_ostream &OS);
668 /// \brief Create the Sema object to be used for parsing.
669 void createSema(TranslationUnitKind TUKind,
670 CodeCompleteConsumer *CompletionConsumer);
672 /// Create the frontend timer and replace any existing one with it.
673 void createFrontendTimer();
675 /// Create the default output file (from the invocation's options) and add it
676 /// to the list of tracked output files.
678 /// The files created by this function always use temporary files to write to
679 /// their result (that is, the data is written to a temporary file which will
680 /// atomically replace the target output on success).
682 /// \return - Null on error.
683 std::unique_ptr<raw_pwrite_stream>
684 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
685 StringRef Extension = "");
687 /// Create a new output file and add it to the list of tracked output files,
688 /// optionally deriving the output path name.
690 /// \return - Null on error.
691 std::unique_ptr<raw_pwrite_stream>
692 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
693 StringRef BaseInput, StringRef Extension, bool UseTemporary,
694 bool CreateMissingDirectories = false);
696 /// Create a new output file, optionally deriving the output path name.
698 /// If \p OutputPath is empty, then createOutputFile will derive an output
699 /// path location as \p BaseInput, with any suffix removed, and \p Extension
700 /// appended. If \p OutputPath is not stdout and \p UseTemporary
701 /// is true, createOutputFile will create a new temporary file that must be
702 /// renamed to \p OutputPath in the end.
704 /// \param OutputPath - If given, the path to the output file.
705 /// \param Error [out] - On failure, the error.
706 /// \param BaseInput - If \p OutputPath is empty, the input path name to use
707 /// for deriving the output path.
708 /// \param Extension - The extension to use for derived output names.
709 /// \param Binary - The mode to open the file in.
710 /// \param RemoveFileOnSignal - Whether the file should be registered with
711 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
712 /// multithreaded use, as the underlying signal mechanism is not reentrant
713 /// \param UseTemporary - Create a new temporary file that must be renamed to
714 /// OutputPath in the end.
715 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
716 /// missing directories in the output path.
717 /// \param ResultPathName [out] - If given, the result path name will be
718 /// stored here on success.
719 /// \param TempPathName [out] - If given, the temporary file path name
720 /// will be stored here on success.
721 std::unique_ptr<raw_pwrite_stream>
722 createOutputFile(StringRef OutputPath, std::error_code &Error, bool Binary,
723 bool RemoveFileOnSignal, StringRef BaseInput,
724 StringRef Extension, bool UseTemporary,
725 bool CreateMissingDirectories, std::string *ResultPathName,
726 std::string *TempPathName);
728 std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
731 /// @name Initialization Utility Methods
734 /// InitializeSourceManager - Initialize the source manager to set InputFile
735 /// as the main file.
737 /// \return True on success.
738 bool InitializeSourceManager(const FrontendInputFile &Input);
740 /// InitializeSourceManager - Initialize the source manager to set InputFile
741 /// as the main file.
743 /// \return True on success.
744 static bool InitializeSourceManager(const FrontendInputFile &Input,
745 DiagnosticsEngine &Diags,
746 FileManager &FileMgr,
747 SourceManager &SourceMgr,
749 DependencyOutputOptions &DepOpts,
750 const FrontendOptions &Opts);
754 // Create module manager.
755 void createModuleManager();
757 bool loadModuleFile(StringRef FileName);
759 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
760 Module::NameVisibilityKind Visibility,
761 bool IsInclusionDirective) override;
763 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
764 SourceLocation ImportLoc) override;
766 bool hadModuleLoaderFatalFailure() const {
767 return ModuleLoader::HadFatalFailure;
770 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override;
772 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
774 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
775 DependencyCollectors.push_back(std::move(Listener));
779 } // end namespace clang