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 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 ModuleBuildFailed = 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::string TempFilename;
169 
170     OutputFile(std::string filename, std::string tempFilename)
171         : Filename(std::move(filename)), TempFilename(std::move(tempFilename)) {
172     }
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   /// }
223   /// @name Compiler Invocation and Options
224   /// {
225 
226   bool hasInvocation() const { return Invocation != nullptr; }
227 
228   CompilerInvocation &getInvocation() {
229     assert(Invocation && "Compiler instance has no invocation!");
230     return *Invocation;
231   }
232 
233   /// setInvocation - Replace the current invocation.
234   void setInvocation(std::shared_ptr<CompilerInvocation> Value);
235 
236   /// Indicates whether we should (re)build the global module index.
237   bool shouldBuildGlobalModuleIndex() const;
238 
239   /// Set the flag indicating whether we should (re)build the global
240   /// module index.
241   void setBuildGlobalModuleIndex(bool Build) {
242     BuildGlobalModuleIndex = Build;
243   }
244 
245   /// }
246   /// @name Forwarding Methods
247   /// {
248 
249   AnalyzerOptionsRef getAnalyzerOpts() {
250     return Invocation->getAnalyzerOpts();
251   }
252 
253   CodeGenOptions &getCodeGenOpts() {
254     return Invocation->getCodeGenOpts();
255   }
256   const CodeGenOptions &getCodeGenOpts() const {
257     return Invocation->getCodeGenOpts();
258   }
259 
260   DependencyOutputOptions &getDependencyOutputOpts() {
261     return Invocation->getDependencyOutputOpts();
262   }
263   const DependencyOutputOptions &getDependencyOutputOpts() const {
264     return Invocation->getDependencyOutputOpts();
265   }
266 
267   DiagnosticOptions &getDiagnosticOpts() {
268     return Invocation->getDiagnosticOpts();
269   }
270   const DiagnosticOptions &getDiagnosticOpts() const {
271     return Invocation->getDiagnosticOpts();
272   }
273 
274   FileSystemOptions &getFileSystemOpts() {
275     return Invocation->getFileSystemOpts();
276   }
277   const FileSystemOptions &getFileSystemOpts() const {
278     return Invocation->getFileSystemOpts();
279   }
280 
281   FrontendOptions &getFrontendOpts() {
282     return Invocation->getFrontendOpts();
283   }
284   const FrontendOptions &getFrontendOpts() const {
285     return Invocation->getFrontendOpts();
286   }
287 
288   HeaderSearchOptions &getHeaderSearchOpts() {
289     return Invocation->getHeaderSearchOpts();
290   }
291   const HeaderSearchOptions &getHeaderSearchOpts() const {
292     return Invocation->getHeaderSearchOpts();
293   }
294   std::shared_ptr<HeaderSearchOptions> getHeaderSearchOptsPtr() const {
295     return Invocation->getHeaderSearchOptsPtr();
296   }
297 
298   LangOptions &getLangOpts() {
299     return *Invocation->getLangOpts();
300   }
301   const LangOptions &getLangOpts() const {
302     return *Invocation->getLangOpts();
303   }
304 
305   PreprocessorOptions &getPreprocessorOpts() {
306     return Invocation->getPreprocessorOpts();
307   }
308   const PreprocessorOptions &getPreprocessorOpts() const {
309     return Invocation->getPreprocessorOpts();
310   }
311 
312   PreprocessorOutputOptions &getPreprocessorOutputOpts() {
313     return Invocation->getPreprocessorOutputOpts();
314   }
315   const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
316     return Invocation->getPreprocessorOutputOpts();
317   }
318 
319   TargetOptions &getTargetOpts() {
320     return Invocation->getTargetOpts();
321   }
322   const TargetOptions &getTargetOpts() const {
323     return Invocation->getTargetOpts();
324   }
325 
326   /// }
327   /// @name Diagnostics Engine
328   /// {
329 
330   bool hasDiagnostics() const { return Diagnostics != nullptr; }
331 
332   /// Get the current diagnostics engine.
333   DiagnosticsEngine &getDiagnostics() const {
334     assert(Diagnostics && "Compiler instance has no diagnostics!");
335     return *Diagnostics;
336   }
337 
338   /// setDiagnostics - Replace the current diagnostics engine.
339   void setDiagnostics(DiagnosticsEngine *Value);
340 
341   DiagnosticConsumer &getDiagnosticClient() const {
342     assert(Diagnostics && Diagnostics->getClient() &&
343            "Compiler instance has no diagnostic client!");
344     return *Diagnostics->getClient();
345   }
346 
347   /// }
348   /// @name VerboseOutputStream
349   /// }
350 
351   /// Replace the current stream for verbose output.
352   void setVerboseOutputStream(raw_ostream &Value);
353 
354   /// Replace the current stream for verbose output.
355   void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
356 
357   /// Get the current stream for verbose output.
358   raw_ostream &getVerboseOutputStream() {
359     return *VerboseOutputStream;
360   }
361 
362   /// }
363   /// @name Target Info
364   /// {
365 
366   bool hasTarget() const { return Target != nullptr; }
367 
368   TargetInfo &getTarget() const {
369     assert(Target && "Compiler instance has no target!");
370     return *Target;
371   }
372 
373   /// Replace the current Target.
374   void setTarget(TargetInfo *Value);
375 
376   /// }
377   /// @name AuxTarget Info
378   /// {
379 
380   TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
381 
382   /// Replace the current AuxTarget.
383   void setAuxTarget(TargetInfo *Value);
384 
385   /// }
386   /// @name Virtual File System
387   /// {
388 
389   llvm::vfs::FileSystem &getVirtualFileSystem() const;
390 
391   /// }
392   /// @name File Manager
393   /// {
394 
395   bool hasFileManager() const { return FileMgr != nullptr; }
396 
397   /// Return the current file manager to the caller.
398   FileManager &getFileManager() const {
399     assert(FileMgr && "Compiler instance has no file manager!");
400     return *FileMgr;
401   }
402 
403   void resetAndLeakFileManager() {
404     llvm::BuryPointer(FileMgr.get());
405     FileMgr.resetWithoutRelease();
406   }
407 
408   /// Replace the current file manager and virtual file system.
409   void setFileManager(FileManager *Value);
410 
411   /// }
412   /// @name Source Manager
413   /// {
414 
415   bool hasSourceManager() const { return SourceMgr != nullptr; }
416 
417   /// Return the current source manager.
418   SourceManager &getSourceManager() const {
419     assert(SourceMgr && "Compiler instance has no source manager!");
420     return *SourceMgr;
421   }
422 
423   void resetAndLeakSourceManager() {
424     llvm::BuryPointer(SourceMgr.get());
425     SourceMgr.resetWithoutRelease();
426   }
427 
428   /// setSourceManager - Replace the current source manager.
429   void setSourceManager(SourceManager *Value);
430 
431   /// }
432   /// @name Preprocessor
433   /// {
434 
435   bool hasPreprocessor() const { return PP != nullptr; }
436 
437   /// Return the current preprocessor.
438   Preprocessor &getPreprocessor() const {
439     assert(PP && "Compiler instance has no preprocessor!");
440     return *PP;
441   }
442 
443   std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; }
444 
445   void resetAndLeakPreprocessor() {
446     llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP));
447   }
448 
449   /// Replace the current preprocessor.
450   void setPreprocessor(std::shared_ptr<Preprocessor> Value);
451 
452   /// }
453   /// @name ASTContext
454   /// {
455 
456   bool hasASTContext() const { return Context != nullptr; }
457 
458   ASTContext &getASTContext() const {
459     assert(Context && "Compiler instance has no AST context!");
460     return *Context;
461   }
462 
463   void resetAndLeakASTContext() {
464     llvm::BuryPointer(Context.get());
465     Context.resetWithoutRelease();
466   }
467 
468   /// setASTContext - Replace the current AST context.
469   void setASTContext(ASTContext *Value);
470 
471   /// Replace the current Sema; the compiler instance takes ownership
472   /// of S.
473   void setSema(Sema *S);
474 
475   /// }
476   /// @name ASTConsumer
477   /// {
478 
479   bool hasASTConsumer() const { return (bool)Consumer; }
480 
481   ASTConsumer &getASTConsumer() const {
482     assert(Consumer && "Compiler instance has no AST consumer!");
483     return *Consumer;
484   }
485 
486   /// takeASTConsumer - Remove the current AST consumer and give ownership to
487   /// the caller.
488   std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
489 
490   /// setASTConsumer - Replace the current AST consumer; the compiler instance
491   /// takes ownership of \p Value.
492   void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
493 
494   /// }
495   /// @name Semantic analysis
496   /// {
497   bool hasSema() const { return (bool)TheSema; }
498 
499   Sema &getSema() const {
500     assert(TheSema && "Compiler instance has no Sema object!");
501     return *TheSema;
502   }
503 
504   std::unique_ptr<Sema> takeSema();
505   void resetAndLeakSema();
506 
507   /// }
508   /// @name Module Management
509   /// {
510 
511   IntrusiveRefCntPtr<ASTReader> getASTReader() const;
512   void setASTReader(IntrusiveRefCntPtr<ASTReader> Reader);
513 
514   std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
515   void setModuleDepCollector(
516       std::shared_ptr<ModuleDependencyCollector> Collector);
517 
518   std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
519     return ThePCHContainerOperations;
520   }
521 
522   /// Return the appropriate PCHContainerWriter depending on the
523   /// current CodeGenOptions.
524   const PCHContainerWriter &getPCHContainerWriter() const {
525     assert(Invocation && "cannot determine module format without invocation");
526     StringRef Format = getHeaderSearchOpts().ModuleFormat;
527     auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
528     if (!Writer) {
529       if (Diagnostics)
530         Diagnostics->Report(diag::err_module_format_unhandled) << Format;
531       llvm::report_fatal_error("unknown module format");
532     }
533     return *Writer;
534   }
535 
536   /// Return the appropriate PCHContainerReader depending on the
537   /// current CodeGenOptions.
538   const PCHContainerReader &getPCHContainerReader() const {
539     assert(Invocation && "cannot determine module format without invocation");
540     StringRef Format = getHeaderSearchOpts().ModuleFormat;
541     auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
542     if (!Reader) {
543       if (Diagnostics)
544         Diagnostics->Report(diag::err_module_format_unhandled) << Format;
545       llvm::report_fatal_error("unknown module format");
546     }
547     return *Reader;
548   }
549 
550   /// }
551   /// @name Code Completion
552   /// {
553 
554   bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
555 
556   CodeCompleteConsumer &getCodeCompletionConsumer() const {
557     assert(CompletionConsumer &&
558            "Compiler instance has no code completion consumer!");
559     return *CompletionConsumer;
560   }
561 
562   /// setCodeCompletionConsumer - Replace the current code completion consumer;
563   /// the compiler instance takes ownership of \p Value.
564   void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
565 
566   /// }
567   /// @name Frontend timer
568   /// {
569 
570   bool hasFrontendTimer() const { return (bool)FrontendTimer; }
571 
572   llvm::Timer &getFrontendTimer() const {
573     assert(FrontendTimer && "Compiler instance has no frontend timer!");
574     return *FrontendTimer;
575   }
576 
577   /// }
578   /// @name Output Files
579   /// {
580 
581   /// clearOutputFiles - Clear the output file list. The underlying output
582   /// streams must have been closed beforehand.
583   ///
584   /// \param EraseFiles - If true, attempt to erase the files from disk.
585   void clearOutputFiles(bool EraseFiles);
586 
587   /// }
588   /// @name Construction Utility Methods
589   /// {
590 
591   /// Create the diagnostics engine using the invocation's diagnostic options
592   /// and replace any existing one with it.
593   ///
594   /// Note that this routine also replaces the diagnostic client,
595   /// allocating one if one is not provided.
596   ///
597   /// \param Client If non-NULL, a diagnostic client that will be
598   /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
599   /// unit.
600   ///
601   /// \param ShouldOwnClient If Client is non-NULL, specifies whether
602   /// the diagnostic object should take ownership of the client.
603   void createDiagnostics(DiagnosticConsumer *Client = nullptr,
604                          bool ShouldOwnClient = true);
605 
606   /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
607   ///
608   /// If no diagnostic client is provided, this creates a
609   /// DiagnosticConsumer that is owned by the returned diagnostic
610   /// object, if using directly the caller is responsible for
611   /// releasing the returned DiagnosticsEngine's client eventually.
612   ///
613   /// \param Opts - The diagnostic options; note that the created text
614   /// diagnostic object contains a reference to these options.
615   ///
616   /// \param Client If non-NULL, a diagnostic client that will be
617   /// attached to (and, then, owned by) the returned DiagnosticsEngine
618   /// object.
619   ///
620   /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
621   /// used by some diagnostics printers (for logging purposes only).
622   ///
623   /// \return The new object on success, or null on failure.
624   static IntrusiveRefCntPtr<DiagnosticsEngine>
625   createDiagnostics(DiagnosticOptions *Opts,
626                     DiagnosticConsumer *Client = nullptr,
627                     bool ShouldOwnClient = true,
628                     const CodeGenOptions *CodeGenOpts = nullptr);
629 
630   /// Create the file manager and replace any existing one with it.
631   ///
632   /// \return The new file manager on success, or null on failure.
633   FileManager *
634   createFileManager(IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr);
635 
636   /// Create the source manager and replace any existing one with it.
637   void createSourceManager(FileManager &FileMgr);
638 
639   /// Create the preprocessor, using the invocation, file, and source managers,
640   /// and replace any existing one with it.
641   void createPreprocessor(TranslationUnitKind TUKind);
642 
643   std::string getSpecificModuleCachePath(StringRef ModuleHash);
644   std::string getSpecificModuleCachePath() {
645     return getSpecificModuleCachePath(getInvocation().getModuleHash());
646   }
647 
648   /// Create the AST context.
649   void createASTContext();
650 
651   /// Create an external AST source to read a PCH file and attach it to the AST
652   /// context.
653   void createPCHExternalASTSource(
654       StringRef Path, DisableValidationForModuleKind DisableValidation,
655       bool AllowPCHWithCompilerErrors, void *DeserializationListener,
656       bool OwnDeserializationListener);
657 
658   /// Create an external AST source to read a PCH file.
659   ///
660   /// \return - The new object on success, or null on failure.
661   static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
662       StringRef Path, StringRef Sysroot,
663       DisableValidationForModuleKind DisableValidation,
664       bool AllowPCHWithCompilerErrors, Preprocessor &PP,
665       InMemoryModuleCache &ModuleCache, ASTContext &Context,
666       const PCHContainerReader &PCHContainerRdr,
667       ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
668       ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
669       void *DeserializationListener, bool OwnDeserializationListener,
670       bool Preamble, bool UseGlobalModuleIndex);
671 
672   /// Create a code completion consumer using the invocation; note that this
673   /// will cause the source manager to truncate the input source file at the
674   /// completion point.
675   void createCodeCompletionConsumer();
676 
677   /// Create a code completion consumer to print code completion results, at
678   /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
679   static CodeCompleteConsumer *createCodeCompletionConsumer(
680       Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
681       const CodeCompleteOptions &Opts, raw_ostream &OS);
682 
683   /// Create the Sema object to be used for parsing.
684   void createSema(TranslationUnitKind TUKind,
685                   CodeCompleteConsumer *CompletionConsumer);
686 
687   /// Create the frontend timer and replace any existing one with it.
688   void createFrontendTimer();
689 
690   /// Create the default output file (from the invocation's options) and add it
691   /// to the list of tracked output files.
692   ///
693   /// The files created by this are usually removed on signal, and, depending
694   /// on FrontendOptions, may also use a temporary file (that is, the data is
695   /// written to a temporary file which will atomically replace the target
696   /// output on success). If a client (like libclang) needs to disable
697   /// RemoveFileOnSignal, temporary files will be forced on.
698   ///
699   /// \return - Null on error.
700   std::unique_ptr<raw_pwrite_stream>
701   createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
702                           StringRef Extension = "",
703                           bool RemoveFileOnSignal = true,
704                           bool CreateMissingDirectories = false);
705 
706   /// Create a new output file, optionally deriving the output path name, and
707   /// add it to the list of tracked output files.
708   ///
709   /// \return - Null on error.
710   std::unique_ptr<raw_pwrite_stream>
711   createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
712                    bool UseTemporary, bool CreateMissingDirectories = false);
713 
714 private:
715   /// Create a new output file and add it to the list of tracked output files.
716   ///
717   /// If \p OutputPath is empty, then createOutputFile will derive an output
718   /// path location as \p BaseInput, with any suffix removed, and \p Extension
719   /// appended. If \p OutputPath is not stdout and \p UseTemporary
720   /// is true, createOutputFile will create a new temporary file that must be
721   /// renamed to \p OutputPath in the end.
722   ///
723   /// \param OutputPath - If given, the path to the output file.
724   /// \param Binary - The mode to open the file in.
725   /// \param RemoveFileOnSignal - Whether the file should be registered with
726   /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
727   /// multithreaded use, as the underlying signal mechanism is not reentrant
728   /// \param UseTemporary - Create a new temporary file that must be renamed to
729   /// OutputPath in the end.
730   /// \param CreateMissingDirectories - When \p UseTemporary is true, create
731   /// missing directories in the output path.
732   Expected<std::unique_ptr<raw_pwrite_stream>>
733   createOutputFileImpl(StringRef OutputPath, bool Binary,
734                        bool RemoveFileOnSignal, bool UseTemporary,
735                        bool CreateMissingDirectories);
736 
737 public:
738   std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
739 
740   /// }
741   /// @name Initialization Utility Methods
742   /// {
743 
744   /// InitializeSourceManager - Initialize the source manager to set InputFile
745   /// as the main file.
746   ///
747   /// \return True on success.
748   bool InitializeSourceManager(const FrontendInputFile &Input);
749 
750   /// InitializeSourceManager - Initialize the source manager to set InputFile
751   /// as the main file.
752   ///
753   /// \return True on success.
754   static bool InitializeSourceManager(const FrontendInputFile &Input,
755                                       DiagnosticsEngine &Diags,
756                                       FileManager &FileMgr,
757                                       SourceManager &SourceMgr);
758 
759   /// }
760 
761   void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) {
762     OutputStream = std::move(OutStream);
763   }
764 
765   std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() {
766     return std::move(OutputStream);
767   }
768 
769   void createASTReader();
770 
771   bool loadModuleFile(StringRef FileName);
772 
773 private:
774   /// Find a module, potentially compiling it, before reading its AST.  This is
775   /// the guts of loadModule.
776   ///
777   /// For prebuilt modules, the Module is not expected to exist in
778   /// HeaderSearch's ModuleMap.  If a ModuleFile by that name is in the
779   /// ModuleManager, then it will be loaded and looked up.
780   ///
781   /// For implicit modules, the Module is expected to already be in the
782   /// ModuleMap.  First attempt to load it from the given path on disk.  If that
783   /// fails, defer to compileModuleAndReadAST, which will first build and then
784   /// load it.
785   ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
786                                                  SourceLocation ImportLoc,
787                                                  SourceLocation ModuleNameLoc,
788                                                  bool IsInclusionDirective);
789 
790 public:
791   ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
792                               Module::NameVisibilityKind Visibility,
793                               bool IsInclusionDirective) override;
794 
795   void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName,
796                               StringRef Source) override;
797 
798   void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
799                          SourceLocation ImportLoc) override;
800 
801   bool hadModuleLoaderFatalFailure() const {
802     return ModuleLoader::HadFatalFailure;
803   }
804 
805   GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override;
806 
807   bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
808 
809   void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
810     DependencyCollectors.push_back(std::move(Listener));
811   }
812 
813   void setExternalSemaSource(IntrusiveRefCntPtr<ExternalSemaSource> ESS);
814 
815   InMemoryModuleCache &getModuleCache() const { return *ModuleCache; }
816 };
817 
818 } // end namespace clang
819 
820 #endif
821