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