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