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