CompilerInstance.h revision 5e35693721364673f8196e4f5a370f56b92e6053
1//===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
11#define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
12
13#include "clang/Frontend/CompilerInvocation.h"
14#include "clang/Lex/ModuleLoader.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/IntrusiveRefCntPtr.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/OwningPtr.h"
20#include <cassert>
21#include <list>
22#include <string>
23#include <utility>
24
25namespace llvm {
26class raw_fd_ostream;
27class Timer;
28}
29
30namespace clang {
31class ASTContext;
32class ASTConsumer;
33class ASTReader;
34class CodeCompleteConsumer;
35class DiagnosticsEngine;
36class DiagnosticConsumer;
37class ExternalASTSource;
38class FileEntry;
39class FileManager;
40class FrontendAction;
41class Module;
42class Preprocessor;
43class Sema;
44class SourceManager;
45class TargetInfo;
46
47/// CompilerInstance - Helper class for managing a single instance of the Clang
48/// compiler.
49///
50/// The CompilerInstance serves two purposes:
51///  (1) It manages the various objects which are necessary to run the compiler,
52///      for example the preprocessor, the target information, and the AST
53///      context.
54///  (2) It provides utility routines for constructing and manipulating the
55///      common Clang objects.
56///
57/// The compiler instance generally owns the instance of all the objects that it
58/// manages. However, clients can still share objects by manually setting the
59/// object and retaking ownership prior to destroying the CompilerInstance.
60///
61/// The compiler instance is intended to simplify clients, but not to lock them
62/// in to the compiler instance for everything. When possible, utility functions
63/// come in two forms; a short form that reuses the CompilerInstance objects,
64/// and a long form that takes explicit instances of any required objects.
65class CompilerInstance : public ModuleLoader {
66  /// The options used in this compiler instance.
67  llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation;
68
69  /// The diagnostics engine instance.
70  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
71
72  /// The target being compiled for.
73  llvm::IntrusiveRefCntPtr<TargetInfo> Target;
74
75  /// The file manager.
76  llvm::IntrusiveRefCntPtr<FileManager> FileMgr;
77
78  /// The source manager.
79  llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr;
80
81  /// The preprocessor.
82  llvm::IntrusiveRefCntPtr<Preprocessor> PP;
83
84  /// The AST context.
85  llvm::IntrusiveRefCntPtr<ASTContext> Context;
86
87  /// The AST consumer.
88  llvm::OwningPtr<ASTConsumer> Consumer;
89
90  /// The code completion consumer.
91  llvm::OwningPtr<CodeCompleteConsumer> CompletionConsumer;
92
93  /// \brief The semantic analysis object.
94  llvm::OwningPtr<Sema> TheSema;
95
96  /// \brief The frontend timer
97  llvm::OwningPtr<llvm::Timer> FrontendTimer;
98
99  /// \brief Non-owning reference to the ASTReader, if one exists.
100  ASTReader *ModuleManager;
101
102  /// \brief The set of top-level modules that has already been loaded,
103  /// along with the module map
104  llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
105
106  /// \brief The location of the module-import keyword for the last module
107  /// import.
108  SourceLocation LastModuleImportLoc;
109
110  /// \brief The result of the last module import.
111  ///
112  Module *LastModuleImportResult;
113
114  /// \brief Holds information about the output file.
115  ///
116  /// If TempFilename is not empty we must rename it to Filename at the end.
117  /// TempFilename may be empty and Filename non empty if creating the temporary
118  /// failed.
119  struct OutputFile {
120    std::string Filename;
121    std::string TempFilename;
122    raw_ostream *OS;
123
124    OutputFile(const std::string &filename, const std::string &tempFilename,
125               raw_ostream *os)
126      : Filename(filename), TempFilename(tempFilename), OS(os) { }
127  };
128
129  /// The list of active output files.
130  std::list<OutputFile> OutputFiles;
131
132  void operator=(const CompilerInstance &);  // DO NOT IMPLEMENT
133  CompilerInstance(const CompilerInstance&); // DO NOT IMPLEMENT
134public:
135  CompilerInstance();
136  ~CompilerInstance();
137
138  /// @name High-Level Operations
139  /// {
140
141  /// ExecuteAction - Execute the provided action against the compiler's
142  /// CompilerInvocation object.
143  ///
144  /// This function makes the following assumptions:
145  ///
146  ///  - The invocation options should be initialized. This function does not
147  ///    handle the '-help' or '-version' options, clients should handle those
148  ///    directly.
149  ///
150  ///  - The diagnostics engine should have already been created by the client.
151  ///
152  ///  - No other CompilerInstance state should have been initialized (this is
153  ///    an unchecked error).
154  ///
155  ///  - Clients should have initialized any LLVM target features that may be
156  ///    required.
157  ///
158  ///  - Clients should eventually call llvm_shutdown() upon the completion of
159  ///    this routine to ensure that any managed objects are properly destroyed.
160  ///
161  /// Note that this routine may write output to 'stderr'.
162  ///
163  /// \param Act - The action to execute.
164  /// \return - True on success.
165  //
166  // FIXME: This function should take the stream to write any debugging /
167  // verbose output to as an argument.
168  //
169  // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
170  // of the context or else not CompilerInstance specific.
171  bool ExecuteAction(FrontendAction &Act);
172
173  /// }
174  /// @name Compiler Invocation and Options
175  /// {
176
177  bool hasInvocation() const { return Invocation != 0; }
178
179  CompilerInvocation &getInvocation() {
180    assert(Invocation && "Compiler instance has no invocation!");
181    return *Invocation;
182  }
183
184  /// setInvocation - Replace the current invocation.
185  void setInvocation(CompilerInvocation *Value);
186
187  /// }
188  /// @name Forwarding Methods
189  /// {
190
191  AnalyzerOptions &getAnalyzerOpts() {
192    return Invocation->getAnalyzerOpts();
193  }
194  const AnalyzerOptions &getAnalyzerOpts() const {
195    return Invocation->getAnalyzerOpts();
196  }
197
198  CodeGenOptions &getCodeGenOpts() {
199    return Invocation->getCodeGenOpts();
200  }
201  const CodeGenOptions &getCodeGenOpts() const {
202    return Invocation->getCodeGenOpts();
203  }
204
205  DependencyOutputOptions &getDependencyOutputOpts() {
206    return Invocation->getDependencyOutputOpts();
207  }
208  const DependencyOutputOptions &getDependencyOutputOpts() const {
209    return Invocation->getDependencyOutputOpts();
210  }
211
212  DiagnosticOptions &getDiagnosticOpts() {
213    return Invocation->getDiagnosticOpts();
214  }
215  const DiagnosticOptions &getDiagnosticOpts() const {
216    return Invocation->getDiagnosticOpts();
217  }
218
219  const FileSystemOptions &getFileSystemOpts() const {
220    return Invocation->getFileSystemOpts();
221  }
222
223  FrontendOptions &getFrontendOpts() {
224    return Invocation->getFrontendOpts();
225  }
226  const FrontendOptions &getFrontendOpts() const {
227    return Invocation->getFrontendOpts();
228  }
229
230  HeaderSearchOptions &getHeaderSearchOpts() {
231    return Invocation->getHeaderSearchOpts();
232  }
233  const HeaderSearchOptions &getHeaderSearchOpts() const {
234    return Invocation->getHeaderSearchOpts();
235  }
236
237  LangOptions &getLangOpts() {
238    return *Invocation->getLangOpts();
239  }
240  const LangOptions &getLangOpts() const {
241    return *Invocation->getLangOpts();
242  }
243
244  PreprocessorOptions &getPreprocessorOpts() {
245    return Invocation->getPreprocessorOpts();
246  }
247  const PreprocessorOptions &getPreprocessorOpts() const {
248    return Invocation->getPreprocessorOpts();
249  }
250
251  PreprocessorOutputOptions &getPreprocessorOutputOpts() {
252    return Invocation->getPreprocessorOutputOpts();
253  }
254  const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
255    return Invocation->getPreprocessorOutputOpts();
256  }
257
258  TargetOptions &getTargetOpts() {
259    return Invocation->getTargetOpts();
260  }
261  const TargetOptions &getTargetOpts() const {
262    return Invocation->getTargetOpts();
263  }
264
265  /// }
266  /// @name Diagnostics Engine
267  /// {
268
269  bool hasDiagnostics() const { return Diagnostics != 0; }
270
271  /// Get the current diagnostics engine.
272  DiagnosticsEngine &getDiagnostics() const {
273    assert(Diagnostics && "Compiler instance has no diagnostics!");
274    return *Diagnostics;
275  }
276
277  /// setDiagnostics - Replace the current diagnostics engine.
278  void setDiagnostics(DiagnosticsEngine *Value);
279
280  DiagnosticConsumer &getDiagnosticClient() const {
281    assert(Diagnostics && Diagnostics->getClient() &&
282           "Compiler instance has no diagnostic client!");
283    return *Diagnostics->getClient();
284  }
285
286  /// }
287  /// @name Target Info
288  /// {
289
290  bool hasTarget() const { return Target != 0; }
291
292  TargetInfo &getTarget() const {
293    assert(Target && "Compiler instance has no target!");
294    return *Target;
295  }
296
297  /// Replace the current diagnostics engine.
298  void setTarget(TargetInfo *Value);
299
300  /// }
301  /// @name File Manager
302  /// {
303
304  bool hasFileManager() const { return FileMgr != 0; }
305
306  /// Return the current file manager to the caller.
307  FileManager &getFileManager() const {
308    assert(FileMgr && "Compiler instance has no file manager!");
309    return *FileMgr;
310  }
311
312  void resetAndLeakFileManager() {
313    FileMgr.resetWithoutRelease();
314  }
315
316  /// setFileManager - Replace the current file manager.
317  void setFileManager(FileManager *Value);
318
319  /// }
320  /// @name Source Manager
321  /// {
322
323  bool hasSourceManager() const { return SourceMgr != 0; }
324
325  /// Return the current source manager.
326  SourceManager &getSourceManager() const {
327    assert(SourceMgr && "Compiler instance has no source manager!");
328    return *SourceMgr;
329  }
330
331  void resetAndLeakSourceManager() {
332    SourceMgr.resetWithoutRelease();
333  }
334
335  /// setSourceManager - Replace the current source manager.
336  void setSourceManager(SourceManager *Value);
337
338  /// }
339  /// @name Preprocessor
340  /// {
341
342  bool hasPreprocessor() const { return PP != 0; }
343
344  /// Return the current preprocessor.
345  Preprocessor &getPreprocessor() const {
346    assert(PP && "Compiler instance has no preprocessor!");
347    return *PP;
348  }
349
350  void resetAndLeakPreprocessor() {
351    PP.resetWithoutRelease();
352  }
353
354  /// Replace the current preprocessor.
355  void setPreprocessor(Preprocessor *Value);
356
357  /// }
358  /// @name ASTContext
359  /// {
360
361  bool hasASTContext() const { return Context != 0; }
362
363  ASTContext &getASTContext() const {
364    assert(Context && "Compiler instance has no AST context!");
365    return *Context;
366  }
367
368  void resetAndLeakASTContext() {
369    Context.resetWithoutRelease();
370  }
371
372  /// setASTContext - Replace the current AST context.
373  void setASTContext(ASTContext *Value);
374
375  /// \brief Replace the current Sema; the compiler instance takes ownership
376  /// of S.
377  void setSema(Sema *S);
378
379  /// }
380  /// @name ASTConsumer
381  /// {
382
383  bool hasASTConsumer() const { return Consumer != 0; }
384
385  ASTConsumer &getASTConsumer() const {
386    assert(Consumer && "Compiler instance has no AST consumer!");
387    return *Consumer;
388  }
389
390  /// takeASTConsumer - Remove the current AST consumer and give ownership to
391  /// the caller.
392  ASTConsumer *takeASTConsumer() { return Consumer.take(); }
393
394  /// setASTConsumer - Replace the current AST consumer; the compiler instance
395  /// takes ownership of \arg Value.
396  void setASTConsumer(ASTConsumer *Value);
397
398  /// }
399  /// @name Semantic analysis
400  /// {
401  bool hasSema() const { return TheSema != 0; }
402
403  Sema &getSema() const {
404    assert(TheSema && "Compiler instance has no Sema object!");
405    return *TheSema;
406  }
407
408  Sema *takeSema() { return TheSema.take(); }
409
410  /// }
411  /// @name Module Management
412  /// {
413
414  ASTReader *getModuleManager() const { return ModuleManager; }
415
416  /// }
417  /// @name Code Completion
418  /// {
419
420  bool hasCodeCompletionConsumer() const { return CompletionConsumer != 0; }
421
422  CodeCompleteConsumer &getCodeCompletionConsumer() const {
423    assert(CompletionConsumer &&
424           "Compiler instance has no code completion consumer!");
425    return *CompletionConsumer;
426  }
427
428  /// takeCodeCompletionConsumer - Remove the current code completion consumer
429  /// and give ownership to the caller.
430  CodeCompleteConsumer *takeCodeCompletionConsumer() {
431    return CompletionConsumer.take();
432  }
433
434  /// setCodeCompletionConsumer - Replace the current code completion consumer;
435  /// the compiler instance takes ownership of \arg Value.
436  void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
437
438  /// }
439  /// @name Frontend timer
440  /// {
441
442  bool hasFrontendTimer() const { return FrontendTimer != 0; }
443
444  llvm::Timer &getFrontendTimer() const {
445    assert(FrontendTimer && "Compiler instance has no frontend timer!");
446    return *FrontendTimer;
447  }
448
449  /// }
450  /// @name Output Files
451  /// {
452
453  /// addOutputFile - Add an output file onto the list of tracked output files.
454  ///
455  /// \param OutFile - The output file info.
456  void addOutputFile(const OutputFile &OutFile);
457
458  /// clearOutputFiles - Clear the output file list, destroying the contained
459  /// output streams.
460  ///
461  /// \param EraseFiles - If true, attempt to erase the files from disk.
462  void clearOutputFiles(bool EraseFiles);
463
464  /// }
465  /// @name Construction Utility Methods
466  /// {
467
468  /// Create the diagnostics engine using the invocation's diagnostic options
469  /// and replace any existing one with it.
470  ///
471  /// Note that this routine also replaces the diagnostic client,
472  /// allocating one if one is not provided.
473  ///
474  /// \param Client If non-NULL, a diagnostic client that will be
475  /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
476  /// unit.
477  ///
478  /// \param ShouldOwnClient If Client is non-NULL, specifies whether
479  /// the diagnostic object should take ownership of the client.
480  ///
481  /// \param ShouldCloneClient If Client is non-NULL, specifies whether that
482  /// client should be cloned.
483  void createDiagnostics(int Argc, const char* const *Argv,
484                         DiagnosticConsumer *Client = 0,
485                         bool ShouldOwnClient = true,
486                         bool ShouldCloneClient = true);
487
488  /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
489  ///
490  /// The \arg Argc and \arg Argv arguments are used only for logging purposes,
491  /// when the diagnostic options indicate that the compiler should output
492  /// logging information.
493  ///
494  /// If no diagnostic client is provided, this creates a
495  /// DiagnosticConsumer that is owned by the returned diagnostic
496  /// object, if using directly the caller is responsible for
497  /// releasing the returned DiagnosticsEngine's client eventually.
498  ///
499  /// \param Opts - The diagnostic options; note that the created text
500  /// diagnostic object contains a reference to these options and its lifetime
501  /// must extend past that of the diagnostic engine.
502  ///
503  /// \param Client If non-NULL, a diagnostic client that will be
504  /// attached to (and, then, owned by) the returned DiagnosticsEngine
505  /// object.
506  ///
507  /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
508  /// used by some diagnostics printers (for logging purposes only).
509  ///
510  /// \return The new object on success, or null on failure.
511  static llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
512  createDiagnostics(const DiagnosticOptions &Opts, int Argc,
513                    const char* const *Argv,
514                    DiagnosticConsumer *Client = 0,
515                    bool ShouldOwnClient = true,
516                    bool ShouldCloneClient = true,
517                    const CodeGenOptions *CodeGenOpts = 0);
518
519  /// Create the file manager and replace any existing one with it.
520  void createFileManager();
521
522  /// Create the source manager and replace any existing one with it.
523  void createSourceManager(FileManager &FileMgr);
524
525  /// Create the preprocessor, using the invocation, file, and source managers,
526  /// and replace any existing one with it.
527  void createPreprocessor();
528
529  /// Create the AST context.
530  void createASTContext();
531
532  /// Create an external AST source to read a PCH file and attach it to the AST
533  /// context.
534  void createPCHExternalASTSource(StringRef Path,
535                                  bool DisablePCHValidation,
536                                  bool DisableStatCache,
537                                  void *DeserializationListener);
538
539  /// Create an external AST source to read a PCH file.
540  ///
541  /// \return - The new object on success, or null on failure.
542  static ExternalASTSource *
543  createPCHExternalASTSource(StringRef Path, const std::string &Sysroot,
544                             bool DisablePCHValidation,
545                             bool DisableStatCache,
546                             Preprocessor &PP, ASTContext &Context,
547                             void *DeserializationListener, bool Preamble);
548
549  /// Create a code completion consumer using the invocation; note that this
550  /// will cause the source manager to truncate the input source file at the
551  /// completion point.
552  void createCodeCompletionConsumer();
553
554  /// Create a code completion consumer to print code completion results, at
555  /// \arg Filename, \arg Line, and \arg Column, to the given output stream \arg
556  /// OS.
557  static CodeCompleteConsumer *
558  createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
559                               unsigned Line, unsigned Column,
560                               bool ShowMacros,
561                               bool ShowCodePatterns, bool ShowGlobals,
562                               raw_ostream &OS);
563
564  /// \brief Create the Sema object to be used for parsing.
565  void createSema(TranslationUnitKind TUKind,
566                  CodeCompleteConsumer *CompletionConsumer);
567
568  /// Create the frontend timer and replace any existing one with it.
569  void createFrontendTimer();
570
571  /// Create the default output file (from the invocation's options) and add it
572  /// to the list of tracked output files.
573  ///
574  /// \return - Null on error.
575  llvm::raw_fd_ostream *
576  createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
577                          StringRef Extension = "");
578
579  /// Create a new output file and add it to the list of tracked output files,
580  /// optionally deriving the output path name.
581  ///
582  /// \return - Null on error.
583  llvm::raw_fd_ostream *
584  createOutputFile(StringRef OutputPath,
585                   bool Binary = true, bool RemoveFileOnSignal = true,
586                   StringRef BaseInput = "",
587                   StringRef Extension = "",
588                   bool UseTemporary = false);
589
590  /// Create a new output file, optionally deriving the output path name.
591  ///
592  /// If \arg OutputPath is empty, then createOutputFile will derive an output
593  /// path location as \arg BaseInput, with any suffix removed, and \arg
594  /// Extension appended. If OutputPath is not stdout and \arg UseTemporary
595  /// is true, createOutputFile will create a new temporary file that must be
596  /// renamed to OutputPath in the end.
597  ///
598  /// \param OutputPath - If given, the path to the output file.
599  /// \param Error [out] - On failure, the error message.
600  /// \param BaseInput - If \arg OutputPath is empty, the input path name to use
601  /// for deriving the output path.
602  /// \param Extension - The extension to use for derived output names.
603  /// \param Binary - The mode to open the file in.
604  /// \param RemoveFileOnSignal - Whether the file should be registered with
605  /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
606  /// multithreaded use, as the underlying signal mechanism is not reentrant
607  /// \param UseTemporary - Create a new temporary file that must be renamed to
608  ///         OutputPath in the end
609  /// \param ResultPathName [out] - If given, the result path name will be
610  /// stored here on success.
611  /// \param TempPathName [out] - If given, the temporary file path name
612  /// will be stored here on success.
613  static llvm::raw_fd_ostream *
614  createOutputFile(StringRef OutputPath, std::string &Error,
615                   bool Binary = true, bool RemoveFileOnSignal = true,
616                   StringRef BaseInput = "",
617                   StringRef Extension = "",
618                   bool UseTemporary = false,
619                   std::string *ResultPathName = 0,
620                   std::string *TempPathName = 0);
621
622  /// }
623  /// @name Initialization Utility Methods
624  /// {
625
626  /// InitializeSourceManager - Initialize the source manager to set InputFile
627  /// as the main file.
628  ///
629  /// \return True on success.
630  bool InitializeSourceManager(StringRef InputFile);
631
632  /// InitializeSourceManager - Initialize the source manager to set InputFile
633  /// as the main file.
634  ///
635  /// \return True on success.
636  static bool InitializeSourceManager(StringRef InputFile,
637                                      DiagnosticsEngine &Diags,
638                                      FileManager &FileMgr,
639                                      SourceManager &SourceMgr,
640                                      const FrontendOptions &Opts);
641
642  /// }
643
644  virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
645                             Module::NameVisibilityKind Visibility);
646};
647
648} // end namespace clang
649
650#endif
651