CompilerInstance.h revision 251662
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 27namespace llvm { 28class raw_fd_ostream; 29class Timer; 30} 31 32namespace clang { 33class ASTContext; 34class ASTConsumer; 35class ASTReader; 36class CodeCompleteConsumer; 37class DiagnosticsEngine; 38class DiagnosticConsumer; 39class ExternalASTSource; 40class FileEntry; 41class FileManager; 42class FrontendAction; 43class Module; 44class Preprocessor; 45class Sema; 46class SourceManager; 47class 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. 67class 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; 143public: 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 != 0; } 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 != 0; } 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 { return CompletionConsumer != 0; } 437 438 CodeCompleteConsumer &getCodeCompletionConsumer() const { 439 assert(CompletionConsumer && 440 "Compiler instance has no code completion consumer!"); 441 return *CompletionConsumer; 442 } 443 444 /// takeCodeCompletionConsumer - Remove the current code completion consumer 445 /// and give ownership to the caller. 446 CodeCompleteConsumer *takeCodeCompletionConsumer() { 447 return CompletionConsumer.take(); 448 } 449 450 /// setCodeCompletionConsumer - Replace the current code completion consumer; 451 /// the compiler instance takes ownership of \p Value. 452 void setCodeCompletionConsumer(CodeCompleteConsumer *Value); 453 454 /// } 455 /// @name Frontend timer 456 /// { 457 458 bool hasFrontendTimer() const { return FrontendTimer != 0; } 459 460 llvm::Timer &getFrontendTimer() const { 461 assert(FrontendTimer && "Compiler instance has no frontend timer!"); 462 return *FrontendTimer; 463 } 464 465 /// } 466 /// @name Output Files 467 /// { 468 469 /// addOutputFile - Add an output file onto the list of tracked output files. 470 /// 471 /// \param OutFile - The output file info. 472 void addOutputFile(const OutputFile &OutFile); 473 474 /// clearOutputFiles - Clear the output file list, destroying the contained 475 /// output streams. 476 /// 477 /// \param EraseFiles - If true, attempt to erase the files from disk. 478 void clearOutputFiles(bool EraseFiles); 479 480 /// } 481 /// @name Construction Utility Methods 482 /// { 483 484 /// Create the diagnostics engine using the invocation's diagnostic options 485 /// and replace any existing one with it. 486 /// 487 /// Note that this routine also replaces the diagnostic client, 488 /// allocating one if one is not provided. 489 /// 490 /// \param Client If non-NULL, a diagnostic client that will be 491 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST 492 /// unit. 493 /// 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); 498 499 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter. 500 /// 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. 505 /// 506 /// \param Opts - The diagnostic options; note that the created text 507 /// diagnostic object contains a reference to these options. 508 /// 509 /// \param Client If non-NULL, a diagnostic client that will be 510 /// attached to (and, then, owned by) the returned DiagnosticsEngine 511 /// object. 512 /// 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). 515 /// 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); 522 523 /// Create the file manager and replace any existing one with it. 524 void createFileManager(); 525 526 /// Create the source manager and replace any existing one with it. 527 void createSourceManager(FileManager &FileMgr); 528 529 /// Create the preprocessor, using the invocation, file, and source managers, 530 /// and replace any existing one with it. 531 void createPreprocessor(); 532 533 /// Create the AST context. 534 void createASTContext(); 535 536 /// Create an external AST source to read a PCH file and attach it to the AST 537 /// context. 538 void createPCHExternalASTSource(StringRef Path, 539 bool DisablePCHValidation, 540 bool AllowPCHWithCompilerErrors, 541 void *DeserializationListener); 542 543 /// Create an external AST source to read a PCH file. 544 /// 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); 553 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(); 558 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, 565 raw_ostream &OS); 566 567 /// \brief Create the Sema object to be used for parsing. 568 void createSema(TranslationUnitKind TUKind, 569 CodeCompleteConsumer *CompletionConsumer); 570 571 /// Create the frontend timer and replace any existing one with it. 572 void createFrontendTimer(); 573 574 /// Create the default output file (from the invocation's options) and add it 575 /// to the list of tracked output files. 576 /// 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). 580 /// 581 /// \return - Null on error. 582 llvm::raw_fd_ostream * 583 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "", 584 StringRef Extension = ""); 585 586 /// Create a new output file and add it to the list of tracked output files, 587 /// optionally deriving the output path name. 588 /// 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); 597 598 /// Create a new output file, optionally deriving the output path name. 599 /// 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. 605 /// 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); 632 633 /// } 634 /// @name Initialization Utility Methods 635 /// { 636 637 /// InitializeSourceManager - Initialize the source manager to set InputFile 638 /// as the main file. 639 /// 640 /// \return True on success. 641 bool InitializeSourceManager(const FrontendInputFile &Input); 642 643 /// InitializeSourceManager - Initialize the source manager to set InputFile 644 /// as the main file. 645 /// 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); 652 653 /// } 654 655 virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, 656 ModuleIdPath Path, 657 Module::NameVisibilityKind Visibility, 658 bool IsInclusionDirective); 659 660 virtual void makeModuleVisible(Module *Mod, 661 Module::NameVisibilityKind Visibility, 662 SourceLocation ImportLoc, 663 bool Complain); 664 665}; 666 667} // end namespace clang 668 669#endif 670