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