1 //===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_ 10 #define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_ 11 12 #include "clang/AST/ASTConsumer.h" 13 #include "clang/Basic/Diagnostic.h" 14 #include "clang/Basic/SourceManager.h" 15 #include "clang/Basic/TargetInfo.h" 16 #include "clang/Frontend/CompilerInvocation.h" 17 #include "clang/Frontend/PCHContainerOperations.h" 18 #include "clang/Frontend/Utils.h" 19 #include "clang/Lex/HeaderSearchOptions.h" 20 #include "clang/Lex/ModuleLoader.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/IntrusiveRefCntPtr.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/Support/BuryPointer.h" 26 #include "llvm/Support/FileSystem.h" 27 #include <cassert> 28 #include <list> 29 #include <memory> 30 #include <optional> 31 #include <string> 32 #include <utility> 33 34 namespace llvm { 35 class raw_fd_ostream; 36 class Timer; 37 class TimerGroup; 38 } 39 40 namespace clang { 41 class ASTContext; 42 class ASTReader; 43 class CodeCompleteConsumer; 44 class DiagnosticsEngine; 45 class DiagnosticConsumer; 46 class FileManager; 47 class FrontendAction; 48 class InMemoryModuleCache; 49 class Module; 50 class Preprocessor; 51 class Sema; 52 class SourceManager; 53 class TargetInfo; 54 enum class DisableValidationForModuleKind; 55 56 /// CompilerInstance - Helper class for managing a single instance of the Clang 57 /// compiler. 58 /// 59 /// The CompilerInstance serves two purposes: 60 /// (1) It manages the various objects which are necessary to run the compiler, 61 /// for example the preprocessor, the target information, and the AST 62 /// context. 63 /// (2) It provides utility routines for constructing and manipulating the 64 /// common Clang objects. 65 /// 66 /// The compiler instance generally owns the instance of all the objects that it 67 /// manages. However, clients can still share objects by manually setting the 68 /// object and retaking ownership prior to destroying the CompilerInstance. 69 /// 70 /// The compiler instance is intended to simplify clients, but not to lock them 71 /// in to the compiler instance for everything. When possible, utility functions 72 /// come in two forms; a short form that reuses the CompilerInstance objects, 73 /// and a long form that takes explicit instances of any required objects. 74 class CompilerInstance : public ModuleLoader { 75 /// The options used in this compiler instance. 76 std::shared_ptr<CompilerInvocation> Invocation; 77 78 /// The diagnostics engine instance. 79 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics; 80 81 /// The target being compiled for. 82 IntrusiveRefCntPtr<TargetInfo> Target; 83 84 /// Auxiliary Target info. 85 IntrusiveRefCntPtr<TargetInfo> AuxTarget; 86 87 /// The file manager. 88 IntrusiveRefCntPtr<FileManager> FileMgr; 89 90 /// The source manager. 91 IntrusiveRefCntPtr<SourceManager> SourceMgr; 92 93 /// The cache of PCM files. 94 IntrusiveRefCntPtr<InMemoryModuleCache> ModuleCache; 95 96 /// The preprocessor. 97 std::shared_ptr<Preprocessor> PP; 98 99 /// The AST context. 100 IntrusiveRefCntPtr<ASTContext> Context; 101 102 /// An optional sema source that will be attached to sema. 103 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSemaSrc; 104 105 /// The AST consumer. 106 std::unique_ptr<ASTConsumer> Consumer; 107 108 /// The code completion consumer. 109 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer; 110 111 /// The semantic analysis object. 112 std::unique_ptr<Sema> TheSema; 113 114 /// The frontend timer group. 115 std::unique_ptr<llvm::TimerGroup> FrontendTimerGroup; 116 117 /// The frontend timer. 118 std::unique_ptr<llvm::Timer> FrontendTimer; 119 120 /// The ASTReader, if one exists. 121 IntrusiveRefCntPtr<ASTReader> TheASTReader; 122 123 /// The module dependency collector for crashdumps 124 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector; 125 126 /// The module provider. 127 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations; 128 129 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors; 130 131 /// The set of top-level modules that has already been built on the 132 /// fly as part of this overall compilation action. 133 std::map<std::string, std::string, std::less<>> BuiltModules; 134 135 /// Should we delete the BuiltModules when we're done? 136 bool DeleteBuiltModules = true; 137 138 /// The location of the module-import keyword for the last module 139 /// import. 140 SourceLocation LastModuleImportLoc; 141 142 /// The result of the last module import. 143 /// 144 ModuleLoadResult LastModuleImportResult; 145 146 /// Whether we should (re)build the global module index once we 147 /// have finished with this translation unit. 148 bool BuildGlobalModuleIndex = false; 149 150 /// We have a full global module index, with all modules. 151 bool HaveFullGlobalModuleIndex = false; 152 153 /// One or more modules failed to build. 154 bool DisableGeneratingGlobalModuleIndex = false; 155 156 /// The stream for verbose output if owned, otherwise nullptr. 157 std::unique_ptr<raw_ostream> OwnedVerboseOutputStream; 158 159 /// The stream for verbose output. 160 raw_ostream *VerboseOutputStream = &llvm::errs(); 161 162 /// Holds information about the output file. 163 /// 164 /// If TempFilename is not empty we must rename it to Filename at the end. 165 /// TempFilename may be empty and Filename non-empty if creating the temporary 166 /// failed. 167 struct OutputFile { 168 std::string Filename; 169 std::optional<llvm::sys::fs::TempFile> File; 170 171 OutputFile(std::string filename, 172 std::optional<llvm::sys::fs::TempFile> file) 173 : Filename(std::move(filename)), File(std::move(file)) {} 174 }; 175 176 /// The list of active output files. 177 std::list<OutputFile> OutputFiles; 178 179 /// Force an output buffer. 180 std::unique_ptr<llvm::raw_pwrite_stream> OutputStream; 181 182 CompilerInstance(const CompilerInstance &) = delete; 183 void operator=(const CompilerInstance &) = delete; 184 public: 185 explicit CompilerInstance( 186 std::shared_ptr<PCHContainerOperations> PCHContainerOps = 187 std::make_shared<PCHContainerOperations>(), 188 InMemoryModuleCache *SharedModuleCache = nullptr); 189 ~CompilerInstance() override; 190 191 /// @name High-Level Operations 192 /// { 193 194 /// ExecuteAction - Execute the provided action against the compiler's 195 /// CompilerInvocation object. 196 /// 197 /// This function makes the following assumptions: 198 /// 199 /// - The invocation options should be initialized. This function does not 200 /// handle the '-help' or '-version' options, clients should handle those 201 /// directly. 202 /// 203 /// - The diagnostics engine should have already been created by the client. 204 /// 205 /// - No other CompilerInstance state should have been initialized (this is 206 /// an unchecked error). 207 /// 208 /// - Clients should have initialized any LLVM target features that may be 209 /// required. 210 /// 211 /// - Clients should eventually call llvm_shutdown() upon the completion of 212 /// this routine to ensure that any managed objects are properly destroyed. 213 /// 214 /// Note that this routine may write output to 'stderr'. 215 /// 216 /// \param Act - The action to execute. 217 /// \return - True on success. 218 // 219 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part 220 // of the context or else not CompilerInstance specific. 221 bool ExecuteAction(FrontendAction &Act); 222 223 /// Load the list of plugins requested in the \c FrontendOptions. 224 void LoadRequestedPlugins(); 225 226 /// } 227 /// @name Compiler Invocation and Options 228 /// { 229 230 bool hasInvocation() const { return Invocation != nullptr; } 231 232 CompilerInvocation &getInvocation() { 233 assert(Invocation && "Compiler instance has no invocation!"); 234 return *Invocation; 235 } 236 237 std::shared_ptr<CompilerInvocation> getInvocationPtr() { return Invocation; } 238 239 /// setInvocation - Replace the current invocation. 240 void setInvocation(std::shared_ptr<CompilerInvocation> Value); 241 242 /// Indicates whether we should (re)build the global module index. 243 bool shouldBuildGlobalModuleIndex() const; 244 245 /// Set the flag indicating whether we should (re)build the global 246 /// module index. 247 void setBuildGlobalModuleIndex(bool Build) { 248 BuildGlobalModuleIndex = Build; 249 } 250 251 /// } 252 /// @name Forwarding Methods 253 /// { 254 255 AnalyzerOptionsRef getAnalyzerOpts() { 256 return Invocation->getAnalyzerOpts(); 257 } 258 259 CodeGenOptions &getCodeGenOpts() { 260 return Invocation->getCodeGenOpts(); 261 } 262 const CodeGenOptions &getCodeGenOpts() const { 263 return Invocation->getCodeGenOpts(); 264 } 265 266 DependencyOutputOptions &getDependencyOutputOpts() { 267 return Invocation->getDependencyOutputOpts(); 268 } 269 const DependencyOutputOptions &getDependencyOutputOpts() const { 270 return Invocation->getDependencyOutputOpts(); 271 } 272 273 DiagnosticOptions &getDiagnosticOpts() { 274 return Invocation->getDiagnosticOpts(); 275 } 276 const DiagnosticOptions &getDiagnosticOpts() const { 277 return Invocation->getDiagnosticOpts(); 278 } 279 280 FileSystemOptions &getFileSystemOpts() { 281 return Invocation->getFileSystemOpts(); 282 } 283 const FileSystemOptions &getFileSystemOpts() const { 284 return Invocation->getFileSystemOpts(); 285 } 286 287 FrontendOptions &getFrontendOpts() { 288 return Invocation->getFrontendOpts(); 289 } 290 const FrontendOptions &getFrontendOpts() const { 291 return Invocation->getFrontendOpts(); 292 } 293 294 HeaderSearchOptions &getHeaderSearchOpts() { 295 return Invocation->getHeaderSearchOpts(); 296 } 297 const HeaderSearchOptions &getHeaderSearchOpts() const { 298 return Invocation->getHeaderSearchOpts(); 299 } 300 std::shared_ptr<HeaderSearchOptions> getHeaderSearchOptsPtr() const { 301 return Invocation->getHeaderSearchOptsPtr(); 302 } 303 304 LangOptions &getLangOpts() { 305 return *Invocation->getLangOpts(); 306 } 307 const LangOptions &getLangOpts() const { 308 return *Invocation->getLangOpts(); 309 } 310 311 PreprocessorOptions &getPreprocessorOpts() { 312 return Invocation->getPreprocessorOpts(); 313 } 314 const PreprocessorOptions &getPreprocessorOpts() const { 315 return Invocation->getPreprocessorOpts(); 316 } 317 318 PreprocessorOutputOptions &getPreprocessorOutputOpts() { 319 return Invocation->getPreprocessorOutputOpts(); 320 } 321 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const { 322 return Invocation->getPreprocessorOutputOpts(); 323 } 324 325 TargetOptions &getTargetOpts() { 326 return Invocation->getTargetOpts(); 327 } 328 const TargetOptions &getTargetOpts() const { 329 return Invocation->getTargetOpts(); 330 } 331 332 /// } 333 /// @name Diagnostics Engine 334 /// { 335 336 bool hasDiagnostics() const { return Diagnostics != nullptr; } 337 338 /// Get the current diagnostics engine. 339 DiagnosticsEngine &getDiagnostics() const { 340 assert(Diagnostics && "Compiler instance has no diagnostics!"); 341 return *Diagnostics; 342 } 343 344 IntrusiveRefCntPtr<DiagnosticsEngine> getDiagnosticsPtr() const { 345 assert(Diagnostics && "Compiler instance has no diagnostics!"); 346 return Diagnostics; 347 } 348 349 /// setDiagnostics - Replace the current diagnostics engine. 350 void setDiagnostics(DiagnosticsEngine *Value); 351 352 DiagnosticConsumer &getDiagnosticClient() const { 353 assert(Diagnostics && Diagnostics->getClient() && 354 "Compiler instance has no diagnostic client!"); 355 return *Diagnostics->getClient(); 356 } 357 358 /// } 359 /// @name VerboseOutputStream 360 /// } 361 362 /// Replace the current stream for verbose output. 363 void setVerboseOutputStream(raw_ostream &Value); 364 365 /// Replace the current stream for verbose output. 366 void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value); 367 368 /// Get the current stream for verbose output. 369 raw_ostream &getVerboseOutputStream() { 370 return *VerboseOutputStream; 371 } 372 373 /// } 374 /// @name Target Info 375 /// { 376 377 bool hasTarget() const { return Target != nullptr; } 378 379 TargetInfo &getTarget() const { 380 assert(Target && "Compiler instance has no target!"); 381 return *Target; 382 } 383 384 IntrusiveRefCntPtr<TargetInfo> getTargetPtr() const { 385 assert(Target && "Compiler instance has no target!"); 386 return Target; 387 } 388 389 /// Replace the current Target. 390 void setTarget(TargetInfo *Value); 391 392 /// } 393 /// @name AuxTarget Info 394 /// { 395 396 TargetInfo *getAuxTarget() const { return AuxTarget.get(); } 397 398 /// Replace the current AuxTarget. 399 void setAuxTarget(TargetInfo *Value); 400 401 // Create Target and AuxTarget based on current options 402 bool createTarget(); 403 404 /// } 405 /// @name Virtual File System 406 /// { 407 408 llvm::vfs::FileSystem &getVirtualFileSystem() const; 409 410 /// } 411 /// @name File Manager 412 /// { 413 414 bool hasFileManager() const { return FileMgr != nullptr; } 415 416 /// Return the current file manager to the caller. 417 FileManager &getFileManager() const { 418 assert(FileMgr && "Compiler instance has no file manager!"); 419 return *FileMgr; 420 } 421 422 IntrusiveRefCntPtr<FileManager> getFileManagerPtr() const { 423 assert(FileMgr && "Compiler instance has no file manager!"); 424 return FileMgr; 425 } 426 427 void resetAndLeakFileManager() { 428 llvm::BuryPointer(FileMgr.get()); 429 FileMgr.resetWithoutRelease(); 430 } 431 432 /// Replace the current file manager and virtual file system. 433 void setFileManager(FileManager *Value); 434 435 /// } 436 /// @name Source Manager 437 /// { 438 439 bool hasSourceManager() const { return SourceMgr != nullptr; } 440 441 /// Return the current source manager. 442 SourceManager &getSourceManager() const { 443 assert(SourceMgr && "Compiler instance has no source manager!"); 444 return *SourceMgr; 445 } 446 447 IntrusiveRefCntPtr<SourceManager> getSourceManagerPtr() const { 448 assert(SourceMgr && "Compiler instance has no source manager!"); 449 return SourceMgr; 450 } 451 452 void resetAndLeakSourceManager() { 453 llvm::BuryPointer(SourceMgr.get()); 454 SourceMgr.resetWithoutRelease(); 455 } 456 457 /// setSourceManager - Replace the current source manager. 458 void setSourceManager(SourceManager *Value); 459 460 /// } 461 /// @name Preprocessor 462 /// { 463 464 bool hasPreprocessor() const { return PP != nullptr; } 465 466 /// Return the current preprocessor. 467 Preprocessor &getPreprocessor() const { 468 assert(PP && "Compiler instance has no preprocessor!"); 469 return *PP; 470 } 471 472 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; } 473 474 void resetAndLeakPreprocessor() { 475 llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP)); 476 } 477 478 /// Replace the current preprocessor. 479 void setPreprocessor(std::shared_ptr<Preprocessor> Value); 480 481 /// } 482 /// @name ASTContext 483 /// { 484 485 bool hasASTContext() const { return Context != nullptr; } 486 487 ASTContext &getASTContext() const { 488 assert(Context && "Compiler instance has no AST context!"); 489 return *Context; 490 } 491 492 IntrusiveRefCntPtr<ASTContext> getASTContextPtr() const { 493 assert(Context && "Compiler instance has no AST context!"); 494 return Context; 495 } 496 497 void resetAndLeakASTContext() { 498 llvm::BuryPointer(Context.get()); 499 Context.resetWithoutRelease(); 500 } 501 502 /// setASTContext - Replace the current AST context. 503 void setASTContext(ASTContext *Value); 504 505 /// Replace the current Sema; the compiler instance takes ownership 506 /// of S. 507 void setSema(Sema *S); 508 509 /// } 510 /// @name ASTConsumer 511 /// { 512 513 bool hasASTConsumer() const { return (bool)Consumer; } 514 515 ASTConsumer &getASTConsumer() const { 516 assert(Consumer && "Compiler instance has no AST consumer!"); 517 return *Consumer; 518 } 519 520 /// takeASTConsumer - Remove the current AST consumer and give ownership to 521 /// the caller. 522 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); } 523 524 /// setASTConsumer - Replace the current AST consumer; the compiler instance 525 /// takes ownership of \p Value. 526 void setASTConsumer(std::unique_ptr<ASTConsumer> Value); 527 528 /// } 529 /// @name Semantic analysis 530 /// { 531 bool hasSema() const { return (bool)TheSema; } 532 533 Sema &getSema() const { 534 assert(TheSema && "Compiler instance has no Sema object!"); 535 return *TheSema; 536 } 537 538 std::unique_ptr<Sema> takeSema(); 539 void resetAndLeakSema(); 540 541 /// } 542 /// @name Module Management 543 /// { 544 545 IntrusiveRefCntPtr<ASTReader> getASTReader() const; 546 void setASTReader(IntrusiveRefCntPtr<ASTReader> Reader); 547 548 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const; 549 void setModuleDepCollector( 550 std::shared_ptr<ModuleDependencyCollector> Collector); 551 552 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const { 553 return ThePCHContainerOperations; 554 } 555 556 /// Return the appropriate PCHContainerWriter depending on the 557 /// current CodeGenOptions. 558 const PCHContainerWriter &getPCHContainerWriter() const { 559 assert(Invocation && "cannot determine module format without invocation"); 560 StringRef Format = getHeaderSearchOpts().ModuleFormat; 561 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format); 562 if (!Writer) { 563 if (Diagnostics) 564 Diagnostics->Report(diag::err_module_format_unhandled) << Format; 565 llvm::report_fatal_error("unknown module format"); 566 } 567 return *Writer; 568 } 569 570 /// Return the appropriate PCHContainerReader depending on the 571 /// current CodeGenOptions. 572 const PCHContainerReader &getPCHContainerReader() const { 573 assert(Invocation && "cannot determine module format without invocation"); 574 StringRef Format = getHeaderSearchOpts().ModuleFormat; 575 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format); 576 if (!Reader) { 577 if (Diagnostics) 578 Diagnostics->Report(diag::err_module_format_unhandled) << Format; 579 llvm::report_fatal_error("unknown module format"); 580 } 581 return *Reader; 582 } 583 584 /// } 585 /// @name Code Completion 586 /// { 587 588 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; } 589 590 CodeCompleteConsumer &getCodeCompletionConsumer() const { 591 assert(CompletionConsumer && 592 "Compiler instance has no code completion consumer!"); 593 return *CompletionConsumer; 594 } 595 596 /// setCodeCompletionConsumer - Replace the current code completion consumer; 597 /// the compiler instance takes ownership of \p Value. 598 void setCodeCompletionConsumer(CodeCompleteConsumer *Value); 599 600 /// } 601 /// @name Frontend timer 602 /// { 603 604 bool hasFrontendTimer() const { return (bool)FrontendTimer; } 605 606 llvm::Timer &getFrontendTimer() const { 607 assert(FrontendTimer && "Compiler instance has no frontend timer!"); 608 return *FrontendTimer; 609 } 610 611 /// } 612 /// @name Output Files 613 /// { 614 615 /// clearOutputFiles - Clear the output file list. The underlying output 616 /// streams must have been closed beforehand. 617 /// 618 /// \param EraseFiles - If true, attempt to erase the files from disk. 619 void clearOutputFiles(bool EraseFiles); 620 621 /// } 622 /// @name Construction Utility Methods 623 /// { 624 625 /// Create the diagnostics engine using the invocation's diagnostic options 626 /// and replace any existing one with it. 627 /// 628 /// Note that this routine also replaces the diagnostic client, 629 /// allocating one if one is not provided. 630 /// 631 /// \param Client If non-NULL, a diagnostic client that will be 632 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST 633 /// unit. 634 /// 635 /// \param ShouldOwnClient If Client is non-NULL, specifies whether 636 /// the diagnostic object should take ownership of the client. 637 void createDiagnostics(DiagnosticConsumer *Client = nullptr, 638 bool ShouldOwnClient = true); 639 640 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter. 641 /// 642 /// If no diagnostic client is provided, this creates a 643 /// DiagnosticConsumer that is owned by the returned diagnostic 644 /// object, if using directly the caller is responsible for 645 /// releasing the returned DiagnosticsEngine's client eventually. 646 /// 647 /// \param Opts - The diagnostic options; note that the created text 648 /// diagnostic object contains a reference to these options. 649 /// 650 /// \param Client If non-NULL, a diagnostic client that will be 651 /// attached to (and, then, owned by) the returned DiagnosticsEngine 652 /// object. 653 /// 654 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be 655 /// used by some diagnostics printers (for logging purposes only). 656 /// 657 /// \return The new object on success, or null on failure. 658 static IntrusiveRefCntPtr<DiagnosticsEngine> 659 createDiagnostics(DiagnosticOptions *Opts, 660 DiagnosticConsumer *Client = nullptr, 661 bool ShouldOwnClient = true, 662 const CodeGenOptions *CodeGenOpts = nullptr); 663 664 /// Create the file manager and replace any existing one with it. 665 /// 666 /// \return The new file manager on success, or null on failure. 667 FileManager * 668 createFileManager(IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr); 669 670 /// Create the source manager and replace any existing one with it. 671 void createSourceManager(FileManager &FileMgr); 672 673 /// Create the preprocessor, using the invocation, file, and source managers, 674 /// and replace any existing one with it. 675 void createPreprocessor(TranslationUnitKind TUKind); 676 677 std::string getSpecificModuleCachePath(StringRef ModuleHash); 678 std::string getSpecificModuleCachePath() { 679 return getSpecificModuleCachePath(getInvocation().getModuleHash()); 680 } 681 682 /// Create the AST context. 683 void createASTContext(); 684 685 /// Create an external AST source to read a PCH file and attach it to the AST 686 /// context. 687 void createPCHExternalASTSource( 688 StringRef Path, DisableValidationForModuleKind DisableValidation, 689 bool AllowPCHWithCompilerErrors, void *DeserializationListener, 690 bool OwnDeserializationListener); 691 692 /// Create an external AST source to read a PCH file. 693 /// 694 /// \return - The new object on success, or null on failure. 695 static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource( 696 StringRef Path, StringRef Sysroot, 697 DisableValidationForModuleKind DisableValidation, 698 bool AllowPCHWithCompilerErrors, Preprocessor &PP, 699 InMemoryModuleCache &ModuleCache, ASTContext &Context, 700 const PCHContainerReader &PCHContainerRdr, 701 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 702 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors, 703 void *DeserializationListener, bool OwnDeserializationListener, 704 bool Preamble, bool UseGlobalModuleIndex); 705 706 /// Create a code completion consumer using the invocation; note that this 707 /// will cause the source manager to truncate the input source file at the 708 /// completion point. 709 void createCodeCompletionConsumer(); 710 711 /// Create a code completion consumer to print code completion results, at 712 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS. 713 static CodeCompleteConsumer *createCodeCompletionConsumer( 714 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column, 715 const CodeCompleteOptions &Opts, raw_ostream &OS); 716 717 /// Create the Sema object to be used for parsing. 718 void createSema(TranslationUnitKind TUKind, 719 CodeCompleteConsumer *CompletionConsumer); 720 721 /// Create the frontend timer and replace any existing one with it. 722 void createFrontendTimer(); 723 724 /// Create the default output file (from the invocation's options) and add it 725 /// to the list of tracked output files. 726 /// 727 /// The files created by this are usually removed on signal, and, depending 728 /// on FrontendOptions, may also use a temporary file (that is, the data is 729 /// written to a temporary file which will atomically replace the target 730 /// output on success). 731 /// 732 /// \return - Null on error. 733 std::unique_ptr<raw_pwrite_stream> createDefaultOutputFile( 734 bool Binary = true, StringRef BaseInput = "", StringRef Extension = "", 735 bool RemoveFileOnSignal = true, bool CreateMissingDirectories = false, 736 bool ForceUseTemporary = false); 737 738 /// Create a new output file, optionally deriving the output path name, and 739 /// add it to the list of tracked output files. 740 /// 741 /// \return - Null on error. 742 std::unique_ptr<raw_pwrite_stream> 743 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, 744 bool UseTemporary, bool CreateMissingDirectories = false); 745 746 private: 747 /// Create a new output file and add it to the list of tracked output files. 748 /// 749 /// If \p OutputPath is empty, then createOutputFile will derive an output 750 /// path location as \p BaseInput, with any suffix removed, and \p Extension 751 /// appended. If \p OutputPath is not stdout and \p UseTemporary 752 /// is true, createOutputFile will create a new temporary file that must be 753 /// renamed to \p OutputPath in the end. 754 /// 755 /// \param OutputPath - If given, the path to the output file. 756 /// \param Binary - The mode to open the file in. 757 /// \param RemoveFileOnSignal - Whether the file should be registered with 758 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for 759 /// multithreaded use, as the underlying signal mechanism is not reentrant 760 /// \param UseTemporary - Create a new temporary file that must be renamed to 761 /// OutputPath in the end. 762 /// \param CreateMissingDirectories - When \p UseTemporary is true, create 763 /// missing directories in the output path. 764 Expected<std::unique_ptr<raw_pwrite_stream>> 765 createOutputFileImpl(StringRef OutputPath, bool Binary, 766 bool RemoveFileOnSignal, bool UseTemporary, 767 bool CreateMissingDirectories); 768 769 public: 770 std::unique_ptr<raw_pwrite_stream> createNullOutputFile(); 771 772 /// } 773 /// @name Initialization Utility Methods 774 /// { 775 776 /// InitializeSourceManager - Initialize the source manager to set InputFile 777 /// as the main file. 778 /// 779 /// \return True on success. 780 bool InitializeSourceManager(const FrontendInputFile &Input); 781 782 /// InitializeSourceManager - Initialize the source manager to set InputFile 783 /// as the main file. 784 /// 785 /// \return True on success. 786 static bool InitializeSourceManager(const FrontendInputFile &Input, 787 DiagnosticsEngine &Diags, 788 FileManager &FileMgr, 789 SourceManager &SourceMgr); 790 791 /// } 792 793 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) { 794 OutputStream = std::move(OutStream); 795 } 796 797 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() { 798 return std::move(OutputStream); 799 } 800 801 void createASTReader(); 802 803 bool loadModuleFile(StringRef FileName); 804 805 private: 806 /// Find a module, potentially compiling it, before reading its AST. This is 807 /// the guts of loadModule. 808 /// 809 /// For prebuilt modules, the Module is not expected to exist in 810 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the 811 /// ModuleManager, then it will be loaded and looked up. 812 /// 813 /// For implicit modules, the Module is expected to already be in the 814 /// ModuleMap. First attempt to load it from the given path on disk. If that 815 /// fails, defer to compileModuleAndReadAST, which will first build and then 816 /// load it. 817 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName, 818 SourceLocation ImportLoc, 819 SourceLocation ModuleNameLoc, 820 bool IsInclusionDirective); 821 822 public: 823 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, 824 Module::NameVisibilityKind Visibility, 825 bool IsInclusionDirective) override; 826 827 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, 828 StringRef Source) override; 829 830 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, 831 SourceLocation ImportLoc) override; 832 833 bool hadModuleLoaderFatalFailure() const { 834 return ModuleLoader::HadFatalFailure; 835 } 836 837 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override; 838 839 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override; 840 841 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) { 842 DependencyCollectors.push_back(std::move(Listener)); 843 } 844 845 void setExternalSemaSource(IntrusiveRefCntPtr<ExternalSemaSource> ESS); 846 847 InMemoryModuleCache &getModuleCache() const { return *ModuleCache; } 848 }; 849 850 } // end namespace clang 851 852 #endif 853