CompilerInstance.h revision 1d9f1fe7173e3084325f43c78af812a36d8a2a7c
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 "llvm/ADT/IntrusiveRefCntPtr.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/ADT/OwningPtr.h"
17#include <cassert>
18#include <list>
19#include <string>
20
21namespace llvm {
22class LLVMContext;
23class raw_ostream;
24class raw_fd_ostream;
25class Timer;
26}
27
28namespace clang {
29class ASTContext;
30class ASTConsumer;
31class CodeCompleteConsumer;
32class Diagnostic;
33class DiagnosticClient;
34class ExternalASTSource;
35class FileManager;
36class FrontendAction;
37class ASTReader;
38class Preprocessor;
39class Sema;
40class SourceManager;
41class TargetInfo;
42
43/// CompilerInstance - Helper class for managing a single instance of the Clang
44/// compiler.
45///
46/// The CompilerInstance serves two purposes:
47///  (1) It manages the various objects which are necessary to run the compiler,
48///      for example the preprocessor, the target information, and the AST
49///      context.
50///  (2) It provides utility routines for constructing and manipulating the
51///      common Clang objects.
52///
53/// The compiler instance generally owns the instance of all the objects that it
54/// manages. However, clients can still share objects by manually setting the
55/// object and retaking ownership prior to destroying the CompilerInstance.
56///
57/// The compiler instance is intended to simplify clients, but not to lock them
58/// in to the compiler instance for everything. When possible, utility functions
59/// come in two forms; a short form that reuses the CompilerInstance objects,
60/// and a long form that takes explicit instances of any required objects.
61class CompilerInstance {
62  /// The LLVM context used for this instance.
63  llvm::OwningPtr<llvm::LLVMContext> LLVMContext;
64
65  /// The options used in this compiler instance.
66  llvm::OwningPtr<CompilerInvocation> Invocation;
67
68  /// The diagnostics engine instance.
69  llvm::IntrusiveRefCntPtr<Diagnostic> Diagnostics;
70
71  /// The target being compiled for.
72  llvm::OwningPtr<TargetInfo> Target;
73
74  /// The file manager.
75  llvm::OwningPtr<FileManager> FileMgr;
76
77  /// The source manager.
78  llvm::OwningPtr<SourceManager> SourceMgr;
79
80  /// The preprocessor.
81  llvm::OwningPtr<Preprocessor> PP;
82
83  /// The AST context.
84  llvm::OwningPtr<ASTContext> Context;
85
86  /// The AST consumer.
87  llvm::OwningPtr<ASTConsumer> Consumer;
88
89  /// The code completion consumer.
90  llvm::OwningPtr<CodeCompleteConsumer> CompletionConsumer;
91
92  /// \brief The semantic analysis object.
93  llvm::OwningPtr<Sema> TheSema;
94
95  /// The frontend timer
96  llvm::OwningPtr<llvm::Timer> FrontendTimer;
97
98  /// \brief Holds information about the output file.
99  ///
100  /// If TempFilename is not empty we must rename it to Filename at the end.
101  /// TempFilename may be empty and Filename non empty if creating the temporary
102  /// failed.
103  struct OutputFile {
104    std::string Filename;
105    std::string TempFilename;
106    llvm::raw_ostream *OS;
107
108    OutputFile(const std::string &filename, const std::string &tempFilename,
109               llvm::raw_ostream *os)
110      : Filename(filename), TempFilename(tempFilename), OS(os) { }
111  };
112
113  /// The list of active output files.
114  std::list<OutputFile> OutputFiles;
115
116  void operator=(const CompilerInstance &);  // DO NOT IMPLEMENT
117  CompilerInstance(const CompilerInstance&); // DO NOT IMPLEMENT
118public:
119  CompilerInstance();
120  ~CompilerInstance();
121
122  /// @name High-Level Operations
123  /// {
124
125  /// ExecuteAction - Execute the provided action against the compiler's
126  /// CompilerInvocation object.
127  ///
128  /// This function makes the following assumptions:
129  ///
130  ///  - The invocation options should be initialized. This function does not
131  ///    handle the '-help' or '-version' options, clients should handle those
132  ///    directly.
133  ///
134  ///  - The diagnostics engine should have already been created by the client.
135  ///
136  ///  - No other CompilerInstance state should have been initialized (this is
137  ///    an unchecked error).
138  ///
139  ///  - Clients should have initialized any LLVM target features that may be
140  ///    required.
141  ///
142  ///  - Clients should eventually call llvm_shutdown() upon the completion of
143  ///    this routine to ensure that any managed objects are properly destroyed.
144  ///
145  /// Note that this routine may write output to 'stderr'.
146  ///
147  /// \param Act - The action to execute.
148  /// \return - True on success.
149  //
150  // FIXME: This function should take the stream to write any debugging /
151  // verbose output to as an argument.
152  //
153  // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
154  // of the context or else not CompilerInstance specific.
155  bool ExecuteAction(FrontendAction &Act);
156
157  /// }
158  /// @name LLVM Context
159  /// {
160
161  bool hasLLVMContext() const { return LLVMContext != 0; }
162
163  llvm::LLVMContext &getLLVMContext() const {
164    assert(LLVMContext && "Compiler instance has no LLVM context!");
165    return *LLVMContext;
166  }
167
168  llvm::LLVMContext *takeLLVMContext() { return LLVMContext.take(); }
169
170  /// setLLVMContext - Replace the current LLVM context and take ownership of
171  /// \arg Value.
172  void setLLVMContext(llvm::LLVMContext *Value);
173
174  /// }
175  /// @name Compiler Invocation and Options
176  /// {
177
178  bool hasInvocation() const { return Invocation != 0; }
179
180  CompilerInvocation &getInvocation() {
181    assert(Invocation && "Compiler instance has no invocation!");
182    return *Invocation;
183  }
184
185  CompilerInvocation *takeInvocation() { return Invocation.take(); }
186
187  /// setInvocation - Replace the current invocation; the compiler instance
188  /// takes ownership of \arg Value.
189  void setInvocation(CompilerInvocation *Value);
190
191  /// }
192  /// @name Forwarding Methods
193  /// {
194
195  AnalyzerOptions &getAnalyzerOpts() {
196    return Invocation->getAnalyzerOpts();
197  }
198  const AnalyzerOptions &getAnalyzerOpts() const {
199    return Invocation->getAnalyzerOpts();
200  }
201
202  CodeGenOptions &getCodeGenOpts() {
203    return Invocation->getCodeGenOpts();
204  }
205  const CodeGenOptions &getCodeGenOpts() const {
206    return Invocation->getCodeGenOpts();
207  }
208
209  DependencyOutputOptions &getDependencyOutputOpts() {
210    return Invocation->getDependencyOutputOpts();
211  }
212  const DependencyOutputOptions &getDependencyOutputOpts() const {
213    return Invocation->getDependencyOutputOpts();
214  }
215
216  DiagnosticOptions &getDiagnosticOpts() {
217    return Invocation->getDiagnosticOpts();
218  }
219  const DiagnosticOptions &getDiagnosticOpts() const {
220    return Invocation->getDiagnosticOpts();
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  Diagnostic &getDiagnostics() const {
272    assert(Diagnostics && "Compiler instance has no diagnostics!");
273    return *Diagnostics;
274  }
275
276  /// setDiagnostics - Replace the current diagnostics engine; the compiler
277  /// instance takes ownership of \arg Value.
278  void setDiagnostics(Diagnostic *Value);
279
280  DiagnosticClient &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  /// takeTarget - Remove the current diagnostics engine and give ownership
298  /// to the caller.
299  TargetInfo *takeTarget() { return Target.take(); }
300
301  /// setTarget - Replace the current diagnostics engine; the compiler
302  /// instance takes ownership of \arg Value.
303  void setTarget(TargetInfo *Value);
304
305  /// }
306  /// @name File Manager
307  /// {
308
309  bool hasFileManager() const { return FileMgr != 0; }
310
311  FileManager &getFileManager() const {
312    assert(FileMgr && "Compiler instance has no file manager!");
313    return *FileMgr;
314  }
315
316  /// takeFileManager - Remove the current file manager and give ownership to
317  /// the caller.
318  FileManager *takeFileManager() { return FileMgr.take(); }
319
320  /// setFileManager - Replace the current file manager; the compiler instance
321  /// takes ownership of \arg Value.
322  void setFileManager(FileManager *Value);
323
324  /// }
325  /// @name Source Manager
326  /// {
327
328  bool hasSourceManager() const { return SourceMgr != 0; }
329
330  SourceManager &getSourceManager() const {
331    assert(SourceMgr && "Compiler instance has no source manager!");
332    return *SourceMgr;
333  }
334
335  /// takeSourceManager - Remove the current source manager and give ownership
336  /// to the caller.
337  SourceManager *takeSourceManager() { return SourceMgr.take(); }
338
339  /// setSourceManager - Replace the current source manager; the compiler
340  /// instance takes ownership of \arg Value.
341  void setSourceManager(SourceManager *Value);
342
343  /// }
344  /// @name Preprocessor
345  /// {
346
347  bool hasPreprocessor() const { return PP != 0; }
348
349  Preprocessor &getPreprocessor() const {
350    assert(PP && "Compiler instance has no preprocessor!");
351    return *PP;
352  }
353
354  /// takePreprocessor - Remove the current preprocessor and give ownership to
355  /// the caller.
356  Preprocessor *takePreprocessor() { return PP.take(); }
357
358  /// setPreprocessor - Replace the current preprocessor; the compiler instance
359  /// takes ownership of \arg Value.
360  void setPreprocessor(Preprocessor *Value);
361
362  /// }
363  /// @name ASTContext
364  /// {
365
366  bool hasASTContext() const { return Context != 0; }
367
368  ASTContext &getASTContext() const {
369    assert(Context && "Compiler instance has no AST context!");
370    return *Context;
371  }
372
373  /// takeASTContext - Remove the current AST context and give ownership to the
374  /// caller.
375  ASTContext *takeASTContext() { return Context.take(); }
376
377  /// setASTContext - Replace the current AST context; the compiler instance
378  /// takes ownership of \arg Value.
379  void setASTContext(ASTContext *Value);
380
381  /// \brief Replace the current Sema; the compiler instance takes ownership
382  /// of S.
383  void setSema(Sema *S);
384
385  /// }
386  /// @name ASTConsumer
387  /// {
388
389  bool hasASTConsumer() const { return Consumer != 0; }
390
391  ASTConsumer &getASTConsumer() const {
392    assert(Consumer && "Compiler instance has no AST consumer!");
393    return *Consumer;
394  }
395
396  /// takeASTConsumer - Remove the current AST consumer and give ownership to
397  /// the caller.
398  ASTConsumer *takeASTConsumer() { return Consumer.take(); }
399
400  /// setASTConsumer - Replace the current AST consumer; the compiler instance
401  /// takes ownership of \arg Value.
402  void setASTConsumer(ASTConsumer *Value);
403
404  /// }
405  /// @name Semantic analysis
406  /// {
407  bool hasSema() const { return TheSema != 0; }
408
409  Sema &getSema() const {
410    assert(TheSema && "Compiler instance has no Sema object!");
411    return *TheSema;
412  }
413
414  Sema *takeSema() { return TheSema.take(); }
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  /// getOutputFileList - Get the list of (path, output stream) pairs of output
454  /// files; the path may be empty but the stream will always be non-null.
455  const std::list< std::pair<std::string,
456                             llvm::raw_ostream*> > &getOutputFileList() const;
457
458  /// addOutputFile - Add an output file onto the list of tracked output files.
459  ///
460  /// \param OutFile - The output file info.
461  void addOutputFile(const OutputFile &OutFile);
462
463  /// clearOutputFiles - Clear the output file list, destroying the contained
464  /// output streams.
465  ///
466  /// \param EraseFiles - If true, attempt to erase the files from disk.
467  void clearOutputFiles(bool EraseFiles);
468
469  /// }
470  /// @name Construction Utility Methods
471  /// {
472
473  /// Create the diagnostics engine using the invocation's diagnostic options
474  /// and replace any existing one with it.
475  ///
476  /// Note that this routine also replaces the diagnostic client.
477  void createDiagnostics(int Argc, char **Argv);
478
479  /// Create a Diagnostic object with a the TextDiagnosticPrinter.
480  ///
481  /// The \arg Argc and \arg Argv arguments are used only for logging purposes,
482  /// when the diagnostic options indicate that the compiler should output
483  /// logging information.
484  ///
485  /// Note that this creates an unowned DiagnosticClient, if using directly the
486  /// caller is responsible for releasing the returned Diagnostic's client
487  /// eventually.
488  ///
489  /// \param Opts - The diagnostic options; note that the created text
490  /// diagnostic object contains a reference to these options and its lifetime
491  /// must extend past that of the diagnostic engine.
492  ///
493  /// \return The new object on success, or null on failure.
494  static llvm::IntrusiveRefCntPtr<Diagnostic>
495  createDiagnostics(const DiagnosticOptions &Opts, int Argc, char **Argv);
496
497  /// Create the file manager and replace any existing one with it.
498  void createFileManager();
499
500  /// Create the source manager and replace any existing one with it.
501  void createSourceManager();
502
503  /// Create the preprocessor, using the invocation, file, and source managers,
504  /// and replace any existing one with it.
505  void createPreprocessor();
506
507  /// Create a Preprocessor object.
508  ///
509  /// Note that this also creates a new HeaderSearch object which will be owned
510  /// by the resulting Preprocessor.
511  ///
512  /// \return The new object on success, or null on failure.
513  static Preprocessor *createPreprocessor(Diagnostic &, const LangOptions &,
514                                          const PreprocessorOptions &,
515                                          const HeaderSearchOptions &,
516                                          const DependencyOutputOptions &,
517                                          const TargetInfo &,
518                                          const FrontendOptions &,
519                                          SourceManager &, FileManager &);
520
521  /// Create the AST context.
522  void createASTContext();
523
524  /// Create an external AST source to read a PCH file and attach it to the AST
525  /// context.
526  void createPCHExternalASTSource(llvm::StringRef Path,
527                                  bool DisablePCHValidation,
528                                  void *DeserializationListener);
529
530  /// Create an external AST source to read a PCH file.
531  ///
532  /// \return - The new object on success, or null on failure.
533  static ExternalASTSource *
534  createPCHExternalASTSource(llvm::StringRef Path, const std::string &Sysroot,
535                             bool DisablePCHValidation,
536                             Preprocessor &PP, ASTContext &Context,
537                             void *DeserializationListener, bool Preamble);
538
539  /// Create a code completion consumer using the invocation; note that this
540  /// will cause the source manager to truncate the input source file at the
541  /// completion point.
542  void createCodeCompletionConsumer();
543
544  /// Create a code completion consumer to print code completion results, at
545  /// \arg Filename, \arg Line, and \arg Column, to the given output stream \arg
546  /// OS.
547  static CodeCompleteConsumer *
548  createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
549                               unsigned Line, unsigned Column,
550                               bool UseDebugPrinter, bool ShowMacros,
551                               bool ShowCodePatterns, bool ShowGlobals,
552                               llvm::raw_ostream &OS);
553
554  /// \brief Create the Sema object to be used for parsing.
555  void createSema(bool CompleteTranslationUnit,
556                  CodeCompleteConsumer *CompletionConsumer);
557
558  /// Create the frontend timer and replace any existing one with it.
559  void createFrontendTimer();
560
561  /// Create the default output file (from the invocation's options) and add it
562  /// to the list of tracked output files.
563  ///
564  /// \return - Null on error.
565  llvm::raw_fd_ostream *
566  createDefaultOutputFile(bool Binary = true, llvm::StringRef BaseInput = "",
567                          llvm::StringRef Extension = "");
568
569  /// Create a new output file and add it to the list of tracked output files,
570  /// optionally deriving the output path name.
571  ///
572  /// \return - Null on error.
573  llvm::raw_fd_ostream *
574  createOutputFile(llvm::StringRef OutputPath, bool Binary = true,
575                   llvm::StringRef BaseInput = "",
576                   llvm::StringRef Extension = "");
577
578  /// Create a new output file, optionally deriving the output path name.
579  ///
580  /// If \arg OutputPath is empty, then createOutputFile will derive an output
581  /// path location as \arg BaseInput, with any suffix removed, and \arg
582  /// Extension appended. If OutputPath is not stdout createOutputFile will
583  /// create a new temporary file that must be renamed to OutputPath in the end.
584  ///
585  /// \param OutputPath - If given, the path to the output file.
586  /// \param Error [out] - On failure, the error message.
587  /// \param BaseInput - If \arg OutputPath is empty, the input path name to use
588  /// for deriving the output path.
589  /// \param Extension - The extension to use for derived output names.
590  /// \param Binary - The mode to open the file in.
591  /// \param ResultPathName [out] - If given, the result path name will be
592  /// stored here on success.
593  /// \param TempPathName [out] - If given, the temporary file path name
594  /// will be stored here on success.
595  static llvm::raw_fd_ostream *
596  createOutputFile(llvm::StringRef OutputPath, std::string &Error,
597                   bool Binary = true, llvm::StringRef BaseInput = "",
598                   llvm::StringRef Extension = "",
599                   std::string *ResultPathName = 0,
600                   std::string *TempPathName = 0);
601
602  /// }
603  /// @name Initialization Utility Methods
604  /// {
605
606  /// InitializeSourceManager - Initialize the source manager to set InputFile
607  /// as the main file.
608  ///
609  /// \return True on success.
610  bool InitializeSourceManager(llvm::StringRef InputFile);
611
612  /// InitializeSourceManager - Initialize the source manager to set InputFile
613  /// as the main file.
614  ///
615  /// \return True on success.
616  static bool InitializeSourceManager(llvm::StringRef InputFile,
617                                      Diagnostic &Diags,
618                                      FileManager &FileMgr,
619                                      SourceManager &SourceMgr,
620                                      const FrontendOptions &Opts);
621
622  /// }
623};
624
625} // end namespace clang
626
627#endif
628