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/Basic/Diagnostic.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Frontend/CompilerInvocation.h"
17 #include "clang/Frontend/Utils.h"
18 #include "clang/Lex/ModuleLoader.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/IntrusiveRefCntPtr.h"
22 #include "llvm/ADT/StringRef.h"
38 class CodeCompleteConsumer;
39 class DiagnosticsEngine;
40 class DiagnosticConsumer;
41 class ExternalASTSource;
51 /// CompilerInstance - Helper class for managing a single instance of the Clang
54 /// The CompilerInstance serves two purposes:
55 /// (1) It manages the various objects which are necessary to run the compiler,
56 /// for example the preprocessor, the target information, and the AST
58 /// (2) It provides utility routines for constructing and manipulating the
59 /// common Clang objects.
61 /// The compiler instance generally owns the instance of all the objects that it
62 /// manages. However, clients can still share objects by manually setting the
63 /// object and retaking ownership prior to destroying the CompilerInstance.
65 /// The compiler instance is intended to simplify clients, but not to lock them
66 /// in to the compiler instance for everything. When possible, utility functions
67 /// come in two forms; a short form that reuses the CompilerInstance objects,
68 /// and a long form that takes explicit instances of any required objects.
69 class CompilerInstance : public ModuleLoader {
70 /// The options used in this compiler instance.
71 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
73 /// The diagnostics engine instance.
74 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
76 /// The target being compiled for.
77 IntrusiveRefCntPtr<TargetInfo> Target;
79 /// The virtual file system.
80 IntrusiveRefCntPtr<vfs::FileSystem> VirtualFileSystem;
83 IntrusiveRefCntPtr<FileManager> FileMgr;
85 /// The source manager.
86 IntrusiveRefCntPtr<SourceManager> SourceMgr;
89 IntrusiveRefCntPtr<Preprocessor> PP;
92 IntrusiveRefCntPtr<ASTContext> Context;
95 std::unique_ptr<ASTConsumer> Consumer;
97 /// The code completion consumer.
98 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
100 /// \brief The semantic analysis object.
101 std::unique_ptr<Sema> TheSema;
103 /// \brief The frontend timer
104 std::unique_ptr<llvm::Timer> FrontendTimer;
106 /// \brief The ASTReader, if one exists.
107 IntrusiveRefCntPtr<ASTReader> ModuleManager;
109 /// \brief The module dependency collector for crashdumps
110 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
112 /// \brief The dependency file generator.
113 std::unique_ptr<DependencyFileGenerator> TheDependencyFileGenerator;
115 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
117 /// \brief The set of top-level modules that has already been loaded,
118 /// along with the module map
119 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
121 /// \brief Module names that have an override for the target file.
122 llvm::StringMap<std::string> ModuleFileOverrides;
124 /// \brief Module files that we've explicitly loaded via \ref loadModuleFile,
125 /// and their dependencies.
126 llvm::StringSet<> ExplicitlyLoadedModuleFiles;
128 /// \brief The location of the module-import keyword for the last module
130 SourceLocation LastModuleImportLoc;
132 /// \brief The result of the last module import.
134 ModuleLoadResult LastModuleImportResult;
136 /// \brief Whether we should (re)build the global module index once we
137 /// have finished with this translation unit.
138 bool BuildGlobalModuleIndex;
140 /// \brief We have a full global module index, with all modules.
141 bool HaveFullGlobalModuleIndex;
143 /// \brief One or more modules failed to build.
144 bool ModuleBuildFailed;
146 /// \brief Holds information about the output file.
148 /// If TempFilename is not empty we must rename it to Filename at the end.
149 /// TempFilename may be empty and Filename non-empty if creating the temporary
152 std::string Filename;
153 std::string TempFilename;
154 std::unique_ptr<raw_ostream> OS;
156 OutputFile(const std::string &filename, const std::string &tempFilename,
157 std::unique_ptr<raw_ostream> OS)
158 : Filename(filename), TempFilename(tempFilename), OS(std::move(OS)) {}
159 OutputFile(OutputFile &&O)
160 : Filename(std::move(O.Filename)),
161 TempFilename(std::move(O.TempFilename)), OS(std::move(O.OS)) {}
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(bool BuildingModule = false);
176 ~CompilerInstance() override;
178 /// @name High-Level Operations
181 /// ExecuteAction - Execute the provided action against the compiler's
182 /// CompilerInvocation object.
184 /// This function makes the following assumptions:
186 /// - The invocation options should be initialized. This function does not
187 /// handle the '-help' or '-version' options, clients should handle those
190 /// - The diagnostics engine should have already been created by the client.
192 /// - No other CompilerInstance state should have been initialized (this is
193 /// an unchecked error).
195 /// - Clients should have initialized any LLVM target features that may be
198 /// - Clients should eventually call llvm_shutdown() upon the completion of
199 /// this routine to ensure that any managed objects are properly destroyed.
201 /// Note that this routine may write output to 'stderr'.
203 /// \param Act - The action to execute.
204 /// \return - True on success.
206 // FIXME: This function should take the stream to write any debugging /
207 // verbose output to as an argument.
209 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
210 // of the context or else not CompilerInstance specific.
211 bool ExecuteAction(FrontendAction &Act);
214 /// @name Compiler Invocation and Options
217 bool hasInvocation() const { return Invocation != nullptr; }
219 CompilerInvocation &getInvocation() {
220 assert(Invocation && "Compiler instance has no invocation!");
224 /// setInvocation - Replace the current invocation.
225 void setInvocation(CompilerInvocation *Value);
227 /// \brief Indicates whether we should (re)build the global module index.
228 bool shouldBuildGlobalModuleIndex() const;
230 /// \brief Set the flag indicating whether we should (re)build the global
232 void setBuildGlobalModuleIndex(bool Build) {
233 BuildGlobalModuleIndex = Build;
237 /// @name Forwarding Methods
240 AnalyzerOptionsRef getAnalyzerOpts() {
241 return Invocation->getAnalyzerOpts();
244 CodeGenOptions &getCodeGenOpts() {
245 return Invocation->getCodeGenOpts();
247 const CodeGenOptions &getCodeGenOpts() const {
248 return Invocation->getCodeGenOpts();
251 DependencyOutputOptions &getDependencyOutputOpts() {
252 return Invocation->getDependencyOutputOpts();
254 const DependencyOutputOptions &getDependencyOutputOpts() const {
255 return Invocation->getDependencyOutputOpts();
258 DiagnosticOptions &getDiagnosticOpts() {
259 return Invocation->getDiagnosticOpts();
261 const DiagnosticOptions &getDiagnosticOpts() const {
262 return Invocation->getDiagnosticOpts();
265 FileSystemOptions &getFileSystemOpts() {
266 return Invocation->getFileSystemOpts();
268 const FileSystemOptions &getFileSystemOpts() const {
269 return Invocation->getFileSystemOpts();
272 FrontendOptions &getFrontendOpts() {
273 return Invocation->getFrontendOpts();
275 const FrontendOptions &getFrontendOpts() const {
276 return Invocation->getFrontendOpts();
279 HeaderSearchOptions &getHeaderSearchOpts() {
280 return Invocation->getHeaderSearchOpts();
282 const HeaderSearchOptions &getHeaderSearchOpts() const {
283 return Invocation->getHeaderSearchOpts();
286 LangOptions &getLangOpts() {
287 return *Invocation->getLangOpts();
289 const LangOptions &getLangOpts() const {
290 return *Invocation->getLangOpts();
293 PreprocessorOptions &getPreprocessorOpts() {
294 return Invocation->getPreprocessorOpts();
296 const PreprocessorOptions &getPreprocessorOpts() const {
297 return Invocation->getPreprocessorOpts();
300 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
301 return Invocation->getPreprocessorOutputOpts();
303 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
304 return Invocation->getPreprocessorOutputOpts();
307 TargetOptions &getTargetOpts() {
308 return Invocation->getTargetOpts();
310 const TargetOptions &getTargetOpts() const {
311 return Invocation->getTargetOpts();
315 /// @name Diagnostics Engine
318 bool hasDiagnostics() const { return Diagnostics != nullptr; }
320 /// Get the current diagnostics engine.
321 DiagnosticsEngine &getDiagnostics() const {
322 assert(Diagnostics && "Compiler instance has no diagnostics!");
326 /// setDiagnostics - Replace the current diagnostics engine.
327 void setDiagnostics(DiagnosticsEngine *Value);
329 DiagnosticConsumer &getDiagnosticClient() const {
330 assert(Diagnostics && Diagnostics->getClient() &&
331 "Compiler instance has no diagnostic client!");
332 return *Diagnostics->getClient();
336 /// @name Target Info
339 bool hasTarget() const { return Target != nullptr; }
341 TargetInfo &getTarget() const {
342 assert(Target && "Compiler instance has no target!");
346 /// Replace the current diagnostics engine.
347 void setTarget(TargetInfo *Value);
350 /// @name Virtual File System
353 bool hasVirtualFileSystem() const { return VirtualFileSystem != nullptr; }
355 vfs::FileSystem &getVirtualFileSystem() const {
356 assert(hasVirtualFileSystem() &&
357 "Compiler instance has no virtual file system");
358 return *VirtualFileSystem;
361 /// \brief Replace the current virtual file system.
363 /// \note Most clients should use setFileManager, which will implicitly reset
364 /// the virtual file system to the one contained in the file manager.
365 void setVirtualFileSystem(IntrusiveRefCntPtr<vfs::FileSystem> FS) {
366 VirtualFileSystem = FS;
370 /// @name File Manager
373 bool hasFileManager() const { return FileMgr != nullptr; }
375 /// Return the current file manager to the caller.
376 FileManager &getFileManager() const {
377 assert(FileMgr && "Compiler instance has no file manager!");
381 void resetAndLeakFileManager() {
382 BuryPointer(FileMgr.get());
383 FileMgr.resetWithoutRelease();
386 /// \brief Replace the current file manager and virtual file system.
387 void setFileManager(FileManager *Value);
390 /// @name Source Manager
393 bool hasSourceManager() const { return SourceMgr != nullptr; }
395 /// Return the current source manager.
396 SourceManager &getSourceManager() const {
397 assert(SourceMgr && "Compiler instance has no source manager!");
401 void resetAndLeakSourceManager() {
402 BuryPointer(SourceMgr.get());
403 SourceMgr.resetWithoutRelease();
406 /// setSourceManager - Replace the current source manager.
407 void setSourceManager(SourceManager *Value);
410 /// @name Preprocessor
413 bool hasPreprocessor() const { return PP != nullptr; }
415 /// Return the current preprocessor.
416 Preprocessor &getPreprocessor() const {
417 assert(PP && "Compiler instance has no preprocessor!");
421 void resetAndLeakPreprocessor() {
422 BuryPointer(PP.get());
423 PP.resetWithoutRelease();
426 /// Replace the current preprocessor.
427 void setPreprocessor(Preprocessor *Value);
433 bool hasASTContext() const { return Context != nullptr; }
435 ASTContext &getASTContext() const {
436 assert(Context && "Compiler instance has no AST context!");
440 void resetAndLeakASTContext() {
441 BuryPointer(Context.get());
442 Context.resetWithoutRelease();
445 /// setASTContext - Replace the current AST context.
446 void setASTContext(ASTContext *Value);
448 /// \brief Replace the current Sema; the compiler instance takes ownership
450 void setSema(Sema *S);
453 /// @name ASTConsumer
456 bool hasASTConsumer() const { return (bool)Consumer; }
458 ASTConsumer &getASTConsumer() const {
459 assert(Consumer && "Compiler instance has no AST consumer!");
463 /// takeASTConsumer - Remove the current AST consumer and give ownership to
465 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
467 /// setASTConsumer - Replace the current AST consumer; the compiler instance
468 /// takes ownership of \p Value.
469 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
472 /// @name Semantic analysis
474 bool hasSema() const { return (bool)TheSema; }
476 Sema &getSema() const {
477 assert(TheSema && "Compiler instance has no Sema object!");
481 std::unique_ptr<Sema> takeSema();
482 void resetAndLeakSema();
485 /// @name Module Management
488 IntrusiveRefCntPtr<ASTReader> getModuleManager() const;
489 void setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader);
491 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
492 void setModuleDepCollector(
493 std::shared_ptr<ModuleDependencyCollector> Collector);
496 /// @name Code Completion
499 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
501 CodeCompleteConsumer &getCodeCompletionConsumer() const {
502 assert(CompletionConsumer &&
503 "Compiler instance has no code completion consumer!");
504 return *CompletionConsumer;
507 /// setCodeCompletionConsumer - Replace the current code completion consumer;
508 /// the compiler instance takes ownership of \p Value.
509 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
512 /// @name Frontend timer
515 bool hasFrontendTimer() const { return (bool)FrontendTimer; }
517 llvm::Timer &getFrontendTimer() const {
518 assert(FrontendTimer && "Compiler instance has no frontend timer!");
519 return *FrontendTimer;
523 /// @name Output Files
526 /// addOutputFile - Add an output file onto the list of tracked output files.
528 /// \param OutFile - The output file info.
529 void addOutputFile(OutputFile &&OutFile);
531 /// clearOutputFiles - Clear the output file list, destroying the contained
534 /// \param EraseFiles - If true, attempt to erase the files from disk.
535 void clearOutputFiles(bool EraseFiles);
538 /// @name Construction Utility Methods
541 /// Create the diagnostics engine using the invocation's diagnostic options
542 /// and replace any existing one with it.
544 /// Note that this routine also replaces the diagnostic client,
545 /// allocating one if one is not provided.
547 /// \param Client If non-NULL, a diagnostic client that will be
548 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
551 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
552 /// the diagnostic object should take ownership of the client.
553 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
554 bool ShouldOwnClient = true);
556 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
558 /// If no diagnostic client is provided, this creates a
559 /// DiagnosticConsumer that is owned by the returned diagnostic
560 /// object, if using directly the caller is responsible for
561 /// releasing the returned DiagnosticsEngine's client eventually.
563 /// \param Opts - The diagnostic options; note that the created text
564 /// diagnostic object contains a reference to these options.
566 /// \param Client If non-NULL, a diagnostic client that will be
567 /// attached to (and, then, owned by) the returned DiagnosticsEngine
570 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
571 /// used by some diagnostics printers (for logging purposes only).
573 /// \return The new object on success, or null on failure.
574 static IntrusiveRefCntPtr<DiagnosticsEngine>
575 createDiagnostics(DiagnosticOptions *Opts,
576 DiagnosticConsumer *Client = nullptr,
577 bool ShouldOwnClient = true,
578 const CodeGenOptions *CodeGenOpts = nullptr);
580 /// Create the file manager and replace any existing one with it.
581 void createFileManager();
583 /// Create the source manager and replace any existing one with it.
584 void createSourceManager(FileManager &FileMgr);
586 /// Create the preprocessor, using the invocation, file, and source managers,
587 /// and replace any existing one with it.
588 void createPreprocessor(TranslationUnitKind TUKind);
590 std::string getSpecificModuleCachePath();
592 /// Create the AST context.
593 void createASTContext();
595 /// Create an external AST source to read a PCH file and attach it to the AST
597 void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation,
598 bool AllowPCHWithCompilerErrors,
599 void *DeserializationListener,
600 bool OwnDeserializationListener);
602 /// Create an external AST source to read a PCH file.
604 /// \return - The new object on success, or null on failure.
605 static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
606 StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
607 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
608 void *DeserializationListener, bool OwnDeserializationListener,
609 bool Preamble, bool UseGlobalModuleIndex);
611 /// Create a code completion consumer using the invocation; note that this
612 /// will cause the source manager to truncate the input source file at the
613 /// completion point.
614 void createCodeCompletionConsumer();
616 /// Create a code completion consumer to print code completion results, at
617 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
618 static CodeCompleteConsumer *
619 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
620 unsigned Line, unsigned Column,
621 const CodeCompleteOptions &Opts,
624 /// \brief Create the Sema object to be used for parsing.
625 void createSema(TranslationUnitKind TUKind,
626 CodeCompleteConsumer *CompletionConsumer);
628 /// Create the frontend timer and replace any existing one with it.
629 void createFrontendTimer();
631 /// Create the default output file (from the invocation's options) and add it
632 /// to the list of tracked output files.
634 /// The files created by this function always use temporary files to write to
635 /// their result (that is, the data is written to a temporary file which will
636 /// atomically replace the target output on success).
638 /// \return - Null on error.
639 raw_pwrite_stream *createDefaultOutputFile(bool Binary = true,
640 StringRef BaseInput = "",
641 StringRef Extension = "");
643 /// Create a new output file and add it to the list of tracked output files,
644 /// optionally deriving the output path name.
646 /// \return - Null on error.
647 raw_pwrite_stream *createOutputFile(StringRef OutputPath, bool Binary,
648 bool RemoveFileOnSignal,
649 StringRef BaseInput, StringRef Extension,
651 bool CreateMissingDirectories = false);
653 /// Create a new output file, optionally deriving the output path name.
655 /// If \p OutputPath is empty, then createOutputFile will derive an output
656 /// path location as \p BaseInput, with any suffix removed, and \p Extension
657 /// appended. If \p OutputPath is not stdout and \p UseTemporary
658 /// is true, createOutputFile will create a new temporary file that must be
659 /// renamed to \p OutputPath in the end.
661 /// \param OutputPath - If given, the path to the output file.
662 /// \param Error [out] - On failure, the error.
663 /// \param BaseInput - If \p OutputPath is empty, the input path name to use
664 /// for deriving the output path.
665 /// \param Extension - The extension to use for derived output names.
666 /// \param Binary - The mode to open the file in.
667 /// \param RemoveFileOnSignal - Whether the file should be registered with
668 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
669 /// multithreaded use, as the underlying signal mechanism is not reentrant
670 /// \param UseTemporary - Create a new temporary file that must be renamed to
671 /// OutputPath in the end.
672 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
673 /// missing directories in the output path.
674 /// \param ResultPathName [out] - If given, the result path name will be
675 /// stored here on success.
676 /// \param TempPathName [out] - If given, the temporary file path name
677 /// will be stored here on success.
678 std::unique_ptr<raw_pwrite_stream>
679 createOutputFile(StringRef OutputPath, std::error_code &Error, bool Binary,
680 bool RemoveFileOnSignal, StringRef BaseInput,
681 StringRef Extension, bool UseTemporary,
682 bool CreateMissingDirectories, std::string *ResultPathName,
683 std::string *TempPathName);
685 llvm::raw_null_ostream *createNullOutputFile();
688 /// @name Initialization Utility Methods
691 /// InitializeSourceManager - Initialize the source manager to set InputFile
692 /// as the main file.
694 /// \return True on success.
695 bool InitializeSourceManager(const FrontendInputFile &Input);
697 /// InitializeSourceManager - Initialize the source manager to set InputFile
698 /// as the main file.
700 /// \return True on success.
701 static bool InitializeSourceManager(const FrontendInputFile &Input,
702 DiagnosticsEngine &Diags,
703 FileManager &FileMgr,
704 SourceManager &SourceMgr,
705 const FrontendOptions &Opts);
709 // Create module manager.
710 void createModuleManager();
712 bool loadModuleFile(StringRef FileName);
714 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
715 Module::NameVisibilityKind Visibility,
716 bool IsInclusionDirective) override;
718 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
719 SourceLocation ImportLoc) override;
721 bool hadModuleLoaderFatalFailure() const {
722 return ModuleLoader::HadFatalFailure;
725 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override;
727 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
729 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
730 DependencyCollectors.push_back(std::move(Listener));
734 } // end namespace clang