xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision dc5cbba3196db61d57b7d84118732a6c96d8ee64)
1 //===--- CompilerInstance.cpp ---------------------------------------------===//
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 #include "clang/Frontend/CompilerInstance.h"
10 #include "clang/AST/ASTConsumer.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/DiagnosticOptions.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/LangStandard.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/Stack.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Basic/Version.h"
22 #include "clang/Config/config.h"
23 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
24 #include "clang/Frontend/FrontendAction.h"
25 #include "clang/Frontend/FrontendActions.h"
26 #include "clang/Frontend/FrontendDiagnostic.h"
27 #include "clang/Frontend/FrontendPluginRegistry.h"
28 #include "clang/Frontend/LogDiagnosticPrinter.h"
29 #include "clang/Frontend/SARIFDiagnosticPrinter.h"
30 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
31 #include "clang/Frontend/TextDiagnosticPrinter.h"
32 #include "clang/Frontend/Utils.h"
33 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Lex/PreprocessorOptions.h"
37 #include "clang/Sema/CodeCompleteConsumer.h"
38 #include "clang/Sema/Sema.h"
39 #include "clang/Serialization/ASTReader.h"
40 #include "clang/Serialization/GlobalModuleIndex.h"
41 #include "clang/Serialization/InMemoryModuleCache.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/ScopeExit.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Config/llvm-config.h"
46 #include "llvm/Support/BuryPointer.h"
47 #include "llvm/Support/CrashRecoveryContext.h"
48 #include "llvm/Support/Errc.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/LockFileManager.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/Path.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/Signals.h"
55 #include "llvm/Support/TimeProfiler.h"
56 #include "llvm/Support/Timer.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/TargetParser/Host.h"
59 #include <optional>
60 #include <time.h>
61 #include <utility>
62 
63 using namespace clang;
64 
65 CompilerInstance::CompilerInstance(
66     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
67     InMemoryModuleCache *SharedModuleCache)
68     : ModuleLoader(/* BuildingModule = */ SharedModuleCache),
69       Invocation(new CompilerInvocation()),
70       ModuleCache(SharedModuleCache ? SharedModuleCache
71                                     : new InMemoryModuleCache),
72       ThePCHContainerOperations(std::move(PCHContainerOps)) {}
73 
74 CompilerInstance::~CompilerInstance() {
75   assert(OutputFiles.empty() && "Still output files in flight?");
76 }
77 
78 void CompilerInstance::setInvocation(
79     std::shared_ptr<CompilerInvocation> Value) {
80   Invocation = std::move(Value);
81 }
82 
83 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
84   return (BuildGlobalModuleIndex ||
85           (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
86            getFrontendOpts().GenerateGlobalModuleIndex)) &&
87          !DisableGeneratingGlobalModuleIndex;
88 }
89 
90 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
91   Diagnostics = Value;
92 }
93 
94 void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
95   OwnedVerboseOutputStream.reset();
96   VerboseOutputStream = &Value;
97 }
98 
99 void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
100   OwnedVerboseOutputStream.swap(Value);
101   VerboseOutputStream = OwnedVerboseOutputStream.get();
102 }
103 
104 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
105 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
106 
107 bool CompilerInstance::createTarget() {
108   // Create the target instance.
109   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
110                                          getInvocation().TargetOpts));
111   if (!hasTarget())
112     return false;
113 
114   // Check whether AuxTarget exists, if not, then create TargetInfo for the
115   // other side of CUDA/OpenMP/SYCL compilation.
116   if (!getAuxTarget() &&
117       (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
118        getLangOpts().SYCLIsDevice) &&
119       !getFrontendOpts().AuxTriple.empty()) {
120     auto TO = std::make_shared<TargetOptions>();
121     TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
122     if (getFrontendOpts().AuxTargetCPU)
123       TO->CPU = *getFrontendOpts().AuxTargetCPU;
124     if (getFrontendOpts().AuxTargetFeatures)
125       TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
126     TO->HostTriple = getTarget().getTriple().str();
127     setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
128   }
129 
130   if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
131     if (getLangOpts().RoundingMath) {
132       getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
133       getLangOpts().RoundingMath = false;
134     }
135     auto FPExc = getLangOpts().getFPExceptionMode();
136     if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
137       getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
138       getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
139     }
140     // FIXME: can we disable FEnvAccess?
141   }
142 
143   // We should do it here because target knows nothing about
144   // language options when it's being created.
145   if (getLangOpts().OpenCL &&
146       !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
147     return false;
148 
149   // Inform the target of the language options.
150   // FIXME: We shouldn't need to do this, the target should be immutable once
151   // created. This complexity should be lifted elsewhere.
152   getTarget().adjust(getDiagnostics(), getLangOpts());
153 
154   // Adjust target options based on codegen options.
155   getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
156 
157   if (auto *Aux = getAuxTarget())
158     getTarget().setAuxTarget(Aux);
159 
160   return true;
161 }
162 
163 llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const {
164   return getFileManager().getVirtualFileSystem();
165 }
166 
167 void CompilerInstance::setFileManager(FileManager *Value) {
168   FileMgr = Value;
169 }
170 
171 void CompilerInstance::setSourceManager(SourceManager *Value) {
172   SourceMgr = Value;
173 }
174 
175 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
176   PP = std::move(Value);
177 }
178 
179 void CompilerInstance::setASTContext(ASTContext *Value) {
180   Context = Value;
181 
182   if (Context && Consumer)
183     getASTConsumer().Initialize(getASTContext());
184 }
185 
186 void CompilerInstance::setSema(Sema *S) {
187   TheSema.reset(S);
188 }
189 
190 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
191   Consumer = std::move(Value);
192 
193   if (Context && Consumer)
194     getASTConsumer().Initialize(getASTContext());
195 }
196 
197 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
198   CompletionConsumer.reset(Value);
199 }
200 
201 std::unique_ptr<Sema> CompilerInstance::takeSema() {
202   return std::move(TheSema);
203 }
204 
205 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const {
206   return TheASTReader;
207 }
208 void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) {
209   assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
210          "Expected ASTReader to use the same PCM cache");
211   TheASTReader = std::move(Reader);
212 }
213 
214 std::shared_ptr<ModuleDependencyCollector>
215 CompilerInstance::getModuleDepCollector() const {
216   return ModuleDepCollector;
217 }
218 
219 void CompilerInstance::setModuleDepCollector(
220     std::shared_ptr<ModuleDependencyCollector> Collector) {
221   ModuleDepCollector = std::move(Collector);
222 }
223 
224 static void collectHeaderMaps(const HeaderSearch &HS,
225                               std::shared_ptr<ModuleDependencyCollector> MDC) {
226   SmallVector<std::string, 4> HeaderMapFileNames;
227   HS.getHeaderMapFileNames(HeaderMapFileNames);
228   for (auto &Name : HeaderMapFileNames)
229     MDC->addFile(Name);
230 }
231 
232 static void collectIncludePCH(CompilerInstance &CI,
233                               std::shared_ptr<ModuleDependencyCollector> MDC) {
234   const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
235   if (PPOpts.ImplicitPCHInclude.empty())
236     return;
237 
238   StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
239   FileManager &FileMgr = CI.getFileManager();
240   auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
241   if (!PCHDir) {
242     MDC->addFile(PCHInclude);
243     return;
244   }
245 
246   std::error_code EC;
247   SmallString<128> DirNative;
248   llvm::sys::path::native(PCHDir->getName(), DirNative);
249   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
250   SimpleASTReaderListener Validator(CI.getPreprocessor());
251   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
252        Dir != DirEnd && !EC; Dir.increment(EC)) {
253     // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
254     // used here since we're not interested in validating the PCH at this time,
255     // but only to check whether this is a file containing an AST.
256     if (!ASTReader::readASTFileControlBlock(
257             Dir->path(), FileMgr, CI.getModuleCache(),
258             CI.getPCHContainerReader(),
259             /*FindModuleFileExtensions=*/false, Validator,
260             /*ValidateDiagnosticOptions=*/false))
261       MDC->addFile(Dir->path());
262   }
263 }
264 
265 static void collectVFSEntries(CompilerInstance &CI,
266                               std::shared_ptr<ModuleDependencyCollector> MDC) {
267   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
268     return;
269 
270   // Collect all VFS found.
271   SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
272   for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
273     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
274         llvm::MemoryBuffer::getFile(VFSFile);
275     if (!Buffer)
276       return;
277     llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
278                                   /*DiagHandler*/ nullptr, VFSFile, VFSEntries);
279   }
280 
281   for (auto &E : VFSEntries)
282     MDC->addFile(E.VPath, E.RPath);
283 }
284 
285 // Diagnostics
286 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
287                                const CodeGenOptions *CodeGenOpts,
288                                DiagnosticsEngine &Diags) {
289   std::error_code EC;
290   std::unique_ptr<raw_ostream> StreamOwner;
291   raw_ostream *OS = &llvm::errs();
292   if (DiagOpts->DiagnosticLogFile != "-") {
293     // Create the output stream.
294     auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
295         DiagOpts->DiagnosticLogFile, EC,
296         llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
297     if (EC) {
298       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
299           << DiagOpts->DiagnosticLogFile << EC.message();
300     } else {
301       FileOS->SetUnbuffered();
302       OS = FileOS.get();
303       StreamOwner = std::move(FileOS);
304     }
305   }
306 
307   // Chain in the diagnostic client which will log the diagnostics.
308   auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
309                                                         std::move(StreamOwner));
310   if (CodeGenOpts)
311     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
312   if (Diags.ownsClient()) {
313     Diags.setClient(
314         new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
315   } else {
316     Diags.setClient(
317         new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
318   }
319 }
320 
321 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
322                                        DiagnosticsEngine &Diags,
323                                        StringRef OutputFile) {
324   auto SerializedConsumer =
325       clang::serialized_diags::create(OutputFile, DiagOpts);
326 
327   if (Diags.ownsClient()) {
328     Diags.setClient(new ChainedDiagnosticConsumer(
329         Diags.takeClient(), std::move(SerializedConsumer)));
330   } else {
331     Diags.setClient(new ChainedDiagnosticConsumer(
332         Diags.getClient(), std::move(SerializedConsumer)));
333   }
334 }
335 
336 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
337                                          bool ShouldOwnClient) {
338   Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
339                                   ShouldOwnClient, &getCodeGenOpts());
340 }
341 
342 IntrusiveRefCntPtr<DiagnosticsEngine>
343 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
344                                     DiagnosticConsumer *Client,
345                                     bool ShouldOwnClient,
346                                     const CodeGenOptions *CodeGenOpts) {
347   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
348   IntrusiveRefCntPtr<DiagnosticsEngine>
349       Diags(new DiagnosticsEngine(DiagID, Opts));
350 
351   // Create the diagnostic client for reporting errors or for
352   // implementing -verify.
353   if (Client) {
354     Diags->setClient(Client, ShouldOwnClient);
355   } else if (Opts->getFormat() == DiagnosticOptions::SARIF) {
356     Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
357   } else
358     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
359 
360   // Chain in -verify checker, if requested.
361   if (Opts->VerifyDiagnostics)
362     Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
363 
364   // Chain in -diagnostic-log-file dumper, if requested.
365   if (!Opts->DiagnosticLogFile.empty())
366     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
367 
368   if (!Opts->DiagnosticSerializationFile.empty())
369     SetupSerializedDiagnostics(Opts, *Diags,
370                                Opts->DiagnosticSerializationFile);
371 
372   // Configure our handling of diagnostics.
373   ProcessWarningOptions(*Diags, *Opts);
374 
375   return Diags;
376 }
377 
378 // File Manager
379 
380 FileManager *CompilerInstance::createFileManager(
381     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
382   if (!VFS)
383     VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
384                   : createVFSFromCompilerInvocation(getInvocation(),
385                                                     getDiagnostics());
386   assert(VFS && "FileManager has no VFS?");
387   FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
388   return FileMgr.get();
389 }
390 
391 // Source Manager
392 
393 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
394   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
395 }
396 
397 // Initialize the remapping of files to alternative contents, e.g.,
398 // those specified through other files.
399 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
400                                     SourceManager &SourceMgr,
401                                     FileManager &FileMgr,
402                                     const PreprocessorOptions &InitOpts) {
403   // Remap files in the source manager (with buffers).
404   for (const auto &RB : InitOpts.RemappedFileBuffers) {
405     // Create the file entry for the file that we're mapping from.
406     const FileEntry *FromFile =
407         FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
408     if (!FromFile) {
409       Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
410       if (!InitOpts.RetainRemappedFileBuffers)
411         delete RB.second;
412       continue;
413     }
414 
415     // Override the contents of the "from" file with the contents of the
416     // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
417     // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
418     // to the SourceManager.
419     if (InitOpts.RetainRemappedFileBuffers)
420       SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
421     else
422       SourceMgr.overrideFileContents(
423           FromFile, std::unique_ptr<llvm::MemoryBuffer>(
424                         const_cast<llvm::MemoryBuffer *>(RB.second)));
425   }
426 
427   // Remap files in the source manager (with other files).
428   for (const auto &RF : InitOpts.RemappedFiles) {
429     // Find the file that we're mapping to.
430     OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
431     if (!ToFile) {
432       Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
433       continue;
434     }
435 
436     // Create the file entry for the file that we're mapping from.
437     const FileEntry *FromFile =
438         FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
439     if (!FromFile) {
440       Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
441       continue;
442     }
443 
444     // Override the contents of the "from" file with the contents of
445     // the "to" file.
446     SourceMgr.overrideFileContents(FromFile, *ToFile);
447   }
448 
449   SourceMgr.setOverridenFilesKeepOriginalName(
450       InitOpts.RemappedFilesKeepOriginalName);
451 }
452 
453 // Preprocessor
454 
455 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
456   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
457 
458   // The AST reader holds a reference to the old preprocessor (if any).
459   TheASTReader.reset();
460 
461   // Create the Preprocessor.
462   HeaderSearch *HeaderInfo =
463       new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
464                        getDiagnostics(), getLangOpts(), &getTarget());
465   PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
466                                       getDiagnostics(), getLangOpts(),
467                                       getSourceManager(), *HeaderInfo, *this,
468                                       /*IdentifierInfoLookup=*/nullptr,
469                                       /*OwnsHeaderSearch=*/true, TUKind);
470   getTarget().adjust(getDiagnostics(), getLangOpts());
471   PP->Initialize(getTarget(), getAuxTarget());
472 
473   if (PPOpts.DetailedRecord)
474     PP->createPreprocessingRecord();
475 
476   // Apply remappings to the source manager.
477   InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
478                           PP->getFileManager(), PPOpts);
479 
480   // Predefine macros and configure the preprocessor.
481   InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
482                          getFrontendOpts());
483 
484   // Initialize the header search object.  In CUDA compilations, we use the aux
485   // triple (the host triple) to initialize our header search, since we need to
486   // find the host headers in order to compile the CUDA code.
487   const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
488   if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
489       PP->getAuxTargetInfo())
490     HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
491 
492   ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
493                            PP->getLangOpts(), *HeaderSearchTriple);
494 
495   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
496 
497   if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
498     std::string ModuleHash = getInvocation().getModuleHash();
499     PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
500     PP->getHeaderSearchInfo().setModuleCachePath(
501         getSpecificModuleCachePath(ModuleHash));
502   }
503 
504   // Handle generating dependencies, if requested.
505   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
506   if (!DepOpts.OutputFile.empty())
507     addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
508   if (!DepOpts.DOTOutputFile.empty())
509     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
510                              getHeaderSearchOpts().Sysroot);
511 
512   // If we don't have a collector, but we are collecting module dependencies,
513   // then we're the top level compiler instance and need to create one.
514   if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
515     ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
516         DepOpts.ModuleDependencyOutputDir);
517   }
518 
519   // If there is a module dep collector, register with other dep collectors
520   // and also (a) collect header maps and (b) TODO: input vfs overlay files.
521   if (ModuleDepCollector) {
522     addDependencyCollector(ModuleDepCollector);
523     collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
524     collectIncludePCH(*this, ModuleDepCollector);
525     collectVFSEntries(*this, ModuleDepCollector);
526   }
527 
528   for (auto &Listener : DependencyCollectors)
529     Listener->attachToPreprocessor(*PP);
530 
531   // Handle generating header include information, if requested.
532   if (DepOpts.ShowHeaderIncludes)
533     AttachHeaderIncludeGen(*PP, DepOpts);
534   if (!DepOpts.HeaderIncludeOutputFile.empty()) {
535     StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
536     if (OutputPath == "-")
537       OutputPath = "";
538     AttachHeaderIncludeGen(*PP, DepOpts,
539                            /*ShowAllHeaders=*/true, OutputPath,
540                            /*ShowDepth=*/false);
541   }
542 
543   if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
544     AttachHeaderIncludeGen(*PP, DepOpts,
545                            /*ShowAllHeaders=*/true, /*OutputPath=*/"",
546                            /*ShowDepth=*/true, /*MSStyle=*/true);
547   }
548 }
549 
550 std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
551   // Set up the module path, including the hash for the module-creation options.
552   SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
553   if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
554     llvm::sys::path::append(SpecificModuleCache, ModuleHash);
555   return std::string(SpecificModuleCache.str());
556 }
557 
558 // ASTContext
559 
560 void CompilerInstance::createASTContext() {
561   Preprocessor &PP = getPreprocessor();
562   auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
563                                  PP.getIdentifierTable(), PP.getSelectorTable(),
564                                  PP.getBuiltinInfo(), PP.TUKind);
565   Context->InitBuiltinTypes(getTarget(), getAuxTarget());
566   setASTContext(Context);
567 }
568 
569 // ExternalASTSource
570 
571 namespace {
572 // Helper to recursively read the module names for all modules we're adding.
573 // We mark these as known and redirect any attempt to load that module to
574 // the files we were handed.
575 struct ReadModuleNames : ASTReaderListener {
576   Preprocessor &PP;
577   llvm::SmallVector<std::string, 8> LoadedModules;
578 
579   ReadModuleNames(Preprocessor &PP) : PP(PP) {}
580 
581   void ReadModuleName(StringRef ModuleName) override {
582     // Keep the module name as a string for now. It's not safe to create a new
583     // IdentifierInfo from an ASTReader callback.
584     LoadedModules.push_back(ModuleName.str());
585   }
586 
587   void registerAll() {
588     ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
589     for (const std::string &LoadedModule : LoadedModules)
590       MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
591                          MM.findModule(LoadedModule));
592     LoadedModules.clear();
593   }
594 
595   void markAllUnavailable() {
596     for (const std::string &LoadedModule : LoadedModules) {
597       if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
598               LoadedModule)) {
599         M->HasIncompatibleModuleFile = true;
600 
601         // Mark module as available if the only reason it was unavailable
602         // was missing headers.
603         SmallVector<Module *, 2> Stack;
604         Stack.push_back(M);
605         while (!Stack.empty()) {
606           Module *Current = Stack.pop_back_val();
607           if (Current->IsUnimportable) continue;
608           Current->IsAvailable = true;
609           auto SubmodulesRange = Current->submodules();
610           Stack.insert(Stack.end(), SubmodulesRange.begin(),
611                        SubmodulesRange.end());
612         }
613       }
614     }
615     LoadedModules.clear();
616   }
617 };
618 } // namespace
619 
620 void CompilerInstance::createPCHExternalASTSource(
621     StringRef Path, DisableValidationForModuleKind DisableValidation,
622     bool AllowPCHWithCompilerErrors, void *DeserializationListener,
623     bool OwnDeserializationListener) {
624   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
625   TheASTReader = createPCHExternalASTSource(
626       Path, getHeaderSearchOpts().Sysroot, DisableValidation,
627       AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
628       getASTContext(), getPCHContainerReader(),
629       getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
630       DeserializationListener, OwnDeserializationListener, Preamble,
631       getFrontendOpts().UseGlobalModuleIndex);
632 }
633 
634 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
635     StringRef Path, StringRef Sysroot,
636     DisableValidationForModuleKind DisableValidation,
637     bool AllowPCHWithCompilerErrors, Preprocessor &PP,
638     InMemoryModuleCache &ModuleCache, ASTContext &Context,
639     const PCHContainerReader &PCHContainerRdr,
640     ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
641     ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
642     void *DeserializationListener, bool OwnDeserializationListener,
643     bool Preamble, bool UseGlobalModuleIndex) {
644   HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
645 
646   IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
647       PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
648       Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
649       AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
650       HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent,
651       UseGlobalModuleIndex));
652 
653   // We need the external source to be set up before we read the AST, because
654   // eagerly-deserialized declarations may use it.
655   Context.setExternalSource(Reader.get());
656 
657   Reader->setDeserializationListener(
658       static_cast<ASTDeserializationListener *>(DeserializationListener),
659       /*TakeOwnership=*/OwnDeserializationListener);
660 
661   for (auto &Listener : DependencyCollectors)
662     Listener->attachToASTReader(*Reader);
663 
664   auto Listener = std::make_unique<ReadModuleNames>(PP);
665   auto &ListenerRef = *Listener;
666   ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
667                                                    std::move(Listener));
668 
669   switch (Reader->ReadAST(Path,
670                           Preamble ? serialization::MK_Preamble
671                                    : serialization::MK_PCH,
672                           SourceLocation(),
673                           ASTReader::ARR_None)) {
674   case ASTReader::Success:
675     // Set the predefines buffer as suggested by the PCH reader. Typically, the
676     // predefines buffer will be empty.
677     PP.setPredefines(Reader->getSuggestedPredefines());
678     ListenerRef.registerAll();
679     return Reader;
680 
681   case ASTReader::Failure:
682     // Unrecoverable failure: don't even try to process the input file.
683     break;
684 
685   case ASTReader::Missing:
686   case ASTReader::OutOfDate:
687   case ASTReader::VersionMismatch:
688   case ASTReader::ConfigurationMismatch:
689   case ASTReader::HadErrors:
690     // No suitable PCH file could be found. Return an error.
691     break;
692   }
693 
694   ListenerRef.markAllUnavailable();
695   Context.setExternalSource(nullptr);
696   return nullptr;
697 }
698 
699 // Code Completion
700 
701 static bool EnableCodeCompletion(Preprocessor &PP,
702                                  StringRef Filename,
703                                  unsigned Line,
704                                  unsigned Column) {
705   // Tell the source manager to chop off the given file at a specific
706   // line and column.
707   auto Entry = PP.getFileManager().getFile(Filename);
708   if (!Entry) {
709     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
710       << Filename;
711     return true;
712   }
713 
714   // Truncate the named file at the given line/column.
715   PP.SetCodeCompletionPoint(*Entry, Line, Column);
716   return false;
717 }
718 
719 void CompilerInstance::createCodeCompletionConsumer() {
720   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
721   if (!CompletionConsumer) {
722     setCodeCompletionConsumer(createCodeCompletionConsumer(
723         getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
724         getFrontendOpts().CodeCompleteOpts, llvm::outs()));
725     return;
726   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
727                                   Loc.Line, Loc.Column)) {
728     setCodeCompletionConsumer(nullptr);
729     return;
730   }
731 }
732 
733 void CompilerInstance::createFrontendTimer() {
734   FrontendTimerGroup.reset(
735       new llvm::TimerGroup("frontend", "Clang front-end time report"));
736   FrontendTimer.reset(
737       new llvm::Timer("frontend", "Clang front-end timer",
738                       *FrontendTimerGroup));
739 }
740 
741 CodeCompleteConsumer *
742 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
743                                                StringRef Filename,
744                                                unsigned Line,
745                                                unsigned Column,
746                                                const CodeCompleteOptions &Opts,
747                                                raw_ostream &OS) {
748   if (EnableCodeCompletion(PP, Filename, Line, Column))
749     return nullptr;
750 
751   // Set up the creation routine for code-completion.
752   return new PrintingCodeCompleteConsumer(Opts, OS);
753 }
754 
755 void CompilerInstance::createSema(TranslationUnitKind TUKind,
756                                   CodeCompleteConsumer *CompletionConsumer) {
757   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
758                          TUKind, CompletionConsumer));
759   // Attach the external sema source if there is any.
760   if (ExternalSemaSrc) {
761     TheSema->addExternalSource(ExternalSemaSrc.get());
762     ExternalSemaSrc->InitializeSema(*TheSema);
763   }
764 }
765 
766 // Output Files
767 
768 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
769   // The ASTConsumer can own streams that write to the output files.
770   assert(!hasASTConsumer() && "ASTConsumer should be reset");
771   // Ignore errors that occur when trying to discard the temp file.
772   for (OutputFile &OF : OutputFiles) {
773     if (EraseFiles) {
774       if (OF.File)
775         consumeError(OF.File->discard());
776       if (!OF.Filename.empty())
777         llvm::sys::fs::remove(OF.Filename);
778       continue;
779     }
780 
781     if (!OF.File)
782       continue;
783 
784     if (OF.File->TmpName.empty()) {
785       consumeError(OF.File->discard());
786       continue;
787     }
788 
789     llvm::Error E = OF.File->keep(OF.Filename);
790     if (!E)
791       continue;
792 
793     getDiagnostics().Report(diag::err_unable_to_rename_temp)
794         << OF.File->TmpName << OF.Filename << std::move(E);
795 
796     llvm::sys::fs::remove(OF.File->TmpName);
797   }
798   OutputFiles.clear();
799   if (DeleteBuiltModules) {
800     for (auto &Module : BuiltModules)
801       llvm::sys::fs::remove(Module.second);
802     BuiltModules.clear();
803   }
804 }
805 
806 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
807     bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
808     bool CreateMissingDirectories, bool ForceUseTemporary) {
809   StringRef OutputPath = getFrontendOpts().OutputFile;
810   std::optional<SmallString<128>> PathStorage;
811   if (OutputPath.empty()) {
812     if (InFile == "-" || Extension.empty()) {
813       OutputPath = "-";
814     } else {
815       PathStorage.emplace(InFile);
816       llvm::sys::path::replace_extension(*PathStorage, Extension);
817       OutputPath = *PathStorage;
818     }
819   }
820 
821   return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
822                           getFrontendOpts().UseTemporary || ForceUseTemporary,
823                           CreateMissingDirectories);
824 }
825 
826 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
827   return std::make_unique<llvm::raw_null_ostream>();
828 }
829 
830 std::unique_ptr<raw_pwrite_stream>
831 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
832                                    bool RemoveFileOnSignal, bool UseTemporary,
833                                    bool CreateMissingDirectories) {
834   Expected<std::unique_ptr<raw_pwrite_stream>> OS =
835       createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
836                            CreateMissingDirectories);
837   if (OS)
838     return std::move(*OS);
839   getDiagnostics().Report(diag::err_fe_unable_to_open_output)
840       << OutputPath << errorToErrorCode(OS.takeError()).message();
841   return nullptr;
842 }
843 
844 Expected<std::unique_ptr<llvm::raw_pwrite_stream>>
845 CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
846                                        bool RemoveFileOnSignal,
847                                        bool UseTemporary,
848                                        bool CreateMissingDirectories) {
849   assert((!CreateMissingDirectories || UseTemporary) &&
850          "CreateMissingDirectories is only allowed when using temporary files");
851 
852   // If '-working-directory' was passed, the output filename should be
853   // relative to that.
854   std::optional<SmallString<128>> AbsPath;
855   if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
856     assert(hasFileManager() &&
857            "File Manager is required to fix up relative path.\n");
858 
859     AbsPath.emplace(OutputPath);
860     FileMgr->FixupRelativePath(*AbsPath);
861     OutputPath = *AbsPath;
862   }
863 
864   std::unique_ptr<llvm::raw_fd_ostream> OS;
865   std::optional<StringRef> OSFile;
866 
867   if (UseTemporary) {
868     if (OutputPath == "-")
869       UseTemporary = false;
870     else {
871       llvm::sys::fs::file_status Status;
872       llvm::sys::fs::status(OutputPath, Status);
873       if (llvm::sys::fs::exists(Status)) {
874         // Fail early if we can't write to the final destination.
875         if (!llvm::sys::fs::can_write(OutputPath))
876           return llvm::errorCodeToError(
877               make_error_code(llvm::errc::operation_not_permitted));
878 
879         // Don't use a temporary if the output is a special file. This handles
880         // things like '-o /dev/null'
881         if (!llvm::sys::fs::is_regular_file(Status))
882           UseTemporary = false;
883       }
884     }
885   }
886 
887   std::optional<llvm::sys::fs::TempFile> Temp;
888   if (UseTemporary) {
889     // Create a temporary file.
890     // Insert -%%%%%%%% before the extension (if any), and because some tools
891     // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
892     // artifacts, also append .tmp.
893     StringRef OutputExtension = llvm::sys::path::extension(OutputPath);
894     SmallString<128> TempPath =
895         StringRef(OutputPath).drop_back(OutputExtension.size());
896     TempPath += "-%%%%%%%%";
897     TempPath += OutputExtension;
898     TempPath += ".tmp";
899     llvm::sys::fs::OpenFlags BinaryFlags =
900         Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text;
901     Expected<llvm::sys::fs::TempFile> ExpectedFile =
902         llvm::sys::fs::TempFile::create(
903             TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
904             BinaryFlags);
905 
906     llvm::Error E = handleErrors(
907         ExpectedFile.takeError(), [&](const llvm::ECError &E) -> llvm::Error {
908           std::error_code EC = E.convertToErrorCode();
909           if (CreateMissingDirectories &&
910               EC == llvm::errc::no_such_file_or_directory) {
911             StringRef Parent = llvm::sys::path::parent_path(OutputPath);
912             EC = llvm::sys::fs::create_directories(Parent);
913             if (!EC) {
914               ExpectedFile = llvm::sys::fs::TempFile::create(
915                   TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
916                   BinaryFlags);
917               if (!ExpectedFile)
918                 return llvm::errorCodeToError(
919                     llvm::errc::no_such_file_or_directory);
920             }
921           }
922           return llvm::errorCodeToError(EC);
923         });
924 
925     if (E) {
926       consumeError(std::move(E));
927     } else {
928       Temp = std::move(ExpectedFile.get());
929       OS.reset(new llvm::raw_fd_ostream(Temp->FD, /*shouldClose=*/false));
930       OSFile = Temp->TmpName;
931     }
932     // If we failed to create the temporary, fallback to writing to the file
933     // directly. This handles the corner case where we cannot write to the
934     // directory, but can write to the file.
935   }
936 
937   if (!OS) {
938     OSFile = OutputPath;
939     std::error_code EC;
940     OS.reset(new llvm::raw_fd_ostream(
941         *OSFile, EC,
942         (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF)));
943     if (EC)
944       return llvm::errorCodeToError(EC);
945   }
946 
947   // Add the output file -- but don't try to remove "-", since this means we are
948   // using stdin.
949   OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(),
950                            std::move(Temp));
951 
952   if (!Binary || OS->supportsSeeking())
953     return std::move(OS);
954 
955   return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS));
956 }
957 
958 // Initialization Utilities
959 
960 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
961   return InitializeSourceManager(Input, getDiagnostics(), getFileManager(),
962                                  getSourceManager());
963 }
964 
965 // static
966 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
967                                                DiagnosticsEngine &Diags,
968                                                FileManager &FileMgr,
969                                                SourceManager &SourceMgr) {
970   SrcMgr::CharacteristicKind Kind =
971       Input.getKind().getFormat() == InputKind::ModuleMap
972           ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
973                              : SrcMgr::C_User_ModuleMap
974           : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
975 
976   if (Input.isBuffer()) {
977     SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
978     assert(SourceMgr.getMainFileID().isValid() &&
979            "Couldn't establish MainFileID!");
980     return true;
981   }
982 
983   StringRef InputFile = Input.getFile();
984 
985   // Figure out where to get and map in the main file.
986   auto FileOrErr = InputFile == "-"
987                        ? FileMgr.getSTDIN()
988                        : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
989   if (!FileOrErr) {
990     auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
991     if (InputFile != "-")
992       Diags.Report(diag::err_fe_error_reading) << InputFile << EC.message();
993     else
994       Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
995     return false;
996   }
997 
998   SourceMgr.setMainFileID(
999       SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
1000 
1001   assert(SourceMgr.getMainFileID().isValid() &&
1002          "Couldn't establish MainFileID!");
1003   return true;
1004 }
1005 
1006 // High-Level Operations
1007 
1008 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
1009   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
1010   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
1011   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
1012 
1013   // Mark this point as the bottom of the stack if we don't have somewhere
1014   // better. We generally expect frontend actions to be invoked with (nearly)
1015   // DesiredStackSpace available.
1016   noteBottomOfStack();
1017 
1018   auto FinishDiagnosticClient = llvm::make_scope_exit([&]() {
1019     // Notify the diagnostic client that all files were processed.
1020     getDiagnosticClient().finish();
1021   });
1022 
1023   raw_ostream &OS = getVerboseOutputStream();
1024 
1025   if (!Act.PrepareToExecute(*this))
1026     return false;
1027 
1028   if (!createTarget())
1029     return false;
1030 
1031   // rewriter project will change target built-in bool type from its default.
1032   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
1033     getTarget().noSignedCharForObjCBool();
1034 
1035   // Validate/process some options.
1036   if (getHeaderSearchOpts().Verbose)
1037     OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
1038        << LLVM_VERSION_STRING << " default target "
1039        << llvm::sys::getDefaultTargetTriple() << "\n";
1040 
1041   if (getCodeGenOpts().TimePasses)
1042     createFrontendTimer();
1043 
1044   if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
1045     llvm::EnableStatistics(false);
1046 
1047   for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
1048     // Reset the ID tables if we are reusing the SourceManager and parsing
1049     // regular files.
1050     if (hasSourceManager() && !Act.isModelParsingAction())
1051       getSourceManager().clearIDTables();
1052 
1053     if (Act.BeginSourceFile(*this, FIF)) {
1054       if (llvm::Error Err = Act.Execute()) {
1055         consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1056       }
1057       Act.EndSourceFile();
1058     }
1059   }
1060 
1061   if (getDiagnosticOpts().ShowCarets) {
1062     // We can have multiple diagnostics sharing one diagnostic client.
1063     // Get the total number of warnings/errors from the client.
1064     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1065     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1066 
1067     if (NumWarnings)
1068       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1069     if (NumWarnings && NumErrors)
1070       OS << " and ";
1071     if (NumErrors)
1072       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1073     if (NumWarnings || NumErrors) {
1074       OS << " generated";
1075       if (getLangOpts().CUDA) {
1076         if (!getLangOpts().CUDAIsDevice) {
1077           OS << " when compiling for host";
1078         } else {
1079           OS << " when compiling for " << getTargetOpts().CPU;
1080         }
1081       }
1082       OS << ".\n";
1083     }
1084   }
1085 
1086   if (getFrontendOpts().ShowStats) {
1087     if (hasFileManager()) {
1088       getFileManager().PrintStats();
1089       OS << '\n';
1090     }
1091     llvm::PrintStatistics(OS);
1092   }
1093   StringRef StatsFile = getFrontendOpts().StatsFile;
1094   if (!StatsFile.empty()) {
1095     llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1096     if (getFrontendOpts().AppendStats)
1097       FileFlags |= llvm::sys::fs::OF_Append;
1098     std::error_code EC;
1099     auto StatS =
1100         std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1101     if (EC) {
1102       getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1103           << StatsFile << EC.message();
1104     } else {
1105       llvm::PrintStatisticsJSON(*StatS);
1106     }
1107   }
1108 
1109   return !getDiagnostics().getClient()->getNumErrors();
1110 }
1111 
1112 void CompilerInstance::LoadRequestedPlugins() {
1113   // Load any requested plugins.
1114   for (const std::string &Path : getFrontendOpts().Plugins) {
1115     std::string Error;
1116     if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
1117       getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1118           << Path << Error;
1119   }
1120 
1121   // Check if any of the loaded plugins replaces the main AST action
1122   for (const FrontendPluginRegistry::entry &Plugin :
1123        FrontendPluginRegistry::entries()) {
1124     std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1125     if (P->getActionType() == PluginASTAction::ReplaceAction) {
1126       getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
1127       getFrontendOpts().ActionName = Plugin.getName().str();
1128       break;
1129     }
1130   }
1131 }
1132 
1133 /// Determine the appropriate source input kind based on language
1134 /// options.
1135 static Language getLanguageFromOptions(const LangOptions &LangOpts) {
1136   if (LangOpts.OpenCL)
1137     return Language::OpenCL;
1138   if (LangOpts.CUDA)
1139     return Language::CUDA;
1140   if (LangOpts.ObjC)
1141     return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1142   return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1143 }
1144 
1145 /// Compile a module file for the given module, using the options
1146 /// provided by the importing compiler instance. Returns true if the module
1147 /// was built without errors.
1148 static bool
1149 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1150                   StringRef ModuleName, FrontendInputFile Input,
1151                   StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1152                   llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
1153                       [](CompilerInstance &) {},
1154                   llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1155                       [](CompilerInstance &) {}) {
1156   llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1157 
1158   // Never compile a module that's already finalized - this would cause the
1159   // existing module to be freed, causing crashes if it is later referenced
1160   if (ImportingInstance.getModuleCache().isPCMFinal(ModuleFileName)) {
1161     ImportingInstance.getDiagnostics().Report(
1162         ImportLoc, diag::err_module_rebuild_finalized)
1163         << ModuleName;
1164     return false;
1165   }
1166 
1167   // Construct a compiler invocation for creating this module.
1168   auto Invocation =
1169       std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
1170 
1171   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1172 
1173   // For any options that aren't intended to affect how a module is built,
1174   // reset them to their default values.
1175   Invocation->resetNonModularOptions();
1176 
1177   // Remove any macro definitions that are explicitly ignored by the module.
1178   // They aren't supposed to affect how the module is built anyway.
1179   HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1180   llvm::erase_if(PPOpts.Macros,
1181                  [&HSOpts](const std::pair<std::string, bool> &def) {
1182                    StringRef MacroDef = def.first;
1183                    return HSOpts.ModulesIgnoreMacros.contains(
1184                        llvm::CachedHashString(MacroDef.split('=').first));
1185                  });
1186 
1187   // If the original compiler invocation had -fmodule-name, pass it through.
1188   Invocation->getLangOpts()->ModuleName =
1189       ImportingInstance.getInvocation().getLangOpts()->ModuleName;
1190 
1191   // Note the name of the module we're building.
1192   Invocation->getLangOpts()->CurrentModule = std::string(ModuleName);
1193 
1194   // Make sure that the failed-module structure has been allocated in
1195   // the importing instance, and propagate the pointer to the newly-created
1196   // instance.
1197   PreprocessorOptions &ImportingPPOpts
1198     = ImportingInstance.getInvocation().getPreprocessorOpts();
1199   if (!ImportingPPOpts.FailedModules)
1200     ImportingPPOpts.FailedModules =
1201         std::make_shared<PreprocessorOptions::FailedModulesSet>();
1202   PPOpts.FailedModules = ImportingPPOpts.FailedModules;
1203 
1204   // If there is a module map file, build the module using the module map.
1205   // Set up the inputs/outputs so that we build the module from its umbrella
1206   // header.
1207   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1208   FrontendOpts.OutputFile = ModuleFileName.str();
1209   FrontendOpts.DisableFree = false;
1210   FrontendOpts.GenerateGlobalModuleIndex = false;
1211   FrontendOpts.BuildingImplicitModule = true;
1212   FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1213   // Force implicitly-built modules to hash the content of the module file.
1214   HSOpts.ModulesHashContent = true;
1215   FrontendOpts.Inputs = {Input};
1216 
1217   // Don't free the remapped file buffers; they are owned by our caller.
1218   PPOpts.RetainRemappedFileBuffers = true;
1219 
1220   DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1221 
1222   DiagOpts.VerifyDiagnostics = 0;
1223   assert(ImportingInstance.getInvocation().getModuleHash() ==
1224          Invocation->getModuleHash() && "Module hash mismatch!");
1225 
1226   // Construct a compiler instance that will be used to actually create the
1227   // module.  Since we're sharing an in-memory module cache,
1228   // CompilerInstance::CompilerInstance is responsible for finalizing the
1229   // buffers to prevent use-after-frees.
1230   CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
1231                             &ImportingInstance.getModuleCache());
1232   auto &Inv = *Invocation;
1233   Instance.setInvocation(std::move(Invocation));
1234 
1235   Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
1236                                    ImportingInstance.getDiagnosticClient()),
1237                              /*ShouldOwnClient=*/true);
1238 
1239   if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
1240     Instance.getDiagnostics().setSuppressSystemWarnings(false);
1241 
1242   if (FrontendOpts.ModulesShareFileManager) {
1243     Instance.setFileManager(&ImportingInstance.getFileManager());
1244   } else {
1245     Instance.createFileManager(&ImportingInstance.getVirtualFileSystem());
1246   }
1247   Instance.createSourceManager(Instance.getFileManager());
1248   SourceManager &SourceMgr = Instance.getSourceManager();
1249 
1250   // Note that this module is part of the module build stack, so that we
1251   // can detect cycles in the module graph.
1252   SourceMgr.setModuleBuildStack(
1253     ImportingInstance.getSourceManager().getModuleBuildStack());
1254   SourceMgr.pushModuleBuildStack(ModuleName,
1255     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
1256 
1257   // If we're collecting module dependencies, we need to share a collector
1258   // between all of the module CompilerInstances. Other than that, we don't
1259   // want to produce any dependency output from the module build.
1260   Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
1261   Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1262 
1263   ImportingInstance.getDiagnostics().Report(ImportLoc,
1264                                             diag::remark_module_build)
1265     << ModuleName << ModuleFileName;
1266 
1267   PreBuildStep(Instance);
1268 
1269   // Execute the action to actually build the module in-place. Use a separate
1270   // thread so that we get a stack large enough.
1271   bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread(
1272       [&]() {
1273         GenerateModuleFromModuleMapAction Action;
1274         Instance.ExecuteAction(Action);
1275       },
1276       DesiredStackSize);
1277 
1278   PostBuildStep(Instance);
1279 
1280   ImportingInstance.getDiagnostics().Report(ImportLoc,
1281                                             diag::remark_module_build_done)
1282     << ModuleName;
1283 
1284   if (Crashed) {
1285     // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1286     // that must be closed before clearing output files.
1287     Instance.setSema(nullptr);
1288     Instance.setASTConsumer(nullptr);
1289 
1290     // Delete any remaining temporary files related to Instance.
1291     Instance.clearOutputFiles(/*EraseFiles=*/true);
1292   }
1293 
1294   // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1295   // occurred.
1296   return !Instance.getDiagnostics().hasErrorOccurred() ||
1297          Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1298 }
1299 
1300 static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File,
1301                                                FileManager &FileMgr) {
1302   StringRef Filename = llvm::sys::path::filename(File.getName());
1303   SmallString<128> PublicFilename(File.getDir().getName());
1304   if (Filename == "module_private.map")
1305     llvm::sys::path::append(PublicFilename, "module.map");
1306   else if (Filename == "module.private.modulemap")
1307     llvm::sys::path::append(PublicFilename, "module.modulemap");
1308   else
1309     return std::nullopt;
1310   return FileMgr.getOptionalFileRef(PublicFilename);
1311 }
1312 
1313 /// Compile a module file for the given module in a separate compiler instance,
1314 /// using the options provided by the importing compiler instance. Returns true
1315 /// if the module was built without errors.
1316 static bool compileModule(CompilerInstance &ImportingInstance,
1317                           SourceLocation ImportLoc, Module *Module,
1318                           StringRef ModuleFileName) {
1319   InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
1320                InputKind::ModuleMap);
1321 
1322   // Get or create the module map that we'll use to build this module.
1323   ModuleMap &ModMap
1324     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1325   bool Result;
1326   if (OptionalFileEntryRef ModuleMapFile =
1327           ModMap.getContainingModuleMapFile(Module)) {
1328     // Canonicalize compilation to start with the public module map. This is
1329     // vital for submodules declarations in the private module maps to be
1330     // correctly parsed when depending on a top level module in the public one.
1331     if (OptionalFileEntryRef PublicMMFile = getPublicModuleMap(
1332             *ModuleMapFile, ImportingInstance.getFileManager()))
1333       ModuleMapFile = PublicMMFile;
1334 
1335     StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1336 
1337     // Use the module map where this module resides.
1338     Result = compileModuleImpl(
1339         ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1340         FrontendInputFile(ModuleMapFilePath, IK, +Module->IsSystem),
1341         ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName);
1342   } else {
1343     // FIXME: We only need to fake up an input file here as a way of
1344     // transporting the module's directory to the module map parser. We should
1345     // be able to do that more directly, and parse from a memory buffer without
1346     // inventing this file.
1347     SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1348     llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1349 
1350     std::string InferredModuleMapContent;
1351     llvm::raw_string_ostream OS(InferredModuleMapContent);
1352     Module->print(OS);
1353     OS.flush();
1354 
1355     Result = compileModuleImpl(
1356         ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1357         FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1358         ModMap.getModuleMapFileForUniquing(Module)->getName(),
1359         ModuleFileName,
1360         [&](CompilerInstance &Instance) {
1361       std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1362           llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1363       const FileEntry *ModuleMapFile = Instance.getFileManager().getVirtualFile(
1364           FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1365       Instance.getSourceManager().overrideFileContents(
1366           ModuleMapFile, std::move(ModuleMapBuffer));
1367     });
1368   }
1369 
1370   // We've rebuilt a module. If we're allowed to generate or update the global
1371   // module index, record that fact in the importing compiler instance.
1372   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1373     ImportingInstance.setBuildGlobalModuleIndex(true);
1374   }
1375 
1376   return Result;
1377 }
1378 
1379 /// Read the AST right after compiling the module.
1380 static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1381                                       SourceLocation ImportLoc,
1382                                       SourceLocation ModuleNameLoc,
1383                                       Module *Module, StringRef ModuleFileName,
1384                                       bool *OutOfDate) {
1385   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1386 
1387   unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1388   if (OutOfDate)
1389     ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1390 
1391   // Try to read the module file, now that we've compiled it.
1392   ASTReader::ASTReadResult ReadResult =
1393       ImportingInstance.getASTReader()->ReadAST(
1394           ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1395           ModuleLoadCapabilities);
1396   if (ReadResult == ASTReader::Success)
1397     return true;
1398 
1399   // The caller wants to handle out-of-date failures.
1400   if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1401     *OutOfDate = true;
1402     return false;
1403   }
1404 
1405   // The ASTReader didn't diagnose the error, so conservatively report it.
1406   if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1407     Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1408       << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1409 
1410   return false;
1411 }
1412 
1413 /// Compile a module in a separate compiler instance and read the AST,
1414 /// returning true if the module compiles without errors.
1415 static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
1416                                         SourceLocation ImportLoc,
1417                                         SourceLocation ModuleNameLoc,
1418                                         Module *Module,
1419                                         StringRef ModuleFileName) {
1420   if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
1421                      ModuleFileName)) {
1422     ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1423                                               diag::err_module_not_built)
1424         << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1425     return false;
1426   }
1427 
1428   return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1429                                    Module, ModuleFileName,
1430                                    /*OutOfDate=*/nullptr);
1431 }
1432 
1433 /// Compile a module in a separate compiler instance and read the AST,
1434 /// returning true if the module compiles without errors, using a lock manager
1435 /// to avoid building the same module in multiple compiler instances.
1436 ///
1437 /// Uses a lock file manager and exponential backoff to reduce the chances that
1438 /// multiple instances will compete to create the same module.  On timeout,
1439 /// deletes the lock file in order to avoid deadlock from crashing processes or
1440 /// bugs in the lock file manager.
1441 static bool compileModuleAndReadASTBehindLock(
1442     CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1443     SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
1444   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1445 
1446   Diags.Report(ModuleNameLoc, diag::remark_module_lock)
1447       << ModuleFileName << Module->Name;
1448 
1449   // FIXME: have LockFileManager return an error_code so that we can
1450   // avoid the mkdir when the directory already exists.
1451   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1452   llvm::sys::fs::create_directories(Dir);
1453 
1454   while (true) {
1455     llvm::LockFileManager Locked(ModuleFileName);
1456     switch (Locked) {
1457     case llvm::LockFileManager::LFS_Error:
1458       // ModuleCache takes care of correctness and locks are only necessary for
1459       // performance. Fallback to building the module in case of any lock
1460       // related errors.
1461       Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1462           << Module->Name << Locked.getErrorMessage();
1463       // Clear out any potential leftover.
1464       Locked.unsafeRemoveLockFile();
1465       [[fallthrough]];
1466     case llvm::LockFileManager::LFS_Owned:
1467       // We're responsible for building the module ourselves.
1468       return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1469                                          ModuleNameLoc, Module, ModuleFileName);
1470 
1471     case llvm::LockFileManager::LFS_Shared:
1472       break; // The interesting case.
1473     }
1474 
1475     // Someone else is responsible for building the module. Wait for them to
1476     // finish.
1477     switch (Locked.waitForUnlock()) {
1478     case llvm::LockFileManager::Res_Success:
1479       break; // The interesting case.
1480     case llvm::LockFileManager::Res_OwnerDied:
1481       continue; // try again to get the lock.
1482     case llvm::LockFileManager::Res_Timeout:
1483       // Since ModuleCache takes care of correctness, we try waiting for
1484       // another process to complete the build so clang does not do it done
1485       // twice. If case of timeout, build it ourselves.
1486       Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1487           << Module->Name;
1488       // Clear the lock file so that future invocations can make progress.
1489       Locked.unsafeRemoveLockFile();
1490       continue;
1491     }
1492 
1493     // Read the module that was just written by someone else.
1494     bool OutOfDate = false;
1495     if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1496                                   Module, ModuleFileName, &OutOfDate))
1497       return true;
1498     if (!OutOfDate)
1499       return false;
1500 
1501     // The module may be out of date in the presence of file system races,
1502     // or if one of its imports depends on header search paths that are not
1503     // consistent with this ImportingInstance.  Try again...
1504   }
1505 }
1506 
1507 /// Compile a module in a separate compiler instance and read the AST,
1508 /// returning true if the module compiles without errors, potentially using a
1509 /// lock manager to avoid building the same module in multiple compiler
1510 /// instances.
1511 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1512                                     SourceLocation ImportLoc,
1513                                     SourceLocation ModuleNameLoc,
1514                                     Module *Module, StringRef ModuleFileName) {
1515   return ImportingInstance.getInvocation()
1516                  .getFrontendOpts()
1517                  .BuildingImplicitModuleUsesLock
1518              ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
1519                                                  ModuleNameLoc, Module,
1520                                                  ModuleFileName)
1521              : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1522                                            ModuleNameLoc, Module,
1523                                            ModuleFileName);
1524 }
1525 
1526 /// Diagnose differences between the current definition of the given
1527 /// configuration macro and the definition provided on the command line.
1528 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1529                              Module *Mod, SourceLocation ImportLoc) {
1530   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1531   SourceManager &SourceMgr = PP.getSourceManager();
1532 
1533   // If this identifier has never had a macro definition, then it could
1534   // not have changed.
1535   if (!Id->hadMacroDefinition())
1536     return;
1537   auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1538 
1539   // Find the macro definition from the command line.
1540   MacroInfo *CmdLineDefinition = nullptr;
1541   for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1542     // We only care about the predefines buffer.
1543     FileID FID = SourceMgr.getFileID(MD->getLocation());
1544     if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1545       continue;
1546     if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1547       CmdLineDefinition = DMD->getMacroInfo();
1548     break;
1549   }
1550 
1551   auto *CurrentDefinition = PP.getMacroInfo(Id);
1552   if (CurrentDefinition == CmdLineDefinition) {
1553     // Macro matches. Nothing to do.
1554   } else if (!CurrentDefinition) {
1555     // This macro was defined on the command line, then #undef'd later.
1556     // Complain.
1557     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1558       << true << ConfigMacro << Mod->getFullModuleName();
1559     auto LatestDef = LatestLocalMD->getDefinition();
1560     assert(LatestDef.isUndefined() &&
1561            "predefined macro went away with no #undef?");
1562     PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1563       << true;
1564     return;
1565   } else if (!CmdLineDefinition) {
1566     // There was no definition for this macro in the predefines buffer,
1567     // but there was a local definition. Complain.
1568     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1569       << false << ConfigMacro << Mod->getFullModuleName();
1570     PP.Diag(CurrentDefinition->getDefinitionLoc(),
1571             diag::note_module_def_undef_here)
1572       << false;
1573   } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1574                                                /*Syntactically=*/true)) {
1575     // The macro definitions differ.
1576     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1577       << false << ConfigMacro << Mod->getFullModuleName();
1578     PP.Diag(CurrentDefinition->getDefinitionLoc(),
1579             diag::note_module_def_undef_here)
1580       << false;
1581   }
1582 }
1583 
1584 /// Write a new timestamp file with the given path.
1585 static void writeTimestampFile(StringRef TimestampFile) {
1586   std::error_code EC;
1587   llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
1588 }
1589 
1590 /// Prune the module cache of modules that haven't been accessed in
1591 /// a long time.
1592 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1593   llvm::sys::fs::file_status StatBuf;
1594   llvm::SmallString<128> TimestampFile;
1595   TimestampFile = HSOpts.ModuleCachePath;
1596   assert(!TimestampFile.empty());
1597   llvm::sys::path::append(TimestampFile, "modules.timestamp");
1598 
1599   // Try to stat() the timestamp file.
1600   if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
1601     // If the timestamp file wasn't there, create one now.
1602     if (EC == std::errc::no_such_file_or_directory) {
1603       writeTimestampFile(TimestampFile);
1604     }
1605     return;
1606   }
1607 
1608   // Check whether the time stamp is older than our pruning interval.
1609   // If not, do nothing.
1610   time_t TimeStampModTime =
1611       llvm::sys::toTimeT(StatBuf.getLastModificationTime());
1612   time_t CurrentTime = time(nullptr);
1613   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1614     return;
1615 
1616   // Write a new timestamp file so that nobody else attempts to prune.
1617   // There is a benign race condition here, if two Clang instances happen to
1618   // notice at the same time that the timestamp is out-of-date.
1619   writeTimestampFile(TimestampFile);
1620 
1621   // Walk the entire module cache, looking for unused module files and module
1622   // indices.
1623   std::error_code EC;
1624   SmallString<128> ModuleCachePathNative;
1625   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1626   for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1627        Dir != DirEnd && !EC; Dir.increment(EC)) {
1628     // If we don't have a directory, there's nothing to look into.
1629     if (!llvm::sys::fs::is_directory(Dir->path()))
1630       continue;
1631 
1632     // Walk all of the files within this directory.
1633     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1634          File != FileEnd && !EC; File.increment(EC)) {
1635       // We only care about module and global module index files.
1636       StringRef Extension = llvm::sys::path::extension(File->path());
1637       if (Extension != ".pcm" && Extension != ".timestamp" &&
1638           llvm::sys::path::filename(File->path()) != "modules.idx")
1639         continue;
1640 
1641       // Look at this file. If we can't stat it, there's nothing interesting
1642       // there.
1643       if (llvm::sys::fs::status(File->path(), StatBuf))
1644         continue;
1645 
1646       // If the file has been used recently enough, leave it there.
1647       time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
1648       if (CurrentTime - FileAccessTime <=
1649               time_t(HSOpts.ModuleCachePruneAfter)) {
1650         continue;
1651       }
1652 
1653       // Remove the file.
1654       llvm::sys::fs::remove(File->path());
1655 
1656       // Remove the timestamp file.
1657       std::string TimpestampFilename = File->path() + ".timestamp";
1658       llvm::sys::fs::remove(TimpestampFilename);
1659     }
1660 
1661     // If we removed all of the files in the directory, remove the directory
1662     // itself.
1663     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1664             llvm::sys::fs::directory_iterator() && !EC)
1665       llvm::sys::fs::remove(Dir->path());
1666   }
1667 }
1668 
1669 void CompilerInstance::createASTReader() {
1670   if (TheASTReader)
1671     return;
1672 
1673   if (!hasASTContext())
1674     createASTContext();
1675 
1676   // If we're implicitly building modules but not currently recursively
1677   // building a module, check whether we need to prune the module cache.
1678   if (getSourceManager().getModuleBuildStack().empty() &&
1679       !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1680       getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1681       getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1682     pruneModuleCache(getHeaderSearchOpts());
1683   }
1684 
1685   HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1686   std::string Sysroot = HSOpts.Sysroot;
1687   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1688   const FrontendOptions &FEOpts = getFrontendOpts();
1689   std::unique_ptr<llvm::Timer> ReadTimer;
1690 
1691   if (FrontendTimerGroup)
1692     ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1693                                                 "Reading modules",
1694                                                 *FrontendTimerGroup);
1695   TheASTReader = new ASTReader(
1696       getPreprocessor(), getModuleCache(), &getASTContext(),
1697       getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
1698       Sysroot.empty() ? "" : Sysroot.c_str(),
1699       PPOpts.DisablePCHOrModuleValidation,
1700       /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1701       /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders,
1702       HSOpts.ValidateASTInputFilesContent,
1703       getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1704   if (hasASTConsumer()) {
1705     TheASTReader->setDeserializationListener(
1706         getASTConsumer().GetASTDeserializationListener());
1707     getASTContext().setASTMutationListener(
1708       getASTConsumer().GetASTMutationListener());
1709   }
1710   getASTContext().setExternalSource(TheASTReader);
1711   if (hasSema())
1712     TheASTReader->InitializeSema(getSema());
1713   if (hasASTConsumer())
1714     TheASTReader->StartTranslationUnit(&getASTConsumer());
1715 
1716   for (auto &Listener : DependencyCollectors)
1717     Listener->attachToASTReader(*TheASTReader);
1718 }
1719 
1720 bool CompilerInstance::loadModuleFile(StringRef FileName) {
1721   llvm::Timer Timer;
1722   if (FrontendTimerGroup)
1723     Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1724                *FrontendTimerGroup);
1725   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1726 
1727   // If we don't already have an ASTReader, create one now.
1728   if (!TheASTReader)
1729     createASTReader();
1730 
1731   // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1732   // ASTReader to diagnose it, since it can produce better errors that we can.
1733   bool ConfigMismatchIsRecoverable =
1734       getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
1735                                           SourceLocation())
1736         <= DiagnosticsEngine::Warning;
1737 
1738   auto Listener = std::make_unique<ReadModuleNames>(*PP);
1739   auto &ListenerRef = *Listener;
1740   ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1741                                                    std::move(Listener));
1742 
1743   // Try to load the module file.
1744   switch (TheASTReader->ReadAST(
1745       FileName, serialization::MK_ExplicitModule, SourceLocation(),
1746       ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) {
1747   case ASTReader::Success:
1748     // We successfully loaded the module file; remember the set of provided
1749     // modules so that we don't try to load implicit modules for them.
1750     ListenerRef.registerAll();
1751     return true;
1752 
1753   case ASTReader::ConfigurationMismatch:
1754     // Ignore unusable module files.
1755     getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1756         << FileName;
1757     // All modules provided by any files we tried and failed to load are now
1758     // unavailable; includes of those modules should now be handled textually.
1759     ListenerRef.markAllUnavailable();
1760     return true;
1761 
1762   default:
1763     return false;
1764   }
1765 }
1766 
1767 namespace {
1768 enum ModuleSource {
1769   MS_ModuleNotFound,
1770   MS_ModuleCache,
1771   MS_PrebuiltModulePath,
1772   MS_ModuleBuildPragma
1773 };
1774 } // end namespace
1775 
1776 /// Select a source for loading the named module and compute the filename to
1777 /// load it from.
1778 static ModuleSource selectModuleSource(
1779     Module *M, StringRef ModuleName, std::string &ModuleFilename,
1780     const std::map<std::string, std::string, std::less<>> &BuiltModules,
1781     HeaderSearch &HS) {
1782   assert(ModuleFilename.empty() && "Already has a module source?");
1783 
1784   // Check to see if the module has been built as part of this compilation
1785   // via a module build pragma.
1786   auto BuiltModuleIt = BuiltModules.find(ModuleName);
1787   if (BuiltModuleIt != BuiltModules.end()) {
1788     ModuleFilename = BuiltModuleIt->second;
1789     return MS_ModuleBuildPragma;
1790   }
1791 
1792   // Try to load the module from the prebuilt module path.
1793   const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1794   if (!HSOpts.PrebuiltModuleFiles.empty() ||
1795       !HSOpts.PrebuiltModulePaths.empty()) {
1796     ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1797     if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1798       ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1799     if (!ModuleFilename.empty())
1800       return MS_PrebuiltModulePath;
1801   }
1802 
1803   // Try to load the module from the module cache.
1804   if (M) {
1805     ModuleFilename = HS.getCachedModuleFileName(M);
1806     return MS_ModuleCache;
1807   }
1808 
1809   return MS_ModuleNotFound;
1810 }
1811 
1812 ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1813     StringRef ModuleName, SourceLocation ImportLoc,
1814     SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
1815   // Search for a module with the given name.
1816   HeaderSearch &HS = PP->getHeaderSearchInfo();
1817   Module *M =
1818       HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1819 
1820   // Select the source and filename for loading the named module.
1821   std::string ModuleFilename;
1822   ModuleSource Source =
1823       selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1824   if (Source == MS_ModuleNotFound) {
1825     // We can't find a module, error out here.
1826     getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1827         << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1828     return nullptr;
1829   }
1830   if (ModuleFilename.empty()) {
1831     if (M && M->HasIncompatibleModuleFile) {
1832       // We tried and failed to load a module file for this module. Fall
1833       // back to textual inclusion for its headers.
1834       return ModuleLoadResult::ConfigMismatch;
1835     }
1836 
1837     getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1838         << ModuleName;
1839     return nullptr;
1840   }
1841 
1842   // Create an ASTReader on demand.
1843   if (!getASTReader())
1844     createASTReader();
1845 
1846   // Time how long it takes to load the module.
1847   llvm::Timer Timer;
1848   if (FrontendTimerGroup)
1849     Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
1850                *FrontendTimerGroup);
1851   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1852   llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1853 
1854   // Try to load the module file. If we are not trying to load from the
1855   // module cache, we don't know how to rebuild modules.
1856   unsigned ARRFlags = Source == MS_ModuleCache
1857                           ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
1858                                 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
1859                           : Source == MS_PrebuiltModulePath
1860                                 ? 0
1861                                 : ASTReader::ARR_ConfigurationMismatch;
1862   switch (getASTReader()->ReadAST(ModuleFilename,
1863                                   Source == MS_PrebuiltModulePath
1864                                       ? serialization::MK_PrebuiltModule
1865                                       : Source == MS_ModuleBuildPragma
1866                                             ? serialization::MK_ExplicitModule
1867                                             : serialization::MK_ImplicitModule,
1868                                   ImportLoc, ARRFlags)) {
1869   case ASTReader::Success: {
1870     if (M)
1871       return M;
1872     assert(Source != MS_ModuleCache &&
1873            "missing module, but file loaded from cache");
1874 
1875     // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1876     // until the first call to ReadAST.  Look it up now.
1877     M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1878 
1879     // Check whether M refers to the file in the prebuilt module path.
1880     if (M && M->getASTFile())
1881       if (auto ModuleFile = FileMgr->getFile(ModuleFilename))
1882         if (*ModuleFile == M->getASTFile())
1883           return M;
1884 
1885     getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1886         << ModuleName;
1887     return ModuleLoadResult();
1888   }
1889 
1890   case ASTReader::OutOfDate:
1891   case ASTReader::Missing:
1892     // The most interesting case.
1893     break;
1894 
1895   case ASTReader::ConfigurationMismatch:
1896     if (Source == MS_PrebuiltModulePath)
1897       // FIXME: We shouldn't be setting HadFatalFailure below if we only
1898       // produce a warning here!
1899       getDiagnostics().Report(SourceLocation(),
1900                               diag::warn_module_config_mismatch)
1901           << ModuleFilename;
1902     // Fall through to error out.
1903     [[fallthrough]];
1904   case ASTReader::VersionMismatch:
1905   case ASTReader::HadErrors:
1906     ModuleLoader::HadFatalFailure = true;
1907     // FIXME: The ASTReader will already have complained, but can we shoehorn
1908     // that diagnostic information into a more useful form?
1909     return ModuleLoadResult();
1910 
1911   case ASTReader::Failure:
1912     ModuleLoader::HadFatalFailure = true;
1913     return ModuleLoadResult();
1914   }
1915 
1916   // ReadAST returned Missing or OutOfDate.
1917   if (Source != MS_ModuleCache) {
1918     // We don't know the desired configuration for this module and don't
1919     // necessarily even have a module map. Since ReadAST already produces
1920     // diagnostics for these two cases, we simply error out here.
1921     return ModuleLoadResult();
1922   }
1923 
1924   // The module file is missing or out-of-date. Build it.
1925   assert(M && "missing module, but trying to compile for cache");
1926 
1927   // Check whether there is a cycle in the module graph.
1928   ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1929   ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1930   for (; Pos != PosEnd; ++Pos) {
1931     if (Pos->first == ModuleName)
1932       break;
1933   }
1934 
1935   if (Pos != PosEnd) {
1936     SmallString<256> CyclePath;
1937     for (; Pos != PosEnd; ++Pos) {
1938       CyclePath += Pos->first;
1939       CyclePath += " -> ";
1940     }
1941     CyclePath += ModuleName;
1942 
1943     getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1944         << ModuleName << CyclePath;
1945     return nullptr;
1946   }
1947 
1948   // Check whether we have already attempted to build this module (but
1949   // failed).
1950   if (getPreprocessorOpts().FailedModules &&
1951       getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1952     getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1953         << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1954     return nullptr;
1955   }
1956 
1957   // Try to compile and then read the AST.
1958   if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
1959                                ModuleFilename)) {
1960     assert(getDiagnostics().hasErrorOccurred() &&
1961            "undiagnosed error in compileModuleAndReadAST");
1962     if (getPreprocessorOpts().FailedModules)
1963       getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1964     return nullptr;
1965   }
1966 
1967   // Okay, we've rebuilt and now loaded the module.
1968   return M;
1969 }
1970 
1971 ModuleLoadResult
1972 CompilerInstance::loadModule(SourceLocation ImportLoc,
1973                              ModuleIdPath Path,
1974                              Module::NameVisibilityKind Visibility,
1975                              bool IsInclusionDirective) {
1976   // Determine what file we're searching from.
1977   StringRef ModuleName = Path[0].first->getName();
1978   SourceLocation ModuleNameLoc = Path[0].second;
1979 
1980   // If we've already handled this import, just return the cached result.
1981   // This one-element cache is important to eliminate redundant diagnostics
1982   // when both the preprocessor and parser see the same import declaration.
1983   if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1984     // Make the named module visible.
1985     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1986       TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
1987                                       ImportLoc);
1988     return LastModuleImportResult;
1989   }
1990 
1991   // If we don't already have information on this module, load the module now.
1992   Module *Module = nullptr;
1993   ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1994   if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) {
1995     // Use the cached result, which may be nullptr.
1996     Module = *MaybeModule;
1997   } else if (ModuleName == getLangOpts().CurrentModule) {
1998     // This is the module we're building.
1999     Module = PP->getHeaderSearchInfo().lookupModule(
2000         ModuleName, ImportLoc, /*AllowSearch*/ true,
2001         /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
2002 
2003     MM.cacheModuleLoad(*Path[0].first, Module);
2004   } else {
2005     ModuleLoadResult Result = findOrCompileModuleAndReadAST(
2006         ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
2007     if (!Result.isNormal())
2008       return Result;
2009     if (!Result)
2010       DisableGeneratingGlobalModuleIndex = true;
2011     Module = Result;
2012     MM.cacheModuleLoad(*Path[0].first, Module);
2013   }
2014 
2015   // If we never found the module, fail.  Otherwise, verify the module and link
2016   // it up.
2017   if (!Module)
2018     return ModuleLoadResult();
2019 
2020   // Verify that the rest of the module path actually corresponds to
2021   // a submodule.
2022   bool MapPrivateSubModToTopLevel = false;
2023   for (unsigned I = 1, N = Path.size(); I != N; ++I) {
2024     StringRef Name = Path[I].first->getName();
2025     clang::Module *Sub = Module->findSubmodule(Name);
2026 
2027     // If the user is requesting Foo.Private and it doesn't exist, try to
2028     // match Foo_Private and emit a warning asking for the user to write
2029     // @import Foo_Private instead. FIXME: remove this when existing clients
2030     // migrate off of Foo.Private syntax.
2031     if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
2032       SmallString<128> PrivateModule(Module->Name);
2033       PrivateModule.append("_Private");
2034 
2035       SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
2036       auto &II = PP->getIdentifierTable().get(
2037           PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
2038       PrivPath.push_back(std::make_pair(&II, Path[0].second));
2039 
2040       std::string FileName;
2041       // If there is a modulemap module or prebuilt module, load it.
2042       if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
2043                                                  !IsInclusionDirective) ||
2044           selectModuleSource(nullptr, PrivateModule, FileName, BuiltModules,
2045                              PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2046         Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
2047       if (Sub) {
2048         MapPrivateSubModToTopLevel = true;
2049         PP->markClangModuleAsAffecting(Module);
2050         if (!getDiagnostics().isIgnored(
2051                 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2052           getDiagnostics().Report(Path[I].second,
2053                                   diag::warn_no_priv_submodule_use_toplevel)
2054               << Path[I].first << Module->getFullModuleName() << PrivateModule
2055               << SourceRange(Path[0].second, Path[I].second)
2056               << FixItHint::CreateReplacement(SourceRange(Path[0].second),
2057                                               PrivateModule);
2058           getDiagnostics().Report(Sub->DefinitionLoc,
2059                                   diag::note_private_top_level_defined);
2060         }
2061       }
2062     }
2063 
2064     if (!Sub) {
2065       // Attempt to perform typo correction to find a module name that works.
2066       SmallVector<StringRef, 2> Best;
2067       unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2068 
2069       for (class Module *SubModule : Module->submodules()) {
2070         unsigned ED =
2071             Name.edit_distance(SubModule->Name,
2072                                /*AllowReplacements=*/true, BestEditDistance);
2073         if (ED <= BestEditDistance) {
2074           if (ED < BestEditDistance) {
2075             Best.clear();
2076             BestEditDistance = ED;
2077           }
2078 
2079           Best.push_back(SubModule->Name);
2080         }
2081       }
2082 
2083       // If there was a clear winner, user it.
2084       if (Best.size() == 1) {
2085         getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest)
2086             << Path[I].first << Module->getFullModuleName() << Best[0]
2087             << SourceRange(Path[0].second, Path[I - 1].second)
2088             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
2089                                             Best[0]);
2090 
2091         Sub = Module->findSubmodule(Best[0]);
2092       }
2093     }
2094 
2095     if (!Sub) {
2096       // No submodule by this name. Complain, and don't look for further
2097       // submodules.
2098       getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
2099           << Path[I].first << Module->getFullModuleName()
2100           << SourceRange(Path[0].second, Path[I - 1].second);
2101       break;
2102     }
2103 
2104     Module = Sub;
2105   }
2106 
2107   // Make the named module visible, if it's not already part of the module
2108   // we are parsing.
2109   if (ModuleName != getLangOpts().CurrentModule) {
2110     if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2111       // We have an umbrella header or directory that doesn't actually include
2112       // all of the headers within the directory it covers. Complain about
2113       // this missing submodule and recover by forgetting that we ever saw
2114       // this submodule.
2115       // FIXME: Should we detect this at module load time? It seems fairly
2116       // expensive (and rare).
2117       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2118         << Module->getFullModuleName()
2119         << SourceRange(Path.front().second, Path.back().second);
2120 
2121       return ModuleLoadResult(Module, ModuleLoadResult::MissingExpected);
2122     }
2123 
2124     // Check whether this module is available.
2125     if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
2126                                              getDiagnostics(), Module)) {
2127       getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2128         << SourceRange(Path.front().second, Path.back().second);
2129       LastModuleImportLoc = ImportLoc;
2130       LastModuleImportResult = ModuleLoadResult();
2131       return ModuleLoadResult();
2132     }
2133 
2134     TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2135   }
2136 
2137   // Check for any configuration macros that have changed.
2138   clang::Module *TopModule = Module->getTopLevelModule();
2139   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
2140     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
2141                      Module, ImportLoc);
2142   }
2143 
2144   // Resolve any remaining module using export_as for this one.
2145   getPreprocessor()
2146       .getHeaderSearchInfo()
2147       .getModuleMap()
2148       .resolveLinkAsDependencies(TopModule);
2149 
2150   LastModuleImportLoc = ImportLoc;
2151   LastModuleImportResult = ModuleLoadResult(Module);
2152   return LastModuleImportResult;
2153 }
2154 
2155 void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
2156                                               StringRef ModuleName,
2157                                               StringRef Source) {
2158   // Avoid creating filenames with special characters.
2159   SmallString<128> CleanModuleName(ModuleName);
2160   for (auto &C : CleanModuleName)
2161     if (!isAlphanumeric(C))
2162       C = '_';
2163 
2164   // FIXME: Using a randomized filename here means that our intermediate .pcm
2165   // output is nondeterministic (as .pcm files refer to each other by name).
2166   // Can this affect the output in any way?
2167   SmallString<128> ModuleFileName;
2168   if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2169           CleanModuleName, "pcm", ModuleFileName)) {
2170     getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2171         << ModuleFileName << EC.message();
2172     return;
2173   }
2174   std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2175 
2176   FrontendInputFile Input(
2177       ModuleMapFileName,
2178       InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
2179                 InputKind::ModuleMap, /*Preprocessed*/true));
2180 
2181   std::string NullTerminatedSource(Source.str());
2182 
2183   auto PreBuildStep = [&](CompilerInstance &Other) {
2184     // Create a virtual file containing our desired source.
2185     // FIXME: We shouldn't need to do this.
2186     const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
2187         ModuleMapFileName, NullTerminatedSource.size(), 0);
2188     Other.getSourceManager().overrideFileContents(
2189         ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2190 
2191     Other.BuiltModules = std::move(BuiltModules);
2192     Other.DeleteBuiltModules = false;
2193   };
2194 
2195   auto PostBuildStep = [this](CompilerInstance &Other) {
2196     BuiltModules = std::move(Other.BuiltModules);
2197   };
2198 
2199   // Build the module, inheriting any modules that we've built locally.
2200   if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
2201                         ModuleFileName, PreBuildStep, PostBuildStep)) {
2202     BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str());
2203     llvm::sys::RemoveFileOnSignal(ModuleFileName);
2204   }
2205 }
2206 
2207 void CompilerInstance::makeModuleVisible(Module *Mod,
2208                                          Module::NameVisibilityKind Visibility,
2209                                          SourceLocation ImportLoc) {
2210   if (!TheASTReader)
2211     createASTReader();
2212   if (!TheASTReader)
2213     return;
2214 
2215   TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2216 }
2217 
2218 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
2219     SourceLocation TriggerLoc) {
2220   if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2221     return nullptr;
2222   if (!TheASTReader)
2223     createASTReader();
2224   // Can't do anything if we don't have the module manager.
2225   if (!TheASTReader)
2226     return nullptr;
2227   // Get an existing global index.  This loads it if not already
2228   // loaded.
2229   TheASTReader->loadGlobalIndex();
2230   GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2231   // If the global index doesn't exist, create it.
2232   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2233       hasPreprocessor()) {
2234     llvm::sys::fs::create_directories(
2235       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2236     if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2237             getFileManager(), getPCHContainerReader(),
2238             getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2239       // FIXME this drops the error on the floor. This code is only used for
2240       // typo correction and drops more than just this one source of errors
2241       // (such as the directory creation failure above). It should handle the
2242       // error.
2243       consumeError(std::move(Err));
2244       return nullptr;
2245     }
2246     TheASTReader->resetForReload();
2247     TheASTReader->loadGlobalIndex();
2248     GlobalIndex = TheASTReader->getGlobalIndex();
2249   }
2250   // For finding modules needing to be imported for fixit messages,
2251   // we need to make the global index cover all modules, so we do that here.
2252   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2253     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2254     bool RecreateIndex = false;
2255     for (ModuleMap::module_iterator I = MMap.module_begin(),
2256         E = MMap.module_end(); I != E; ++I) {
2257       Module *TheModule = I->second;
2258       const FileEntry *Entry = TheModule->getASTFile();
2259       if (!Entry) {
2260         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2261         Path.push_back(std::make_pair(
2262             getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
2263         std::reverse(Path.begin(), Path.end());
2264         // Load a module as hidden.  This also adds it to the global index.
2265         loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2266         RecreateIndex = true;
2267       }
2268     }
2269     if (RecreateIndex) {
2270       if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2271               getFileManager(), getPCHContainerReader(),
2272               getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2273         // FIXME As above, this drops the error on the floor.
2274         consumeError(std::move(Err));
2275         return nullptr;
2276       }
2277       TheASTReader->resetForReload();
2278       TheASTReader->loadGlobalIndex();
2279       GlobalIndex = TheASTReader->getGlobalIndex();
2280     }
2281     HaveFullGlobalModuleIndex = true;
2282   }
2283   return GlobalIndex;
2284 }
2285 
2286 // Check global module index for missing imports.
2287 bool
2288 CompilerInstance::lookupMissingImports(StringRef Name,
2289                                        SourceLocation TriggerLoc) {
2290   // Look for the symbol in non-imported modules, but only if an error
2291   // actually occurred.
2292   if (!buildingModule()) {
2293     // Load global module index, or retrieve a previously loaded one.
2294     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
2295       TriggerLoc);
2296 
2297     // Only if we have a global index.
2298     if (GlobalIndex) {
2299       GlobalModuleIndex::HitSet FoundModules;
2300 
2301       // Find the modules that reference the identifier.
2302       // Note that this only finds top-level modules.
2303       // We'll let diagnoseTypo find the actual declaration module.
2304       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2305         return true;
2306     }
2307   }
2308 
2309   return false;
2310 }
2311 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2312 
2313 void CompilerInstance::setExternalSemaSource(
2314     IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
2315   ExternalSemaSrc = std::move(ESS);
2316 }
2317