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