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