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/Basic/Diagnostic.h"
14 #include "clang/Basic/SourceManager.h"
15 #include "clang/Frontend/CompilerInvocation.h"
16 #include "clang/Lex/ModuleLoader.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/IntrusiveRefCntPtr.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/StringRef.h"
36 class CodeCompleteConsumer;
37 class DiagnosticsEngine;
38 class DiagnosticConsumer;
39 class ExternalASTSource;
49 /// CompilerInstance - Helper class for managing a single instance of the Clang
52 /// The CompilerInstance serves two purposes:
53 /// (1) It manages the various objects which are necessary to run the compiler,
54 /// for example the preprocessor, the target information, and the AST
56 /// (2) It provides utility routines for constructing and manipulating the
57 /// common Clang objects.
59 /// The compiler instance generally owns the instance of all the objects that it
60 /// manages. However, clients can still share objects by manually setting the
61 /// object and retaking ownership prior to destroying the CompilerInstance.
63 /// The compiler instance is intended to simplify clients, but not to lock them
64 /// in to the compiler instance for everything. When possible, utility functions
65 /// come in two forms; a short form that reuses the CompilerInstance objects,
66 /// and a long form that takes explicit instances of any required objects.
67 class CompilerInstance : public ModuleLoader {
68 /// The options used in this compiler instance.
69 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
71 /// The diagnostics engine instance.
72 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
74 /// The target being compiled for.
75 IntrusiveRefCntPtr<TargetInfo> Target;
78 IntrusiveRefCntPtr<FileManager> FileMgr;
80 /// The source manager.
81 IntrusiveRefCntPtr<SourceManager> SourceMgr;
84 IntrusiveRefCntPtr<Preprocessor> PP;
87 IntrusiveRefCntPtr<ASTContext> Context;
90 OwningPtr<ASTConsumer> Consumer;
92 /// The code completion consumer.
93 OwningPtr<CodeCompleteConsumer> CompletionConsumer;
95 /// \brief The semantic analysis object.
96 OwningPtr<Sema> TheSema;
98 /// \brief The frontend timer
99 OwningPtr<llvm::Timer> FrontendTimer;
101 /// \brief Non-owning reference to the ASTReader, if one exists.
102 ASTReader *ModuleManager;
104 /// \brief The set of top-level modules that has already been loaded,
105 /// along with the module map
106 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
108 /// \brief The location of the module-import keyword for the last module
110 SourceLocation LastModuleImportLoc;
112 /// \brief The result of the last module import.
114 ModuleLoadResult LastModuleImportResult;
116 /// \brief Whether we should (re)build the global module index once we
117 /// have finished with this translation unit.
118 bool BuildGlobalModuleIndex;
120 /// \brief One or more modules failed to build.
121 bool ModuleBuildFailed;
123 /// \brief Holds information about the output file.
125 /// If TempFilename is not empty we must rename it to Filename at the end.
126 /// TempFilename may be empty and Filename non empty if creating the temporary
129 std::string Filename;
130 std::string TempFilename;
133 OutputFile(const std::string &filename, const std::string &tempFilename,
135 : Filename(filename), TempFilename(tempFilename), OS(os) { }
138 /// The list of active output files.
139 std::list<OutputFile> OutputFiles;
141 CompilerInstance(const CompilerInstance &) LLVM_DELETED_FUNCTION;
142 void operator=(const CompilerInstance &) LLVM_DELETED_FUNCTION;
147 /// @name High-Level Operations
150 /// ExecuteAction - Execute the provided action against the compiler's
151 /// CompilerInvocation object.
153 /// This function makes the following assumptions:
155 /// - The invocation options should be initialized. This function does not
156 /// handle the '-help' or '-version' options, clients should handle those
159 /// - The diagnostics engine should have already been created by the client.
161 /// - No other CompilerInstance state should have been initialized (this is
162 /// an unchecked error).
164 /// - Clients should have initialized any LLVM target features that may be
167 /// - Clients should eventually call llvm_shutdown() upon the completion of
168 /// this routine to ensure that any managed objects are properly destroyed.
170 /// Note that this routine may write output to 'stderr'.
172 /// \param Act - The action to execute.
173 /// \return - True on success.
175 // FIXME: This function should take the stream to write any debugging /
176 // verbose output to as an argument.
178 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
179 // of the context or else not CompilerInstance specific.
180 bool ExecuteAction(FrontendAction &Act);
183 /// @name Compiler Invocation and Options
186 bool hasInvocation() const { return Invocation != 0; }
188 CompilerInvocation &getInvocation() {
189 assert(Invocation && "Compiler instance has no invocation!");
193 /// setInvocation - Replace the current invocation.
194 void setInvocation(CompilerInvocation *Value);
196 /// \brief Indicates whether we should (re)build the global module index.
197 bool shouldBuildGlobalModuleIndex() const;
199 /// \brief Set the flag indicating whether we should (re)build the global
201 void setBuildGlobalModuleIndex(bool Build) {
202 BuildGlobalModuleIndex = Build;
206 /// @name Forwarding Methods
209 AnalyzerOptionsRef getAnalyzerOpts() {
210 return Invocation->getAnalyzerOpts();
213 CodeGenOptions &getCodeGenOpts() {
214 return Invocation->getCodeGenOpts();
216 const CodeGenOptions &getCodeGenOpts() const {
217 return Invocation->getCodeGenOpts();
220 DependencyOutputOptions &getDependencyOutputOpts() {
221 return Invocation->getDependencyOutputOpts();
223 const DependencyOutputOptions &getDependencyOutputOpts() const {
224 return Invocation->getDependencyOutputOpts();
227 DiagnosticOptions &getDiagnosticOpts() {
228 return Invocation->getDiagnosticOpts();
230 const DiagnosticOptions &getDiagnosticOpts() const {
231 return Invocation->getDiagnosticOpts();
234 const FileSystemOptions &getFileSystemOpts() const {
235 return Invocation->getFileSystemOpts();
238 FrontendOptions &getFrontendOpts() {
239 return Invocation->getFrontendOpts();
241 const FrontendOptions &getFrontendOpts() const {
242 return Invocation->getFrontendOpts();
245 HeaderSearchOptions &getHeaderSearchOpts() {
246 return Invocation->getHeaderSearchOpts();
248 const HeaderSearchOptions &getHeaderSearchOpts() const {
249 return Invocation->getHeaderSearchOpts();
252 LangOptions &getLangOpts() {
253 return *Invocation->getLangOpts();
255 const LangOptions &getLangOpts() const {
256 return *Invocation->getLangOpts();
259 PreprocessorOptions &getPreprocessorOpts() {
260 return Invocation->getPreprocessorOpts();
262 const PreprocessorOptions &getPreprocessorOpts() const {
263 return Invocation->getPreprocessorOpts();
266 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
267 return Invocation->getPreprocessorOutputOpts();
269 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
270 return Invocation->getPreprocessorOutputOpts();
273 TargetOptions &getTargetOpts() {
274 return Invocation->getTargetOpts();
276 const TargetOptions &getTargetOpts() const {
277 return Invocation->getTargetOpts();
281 /// @name Diagnostics Engine
284 bool hasDiagnostics() const { return Diagnostics != 0; }
286 /// Get the current diagnostics engine.
287 DiagnosticsEngine &getDiagnostics() const {
288 assert(Diagnostics && "Compiler instance has no diagnostics!");
292 /// setDiagnostics - Replace the current diagnostics engine.
293 void setDiagnostics(DiagnosticsEngine *Value);
295 DiagnosticConsumer &getDiagnosticClient() const {
296 assert(Diagnostics && Diagnostics->getClient() &&
297 "Compiler instance has no diagnostic client!");
298 return *Diagnostics->getClient();
302 /// @name Target Info
305 bool hasTarget() const { return Target != 0; }
307 TargetInfo &getTarget() const {
308 assert(Target && "Compiler instance has no target!");
312 /// Replace the current diagnostics engine.
313 void setTarget(TargetInfo *Value);
316 /// @name File Manager
319 bool hasFileManager() const { return FileMgr != 0; }
321 /// Return the current file manager to the caller.
322 FileManager &getFileManager() const {
323 assert(FileMgr && "Compiler instance has no file manager!");
327 void resetAndLeakFileManager() {
328 FileMgr.resetWithoutRelease();
331 /// setFileManager - Replace the current file manager.
332 void setFileManager(FileManager *Value);
335 /// @name Source Manager
338 bool hasSourceManager() const { return SourceMgr != 0; }
340 /// Return the current source manager.
341 SourceManager &getSourceManager() const {
342 assert(SourceMgr && "Compiler instance has no source manager!");
346 void resetAndLeakSourceManager() {
347 SourceMgr.resetWithoutRelease();
350 /// setSourceManager - Replace the current source manager.
351 void setSourceManager(SourceManager *Value);
354 /// @name Preprocessor
357 bool hasPreprocessor() const { return PP != 0; }
359 /// Return the current preprocessor.
360 Preprocessor &getPreprocessor() const {
361 assert(PP && "Compiler instance has no preprocessor!");
365 void resetAndLeakPreprocessor() {
366 PP.resetWithoutRelease();
369 /// Replace the current preprocessor.
370 void setPreprocessor(Preprocessor *Value);
376 bool hasASTContext() const { return Context != 0; }
378 ASTContext &getASTContext() const {
379 assert(Context && "Compiler instance has no AST context!");
383 void resetAndLeakASTContext() {
384 Context.resetWithoutRelease();
387 /// setASTContext - Replace the current AST context.
388 void setASTContext(ASTContext *Value);
390 /// \brief Replace the current Sema; the compiler instance takes ownership
392 void setSema(Sema *S);
395 /// @name ASTConsumer
398 bool hasASTConsumer() const { return Consumer != 0; }
400 ASTConsumer &getASTConsumer() const {
401 assert(Consumer && "Compiler instance has no AST consumer!");
405 /// takeASTConsumer - Remove the current AST consumer and give ownership to
407 ASTConsumer *takeASTConsumer() { return Consumer.take(); }
409 /// setASTConsumer - Replace the current AST consumer; the compiler instance
410 /// takes ownership of \p Value.
411 void setASTConsumer(ASTConsumer *Value);
414 /// @name Semantic analysis
416 bool hasSema() const { return TheSema != 0; }
418 Sema &getSema() const {
419 assert(TheSema && "Compiler instance has no Sema object!");
423 Sema *takeSema() { return TheSema.take(); }
426 /// @name Module Management
429 ASTReader *getModuleManager() const { return ModuleManager; }
430 void setModuleManager(ASTReader *Reader) { ModuleManager = Reader; }
433 /// @name Code Completion
436 bool hasCodeCompletionConsumer() const { return CompletionConsumer != 0; }
438 CodeCompleteConsumer &getCodeCompletionConsumer() const {
439 assert(CompletionConsumer &&
440 "Compiler instance has no code completion consumer!");
441 return *CompletionConsumer;
444 /// takeCodeCompletionConsumer - Remove the current code completion consumer
445 /// and give ownership to the caller.
446 CodeCompleteConsumer *takeCodeCompletionConsumer() {
447 return CompletionConsumer.take();
450 /// setCodeCompletionConsumer - Replace the current code completion consumer;
451 /// the compiler instance takes ownership of \p Value.
452 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
455 /// @name Frontend timer
458 bool hasFrontendTimer() const { return FrontendTimer != 0; }
460 llvm::Timer &getFrontendTimer() const {
461 assert(FrontendTimer && "Compiler instance has no frontend timer!");
462 return *FrontendTimer;
466 /// @name Output Files
469 /// addOutputFile - Add an output file onto the list of tracked output files.
471 /// \param OutFile - The output file info.
472 void addOutputFile(const OutputFile &OutFile);
474 /// clearOutputFiles - Clear the output file list, destroying the contained
477 /// \param EraseFiles - If true, attempt to erase the files from disk.
478 void clearOutputFiles(bool EraseFiles);
481 /// @name Construction Utility Methods
484 /// Create the diagnostics engine using the invocation's diagnostic options
485 /// and replace any existing one with it.
487 /// Note that this routine also replaces the diagnostic client,
488 /// allocating one if one is not provided.
490 /// \param Client If non-NULL, a diagnostic client that will be
491 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
494 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
495 /// the diagnostic object should take ownership of the client.
496 void createDiagnostics(DiagnosticConsumer *Client = 0,
497 bool ShouldOwnClient = true);
499 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
501 /// If no diagnostic client is provided, this creates a
502 /// DiagnosticConsumer that is owned by the returned diagnostic
503 /// object, if using directly the caller is responsible for
504 /// releasing the returned DiagnosticsEngine's client eventually.
506 /// \param Opts - The diagnostic options; note that the created text
507 /// diagnostic object contains a reference to these options.
509 /// \param Client If non-NULL, a diagnostic client that will be
510 /// attached to (and, then, owned by) the returned DiagnosticsEngine
513 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
514 /// used by some diagnostics printers (for logging purposes only).
516 /// \return The new object on success, or null on failure.
517 static IntrusiveRefCntPtr<DiagnosticsEngine>
518 createDiagnostics(DiagnosticOptions *Opts,
519 DiagnosticConsumer *Client = 0,
520 bool ShouldOwnClient = true,
521 const CodeGenOptions *CodeGenOpts = 0);
523 /// Create the file manager and replace any existing one with it.
524 void createFileManager();
526 /// Create the source manager and replace any existing one with it.
527 void createSourceManager(FileManager &FileMgr);
529 /// Create the preprocessor, using the invocation, file, and source managers,
530 /// and replace any existing one with it.
531 void createPreprocessor();
533 /// Create the AST context.
534 void createASTContext();
536 /// Create an external AST source to read a PCH file and attach it to the AST
538 void createPCHExternalASTSource(StringRef Path,
539 bool DisablePCHValidation,
540 bool AllowPCHWithCompilerErrors,
541 void *DeserializationListener);
543 /// Create an external AST source to read a PCH file.
545 /// \return - The new object on success, or null on failure.
546 static ExternalASTSource *
547 createPCHExternalASTSource(StringRef Path, const std::string &Sysroot,
548 bool DisablePCHValidation,
549 bool AllowPCHWithCompilerErrors,
550 Preprocessor &PP, ASTContext &Context,
551 void *DeserializationListener, bool Preamble,
552 bool UseGlobalModuleIndex);
554 /// Create a code completion consumer using the invocation; note that this
555 /// will cause the source manager to truncate the input source file at the
556 /// completion point.
557 void createCodeCompletionConsumer();
559 /// Create a code completion consumer to print code completion results, at
560 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
561 static CodeCompleteConsumer *
562 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
563 unsigned Line, unsigned Column,
564 const CodeCompleteOptions &Opts,
567 /// \brief Create the Sema object to be used for parsing.
568 void createSema(TranslationUnitKind TUKind,
569 CodeCompleteConsumer *CompletionConsumer);
571 /// Create the frontend timer and replace any existing one with it.
572 void createFrontendTimer();
574 /// Create the default output file (from the invocation's options) and add it
575 /// to the list of tracked output files.
577 /// The files created by this function always use temporary files to write to
578 /// their result (that is, the data is written to a temporary file which will
579 /// atomically replace the target output on success).
581 /// \return - Null on error.
582 llvm::raw_fd_ostream *
583 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
584 StringRef Extension = "");
586 /// Create a new output file and add it to the list of tracked output files,
587 /// optionally deriving the output path name.
589 /// \return - Null on error.
590 llvm::raw_fd_ostream *
591 createOutputFile(StringRef OutputPath,
592 bool Binary = true, bool RemoveFileOnSignal = true,
593 StringRef BaseInput = "",
594 StringRef Extension = "",
595 bool UseTemporary = false,
596 bool CreateMissingDirectories = false);
598 /// Create a new output file, optionally deriving the output path name.
600 /// If \p OutputPath is empty, then createOutputFile will derive an output
601 /// path location as \p BaseInput, with any suffix removed, and \p Extension
602 /// appended. If \p OutputPath is not stdout and \p UseTemporary
603 /// is true, createOutputFile will create a new temporary file that must be
604 /// renamed to \p OutputPath in the end.
606 /// \param OutputPath - If given, the path to the output file.
607 /// \param Error [out] - On failure, the error message.
608 /// \param BaseInput - If \p OutputPath is empty, the input path name to use
609 /// for deriving the output path.
610 /// \param Extension - The extension to use for derived output names.
611 /// \param Binary - The mode to open the file in.
612 /// \param RemoveFileOnSignal - Whether the file should be registered with
613 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
614 /// multithreaded use, as the underlying signal mechanism is not reentrant
615 /// \param UseTemporary - Create a new temporary file that must be renamed to
616 /// OutputPath in the end.
617 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
618 /// missing directories in the output path.
619 /// \param ResultPathName [out] - If given, the result path name will be
620 /// stored here on success.
621 /// \param TempPathName [out] - If given, the temporary file path name
622 /// will be stored here on success.
623 static llvm::raw_fd_ostream *
624 createOutputFile(StringRef OutputPath, std::string &Error,
625 bool Binary = true, bool RemoveFileOnSignal = true,
626 StringRef BaseInput = "",
627 StringRef Extension = "",
628 bool UseTemporary = false,
629 bool CreateMissingDirectories = false,
630 std::string *ResultPathName = 0,
631 std::string *TempPathName = 0);
634 /// @name Initialization Utility Methods
637 /// InitializeSourceManager - Initialize the source manager to set InputFile
638 /// as the main file.
640 /// \return True on success.
641 bool InitializeSourceManager(const FrontendInputFile &Input);
643 /// InitializeSourceManager - Initialize the source manager to set InputFile
644 /// as the main file.
646 /// \return True on success.
647 static bool InitializeSourceManager(const FrontendInputFile &Input,
648 DiagnosticsEngine &Diags,
649 FileManager &FileMgr,
650 SourceManager &SourceMgr,
651 const FrontendOptions &Opts);
655 virtual ModuleLoadResult loadModule(SourceLocation ImportLoc,
657 Module::NameVisibilityKind Visibility,
658 bool IsInclusionDirective);
660 virtual void makeModuleVisible(Module *Mod,
661 Module::NameVisibilityKind Visibility,
662 SourceLocation ImportLoc,
667 } // end namespace clang