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 31namespace llvm { 32class raw_fd_ostream; 33class Timer; 34class TimerGroup; 35} 36 37namespace clang { 38class ASTContext; 39class ASTReader; 40class CodeCompleteConsumer; 41class DiagnosticsEngine; 42class DiagnosticConsumer; 43class ExternalASTSource; 44class FileEntry; 45class FileManager; 46class FrontendAction; 47class InMemoryModuleCache; 48class Module; 49class Preprocessor; 50class Sema; 51class SourceManager; 52class 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. 72class 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> 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 169 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; 187public: 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 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 /// 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. 245 void setBuildGlobalModuleIndex(bool Build) { 246 BuildGlobalModuleIndex = Build; 247 } 248 249 /// } 250 /// @name Forwarding Methods 251 /// { 252 253 AnalyzerOptionsRef getAnalyzerOpts() { 254 return Invocation->getAnalyzerOpts(); 255 } 256 257 CodeGenOptions &getCodeGenOpts() { 258 return Invocation->getCodeGenOpts(); 259 } 260 const CodeGenOptions &getCodeGenOpts() const { 261 return Invocation->getCodeGenOpts(); 262 } 263 264 DependencyOutputOptions &getDependencyOutputOpts() { 265 return Invocation->getDependencyOutputOpts(); 266 } 267 const DependencyOutputOptions &getDependencyOutputOpts() const { 268 return Invocation->getDependencyOutputOpts(); 269 } 270 271 DiagnosticOptions &getDiagnosticOpts() { 272 return Invocation->getDiagnosticOpts(); 273 } 274 const DiagnosticOptions &getDiagnosticOpts() const { 275 return Invocation->getDiagnosticOpts(); 276 } 277 278 FileSystemOptions &getFileSystemOpts() { 279 return Invocation->getFileSystemOpts(); 280 } 281 const FileSystemOptions &getFileSystemOpts() const { 282 return Invocation->getFileSystemOpts(); 283 } 284 285 FrontendOptions &getFrontendOpts() { 286 return Invocation->getFrontendOpts(); 287 } 288 const FrontendOptions &getFrontendOpts() const { 289 return Invocation->getFrontendOpts(); 290 } 291 292 HeaderSearchOptions &getHeaderSearchOpts() { 293 return Invocation->getHeaderSearchOpts(); 294 } 295 const HeaderSearchOptions &getHeaderSearchOpts() const { 296 return Invocation->getHeaderSearchOpts(); 297 } 298 std::shared_ptr<HeaderSearchOptions> getHeaderSearchOptsPtr() const { 299 return Invocation->getHeaderSearchOptsPtr(); 300 } 301 302 LangOptions &getLangOpts() { 303 return *Invocation->getLangOpts(); 304 } 305 const LangOptions &getLangOpts() const { 306 return *Invocation->getLangOpts(); 307 } 308 309 PreprocessorOptions &getPreprocessorOpts() { 310 return Invocation->getPreprocessorOpts(); 311 } 312 const PreprocessorOptions &getPreprocessorOpts() const { 313 return Invocation->getPreprocessorOpts(); 314 } 315 316 PreprocessorOutputOptions &getPreprocessorOutputOpts() { 317 return Invocation->getPreprocessorOutputOpts(); 318 } 319 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const { 320 return Invocation->getPreprocessorOutputOpts(); 321 } 322 323 TargetOptions &getTargetOpts() { 324 return Invocation->getTargetOpts(); 325 } 326 const TargetOptions &getTargetOpts() const { 327 return Invocation->getTargetOpts(); 328 } 329 330 /// } 331 /// @name Diagnostics Engine 332 /// { 333 334 bool hasDiagnostics() const { return Diagnostics != nullptr; } 335 336 /// Get the current diagnostics engine. 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 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. 362 raw_ostream &getVerboseOutputStream() { 363 return *VerboseOutputStream; 364 } 365 366 /// } 367 /// @name Target Info 368 /// { 369 370 bool hasTarget() const { return Target != nullptr; } 371 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 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 return getFileManager().getVirtualFileSystem(); 395 } 396 397 /// } 398 /// @name File Manager 399 /// { 400 401 bool hasFileManager() const { return FileMgr != nullptr; } 402 403 /// Return the current file manager to the caller. 404 FileManager &getFileManager() const { 405 assert(FileMgr && "Compiler instance has no file manager!"); 406 return *FileMgr; 407 } 408 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 421 bool hasSourceManager() const { return SourceMgr != nullptr; } 422 423 /// Return the current source manager. 424 SourceManager &getSourceManager() const { 425 assert(SourceMgr && "Compiler instance has no source manager!"); 426 return *SourceMgr; 427 } 428 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 441 bool hasPreprocessor() const { return PP != nullptr; } 442 443 /// Return the current preprocessor. 444 Preprocessor &getPreprocessor() const { 445 assert(PP && "Compiler instance has no preprocessor!"); 446 return *PP; 447 } 448 449 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; } 450 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 462 bool hasASTContext() const { return Context != nullptr; } 463 464 ASTContext &getASTContext() const { 465 assert(Context && "Compiler instance has no AST context!"); 466 return *Context; 467 } 468 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 485 bool hasASTConsumer() const { return (bool)Consumer; } 486 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. 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 /// { 503 bool hasSema() const { return (bool)TheSema; } 504 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 setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader); 519 520 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const; 521 void setModuleDepCollector( 522 std::shared_ptr<ModuleDependencyCollector> Collector); 523 524 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const { 525 return ThePCHContainerOperations; 526 } 527 528 /// Return the appropriate PCHContainerWriter depending on the 529 /// current CodeGenOptions. 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. 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 560 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; } 561 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 576 bool hasFrontendTimer() const { return (bool)FrontendTimer; } 577 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 /// addOutputFile - Add an output file onto the list of tracked output files. 588 /// 589 /// \param OutFile - The output file info. 590 void addOutputFile(OutputFile &&OutFile); 591 592 /// clearOutputFiles - Clear the output file list. The underlying output 593 /// streams must have been closed beforehand. 594 /// 595 /// \param EraseFiles - If true, attempt to erase the files from disk. 596 void clearOutputFiles(bool EraseFiles); 597 598 /// } 599 /// @name Construction Utility Methods 600 /// { 601 602 /// Create the diagnostics engine using the invocation's diagnostic options 603 /// and replace any existing one with it. 604 /// 605 /// Note that this routine also replaces the diagnostic client, 606 /// allocating one if one is not provided. 607 /// 608 /// \param Client If non-NULL, a diagnostic client that will be 609 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST 610 /// unit. 611 /// 612 /// \param ShouldOwnClient If Client is non-NULL, specifies whether 613 /// the diagnostic object should take ownership of the client. 614 void createDiagnostics(DiagnosticConsumer *Client = nullptr, 615 bool ShouldOwnClient = true); 616 617 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter. 618 /// 619 /// If no diagnostic client is provided, this creates a 620 /// DiagnosticConsumer that is owned by the returned diagnostic 621 /// object, if using directly the caller is responsible for 622 /// releasing the returned DiagnosticsEngine's client eventually. 623 /// 624 /// \param Opts - The diagnostic options; note that the created text 625 /// diagnostic object contains a reference to these options. 626 /// 627 /// \param Client If non-NULL, a diagnostic client that will be 628 /// attached to (and, then, owned by) the returned DiagnosticsEngine 629 /// object. 630 /// 631 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be 632 /// used by some diagnostics printers (for logging purposes only). 633 /// 634 /// \return The new object on success, or null on failure. 635 static IntrusiveRefCntPtr<DiagnosticsEngine> 636 createDiagnostics(DiagnosticOptions *Opts, 637 DiagnosticConsumer *Client = nullptr, 638 bool ShouldOwnClient = true, 639 const CodeGenOptions *CodeGenOpts = nullptr); 640 641 /// Create the file manager and replace any existing one with it. 642 /// 643 /// \return The new file manager on success, or null on failure. 644 FileManager * 645 createFileManager(IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr); 646 647 /// Create the source manager and replace any existing one with it. 648 void createSourceManager(FileManager &FileMgr); 649 650 /// Create the preprocessor, using the invocation, file, and source managers, 651 /// and replace any existing one with it. 652 void createPreprocessor(TranslationUnitKind TUKind); 653 654 std::string getSpecificModuleCachePath(); 655 656 /// Create the AST context. 657 void createASTContext(); 658 659 /// Create an external AST source to read a PCH file and attach it to the AST 660 /// context. 661 void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation, 662 bool AllowPCHWithCompilerErrors, 663 void *DeserializationListener, 664 bool OwnDeserializationListener); 665 666 /// Create an external AST source to read a PCH file. 667 /// 668 /// \return - The new object on success, or null on failure. 669 static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource( 670 StringRef Path, StringRef Sysroot, bool DisablePCHValidation, 671 bool AllowPCHWithCompilerErrors, Preprocessor &PP, 672 InMemoryModuleCache &ModuleCache, ASTContext &Context, 673 const PCHContainerReader &PCHContainerRdr, 674 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 675 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors, 676 void *DeserializationListener, bool OwnDeserializationListener, 677 bool Preamble, bool UseGlobalModuleIndex); 678 679 /// Create a code completion consumer using the invocation; note that this 680 /// will cause the source manager to truncate the input source file at the 681 /// completion point. 682 void createCodeCompletionConsumer(); 683 684 /// Create a code completion consumer to print code completion results, at 685 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS. 686 static CodeCompleteConsumer *createCodeCompletionConsumer( 687 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column, 688 const CodeCompleteOptions &Opts, raw_ostream &OS); 689 690 /// Create the Sema object to be used for parsing. 691 void createSema(TranslationUnitKind TUKind, 692 CodeCompleteConsumer *CompletionConsumer); 693 694 /// Create the frontend timer and replace any existing one with it. 695 void createFrontendTimer(); 696 697 /// Create the default output file (from the invocation's options) and add it 698 /// to the list of tracked output files. 699 /// 700 /// The files created by this function always use temporary files to write to 701 /// their result (that is, the data is written to a temporary file which will 702 /// atomically replace the target output on success). 703 /// 704 /// \return - Null on error. 705 std::unique_ptr<raw_pwrite_stream> 706 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "", 707 StringRef Extension = ""); 708 709 /// Create a new output file and add it to the list of tracked output files, 710 /// optionally deriving the output path name. 711 /// 712 /// \return - Null on error. 713 std::unique_ptr<raw_pwrite_stream> 714 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, 715 StringRef BaseInput, StringRef Extension, bool UseTemporary, 716 bool CreateMissingDirectories = false); 717 718 /// Create a new output file, optionally deriving the output path name. 719 /// 720 /// If \p OutputPath is empty, then createOutputFile will derive an output 721 /// path location as \p BaseInput, with any suffix removed, and \p Extension 722 /// appended. If \p OutputPath is not stdout and \p UseTemporary 723 /// is true, createOutputFile will create a new temporary file that must be 724 /// renamed to \p OutputPath in the end. 725 /// 726 /// \param OutputPath - If given, the path to the output file. 727 /// \param Error [out] - On failure, the error. 728 /// \param BaseInput - If \p OutputPath is empty, the input path name to use 729 /// for deriving the output path. 730 /// \param Extension - The extension to use for derived output names. 731 /// \param Binary - The mode to open the file in. 732 /// \param RemoveFileOnSignal - Whether the file should be registered with 733 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for 734 /// multithreaded use, as the underlying signal mechanism is not reentrant 735 /// \param UseTemporary - Create a new temporary file that must be renamed to 736 /// OutputPath in the end. 737 /// \param CreateMissingDirectories - When \p UseTemporary is true, create 738 /// missing directories in the output path. 739 /// \param ResultPathName [out] - If given, the result path name will be 740 /// stored here on success. 741 /// \param TempPathName [out] - If given, the temporary file path name 742 /// will be stored here on success. 743 std::unique_ptr<raw_pwrite_stream> 744 createOutputFile(StringRef OutputPath, std::error_code &Error, bool Binary, 745 bool RemoveFileOnSignal, StringRef BaseInput, 746 StringRef Extension, bool UseTemporary, 747 bool CreateMissingDirectories, std::string *ResultPathName, 748 std::string *TempPathName); 749 750 std::unique_ptr<raw_pwrite_stream> createNullOutputFile(); 751 752 /// } 753 /// @name Initialization Utility Methods 754 /// { 755 756 /// InitializeSourceManager - Initialize the source manager to set InputFile 757 /// as the main file. 758 /// 759 /// \return True on success. 760 bool InitializeSourceManager(const FrontendInputFile &Input); 761 762 /// InitializeSourceManager - Initialize the source manager to set InputFile 763 /// as the main file. 764 /// 765 /// \return True on success. 766 static bool InitializeSourceManager(const FrontendInputFile &Input, 767 DiagnosticsEngine &Diags, 768 FileManager &FileMgr, 769 SourceManager &SourceMgr, 770 HeaderSearch *HS, 771 DependencyOutputOptions &DepOpts, 772 const FrontendOptions &Opts); 773 774 /// } 775 776 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) { 777 OutputStream = std::move(OutStream); 778 } 779 780 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() { 781 return std::move(OutputStream); 782 } 783 784 // Create module manager. 785 void createASTReader(); 786 787 bool loadModuleFile(StringRef FileName); 788 789private: 790 /// Find a module, potentially compiling it, before reading its AST. This is 791 /// the guts of loadModule. 792 /// 793 /// For prebuilt modules, the Module is not expected to exist in 794 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the 795 /// ModuleManager, then it will be loaded and looked up. 796 /// 797 /// For implicit modules, the Module is expected to already be in the 798 /// ModuleMap. First attempt to load it from the given path on disk. If that 799 /// fails, defer to compileModuleAndReadAST, which will first build and then 800 /// load it. 801 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName, 802 SourceLocation ImportLoc, 803 SourceLocation ModuleNameLoc, 804 bool IsInclusionDirective); 805 806public: 807 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, 808 Module::NameVisibilityKind Visibility, 809 bool IsInclusionDirective) override; 810 811 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, 812 StringRef Source) override; 813 814 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, 815 SourceLocation ImportLoc) override; 816 817 bool hadModuleLoaderFatalFailure() const { 818 return ModuleLoader::HadFatalFailure; 819 } 820 821 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override; 822 823 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override; 824 825 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) { 826 DependencyCollectors.push_back(std::move(Listener)); 827 } 828 829 void setExternalSemaSource(IntrusiveRefCntPtr<ExternalSemaSource> ESS); 830 831 InMemoryModuleCache &getModuleCache() const { return *ModuleCache; } 832}; 833 834} // end namespace clang 835 836#endif 837