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