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