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