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