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