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