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