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