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