xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision ad7aaa475e5e632242b07380ec47d2f35d077209)
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 (!OF.TempFilename.empty()) {
652       if (EraseFiles) {
653         llvm::sys::fs::remove(OF.TempFilename);
654       } else {
655         SmallString<128> NewOutFile(OF.Filename);
656 
657         // If '-working-directory' was passed, the output filename should be
658         // relative to that.
659         FileMgr->FixupRelativePath(NewOutFile);
660         if (std::error_code ec =
661                 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
662           getDiagnostics().Report(diag::err_unable_to_rename_temp)
663             << OF.TempFilename << OF.Filename << ec.message();
664 
665           llvm::sys::fs::remove(OF.TempFilename);
666         }
667       }
668     } else if (!OF.Filename.empty() && EraseFiles)
669       llvm::sys::fs::remove(OF.Filename);
670   }
671   OutputFiles.clear();
672   if (DeleteBuiltModules) {
673     for (auto &Module : BuiltModules)
674       llvm::sys::fs::remove(Module.second);
675     BuiltModules.clear();
676   }
677 }
678 
679 std::unique_ptr<raw_pwrite_stream>
680 CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
681                                           StringRef Extension,
682                                           bool RemoveFileOnSignal,
683                                           bool CreateMissingDirectories) {
684   StringRef OutputPath = getFrontendOpts().OutputFile;
685   Optional<SmallString<128>> PathStorage;
686   if (OutputPath.empty()) {
687     if (InFile == "-" || Extension.empty()) {
688       OutputPath = "-";
689     } else {
690       PathStorage.emplace(InFile);
691       llvm::sys::path::replace_extension(*PathStorage, Extension);
692       OutputPath = *PathStorage;
693     }
694   }
695 
696   // Force a temporary file if RemoveFileOnSignal was disabled.
697   return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
698                           getFrontendOpts().UseTemporary || !RemoveFileOnSignal,
699                           CreateMissingDirectories);
700 }
701 
702 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
703   return std::make_unique<llvm::raw_null_ostream>();
704 }
705 
706 std::unique_ptr<raw_pwrite_stream>
707 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
708                                    bool RemoveFileOnSignal, bool UseTemporary,
709                                    bool CreateMissingDirectories) {
710   Expected<std::unique_ptr<raw_pwrite_stream>> OS =
711       createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
712                            CreateMissingDirectories);
713   if (OS)
714     return std::move(*OS);
715   getDiagnostics().Report(diag::err_fe_unable_to_open_output)
716       << OutputPath << errorToErrorCode(OS.takeError()).message();
717   return nullptr;
718 }
719 
720 Expected<std::unique_ptr<llvm::raw_pwrite_stream>>
721 CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
722                                        bool RemoveFileOnSignal,
723                                        bool UseTemporary,
724                                        bool CreateMissingDirectories) {
725   assert((!CreateMissingDirectories || UseTemporary) &&
726          "CreateMissingDirectories is only allowed when using temporary files");
727 
728   std::unique_ptr<llvm::raw_fd_ostream> OS;
729   Optional<StringRef> OSFile;
730 
731   if (UseTemporary) {
732     if (OutputPath == "-")
733       UseTemporary = false;
734     else {
735       llvm::sys::fs::file_status Status;
736       llvm::sys::fs::status(OutputPath, Status);
737       if (llvm::sys::fs::exists(Status)) {
738         // Fail early if we can't write to the final destination.
739         if (!llvm::sys::fs::can_write(OutputPath))
740           return llvm::errorCodeToError(
741               make_error_code(llvm::errc::operation_not_permitted));
742 
743         // Don't use a temporary if the output is a special file. This handles
744         // things like '-o /dev/null'
745         if (!llvm::sys::fs::is_regular_file(Status))
746           UseTemporary = false;
747       }
748     }
749   }
750 
751   std::string TempFile;
752   if (UseTemporary) {
753     // Create a temporary file.
754     // Insert -%%%%%%%% before the extension (if any), and because some tools
755     // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
756     // artifacts, also append .tmp.
757     StringRef OutputExtension = llvm::sys::path::extension(OutputPath);
758     SmallString<128> TempPath =
759         StringRef(OutputPath).drop_back(OutputExtension.size());
760     TempPath += "-%%%%%%%%";
761     TempPath += OutputExtension;
762     TempPath += ".tmp";
763     int fd;
764     std::error_code EC =
765         llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
766 
767     if (CreateMissingDirectories &&
768         EC == llvm::errc::no_such_file_or_directory) {
769       StringRef Parent = llvm::sys::path::parent_path(OutputPath);
770       EC = llvm::sys::fs::create_directories(Parent);
771       if (!EC) {
772         EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
773       }
774     }
775 
776     if (!EC) {
777       OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
778       OSFile = TempFile = std::string(TempPath.str());
779     }
780     // If we failed to create the temporary, fallback to writing to the file
781     // directly. This handles the corner case where we cannot write to the
782     // directory, but can write to the file.
783   }
784 
785   if (!OS) {
786     OSFile = OutputPath;
787     std::error_code EC;
788     OS.reset(new llvm::raw_fd_ostream(
789         *OSFile, EC,
790         (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text)));
791     if (EC)
792       return llvm::errorCodeToError(EC);
793   }
794 
795   // Make sure the out stream file gets removed if we crash.
796   if (RemoveFileOnSignal)
797     llvm::sys::RemoveFileOnSignal(*OSFile);
798 
799   // Add the output file -- but don't try to remove "-", since this means we are
800   // using stdin.
801   OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(),
802                            std::move(TempFile));
803 
804   if (!Binary || OS->supportsSeeking())
805     return std::move(OS);
806 
807   return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS));
808 }
809 
810 // Initialization Utilities
811 
812 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
813   return InitializeSourceManager(Input, getDiagnostics(), getFileManager(),
814                                  getSourceManager());
815 }
816 
817 // static
818 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
819                                                DiagnosticsEngine &Diags,
820                                                FileManager &FileMgr,
821                                                SourceManager &SourceMgr) {
822   SrcMgr::CharacteristicKind Kind =
823       Input.getKind().getFormat() == InputKind::ModuleMap
824           ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
825                              : SrcMgr::C_User_ModuleMap
826           : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
827 
828   if (Input.isBuffer()) {
829     SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
830     assert(SourceMgr.getMainFileID().isValid() &&
831            "Couldn't establish MainFileID!");
832     return true;
833   }
834 
835   StringRef InputFile = Input.getFile();
836 
837   // Figure out where to get and map in the main file.
838   auto FileOrErr = InputFile == "-"
839                        ? FileMgr.getSTDIN()
840                        : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
841   if (!FileOrErr) {
842     // FIXME: include the error in the diagnostic even when it's not stdin.
843     auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
844     if (InputFile != "-")
845       Diags.Report(diag::err_fe_error_reading) << InputFile;
846     else
847       Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
848     return false;
849   }
850 
851   SourceMgr.setMainFileID(
852       SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
853 
854   assert(SourceMgr.getMainFileID().isValid() &&
855          "Couldn't establish MainFileID!");
856   return true;
857 }
858 
859 // High-Level Operations
860 
861 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
862   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
863   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
864   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
865 
866   // Mark this point as the bottom of the stack if we don't have somewhere
867   // better. We generally expect frontend actions to be invoked with (nearly)
868   // DesiredStackSpace available.
869   noteBottomOfStack();
870 
871   raw_ostream &OS = getVerboseOutputStream();
872 
873   if (!Act.PrepareToExecute(*this))
874     return false;
875 
876   // Create the target instance.
877   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
878                                          getInvocation().TargetOpts));
879   if (!hasTarget())
880     return false;
881 
882   // Create TargetInfo for the other side of CUDA/OpenMP/SYCL compilation.
883   if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
884        getLangOpts().SYCLIsDevice) &&
885       !getFrontendOpts().AuxTriple.empty()) {
886     auto TO = std::make_shared<TargetOptions>();
887     TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
888     if (getFrontendOpts().AuxTargetCPU)
889       TO->CPU = getFrontendOpts().AuxTargetCPU.getValue();
890     if (getFrontendOpts().AuxTargetFeatures)
891       TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.getValue();
892     TO->HostTriple = getTarget().getTriple().str();
893     setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
894   }
895 
896   if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
897     if (getLangOpts().getFPRoundingMode() !=
898         llvm::RoundingMode::NearestTiesToEven) {
899       getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
900       getLangOpts().setFPRoundingMode(llvm::RoundingMode::NearestTiesToEven);
901     }
902     if (getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore) {
903       getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
904       getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
905     }
906     // FIXME: can we disable FEnvAccess?
907   }
908 
909   // Inform the target of the language options.
910   //
911   // FIXME: We shouldn't need to do this, the target should be immutable once
912   // created. This complexity should be lifted elsewhere.
913   getTarget().adjust(getLangOpts());
914 
915   // Adjust target options based on codegen options.
916   getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
917 
918   if (auto *Aux = getAuxTarget())
919     getTarget().setAuxTarget(Aux);
920 
921   // rewriter project will change target built-in bool type from its default.
922   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
923     getTarget().noSignedCharForObjCBool();
924 
925   // Validate/process some options.
926   if (getHeaderSearchOpts().Verbose)
927     OS << "clang -cc1 version " CLANG_VERSION_STRING
928        << " based upon " << BACKEND_PACKAGE_STRING
929        << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
930 
931   if (getCodeGenOpts().TimePasses)
932     createFrontendTimer();
933 
934   if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
935     llvm::EnableStatistics(false);
936 
937   for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
938     // Reset the ID tables if we are reusing the SourceManager and parsing
939     // regular files.
940     if (hasSourceManager() && !Act.isModelParsingAction())
941       getSourceManager().clearIDTables();
942 
943     if (Act.BeginSourceFile(*this, FIF)) {
944       if (llvm::Error Err = Act.Execute()) {
945         consumeError(std::move(Err)); // FIXME this drops errors on the floor.
946       }
947       Act.EndSourceFile();
948     }
949   }
950 
951   // Notify the diagnostic client that all files were processed.
952   getDiagnostics().getClient()->finish();
953 
954   if (getDiagnosticOpts().ShowCarets) {
955     // We can have multiple diagnostics sharing one diagnostic client.
956     // Get the total number of warnings/errors from the client.
957     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
958     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
959 
960     if (NumWarnings)
961       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
962     if (NumWarnings && NumErrors)
963       OS << " and ";
964     if (NumErrors)
965       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
966     if (NumWarnings || NumErrors) {
967       OS << " generated";
968       if (getLangOpts().CUDA) {
969         if (!getLangOpts().CUDAIsDevice) {
970           OS << " when compiling for host";
971         } else {
972           OS << " when compiling for " << getTargetOpts().CPU;
973         }
974       }
975       OS << ".\n";
976     }
977   }
978 
979   if (getFrontendOpts().ShowStats) {
980     if (hasFileManager()) {
981       getFileManager().PrintStats();
982       OS << '\n';
983     }
984     llvm::PrintStatistics(OS);
985   }
986   StringRef StatsFile = getFrontendOpts().StatsFile;
987   if (!StatsFile.empty()) {
988     std::error_code EC;
989     auto StatS = std::make_unique<llvm::raw_fd_ostream>(
990         StatsFile, EC, llvm::sys::fs::OF_Text);
991     if (EC) {
992       getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
993           << StatsFile << EC.message();
994     } else {
995       llvm::PrintStatisticsJSON(*StatS);
996     }
997   }
998 
999   return !getDiagnostics().getClient()->getNumErrors();
1000 }
1001 
1002 /// Determine the appropriate source input kind based on language
1003 /// options.
1004 static Language getLanguageFromOptions(const LangOptions &LangOpts) {
1005   if (LangOpts.OpenCL)
1006     return Language::OpenCL;
1007   if (LangOpts.CUDA)
1008     return Language::CUDA;
1009   if (LangOpts.ObjC)
1010     return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1011   return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1012 }
1013 
1014 /// Compile a module file for the given module, using the options
1015 /// provided by the importing compiler instance. Returns true if the module
1016 /// was built without errors.
1017 static bool
1018 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1019                   StringRef ModuleName, FrontendInputFile Input,
1020                   StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1021                   llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
1022                       [](CompilerInstance &) {},
1023                   llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1024                       [](CompilerInstance &) {}) {
1025   llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1026 
1027   // Construct a compiler invocation for creating this module.
1028   auto Invocation =
1029       std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
1030 
1031   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1032 
1033   // For any options that aren't intended to affect how a module is built,
1034   // reset them to their default values.
1035   Invocation->getLangOpts()->resetNonModularOptions();
1036   PPOpts.resetNonModularOptions();
1037 
1038   // Remove any macro definitions that are explicitly ignored by the module.
1039   // They aren't supposed to affect how the module is built anyway.
1040   HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1041   PPOpts.Macros.erase(
1042       std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
1043                      [&HSOpts](const std::pair<std::string, bool> &def) {
1044         StringRef MacroDef = def.first;
1045         return HSOpts.ModulesIgnoreMacros.count(
1046                    llvm::CachedHashString(MacroDef.split('=').first)) > 0;
1047       }),
1048       PPOpts.Macros.end());
1049 
1050   // If the original compiler invocation had -fmodule-name, pass it through.
1051   Invocation->getLangOpts()->ModuleName =
1052       ImportingInstance.getInvocation().getLangOpts()->ModuleName;
1053 
1054   // Note the name of the module we're building.
1055   Invocation->getLangOpts()->CurrentModule = std::string(ModuleName);
1056 
1057   // Make sure that the failed-module structure has been allocated in
1058   // the importing instance, and propagate the pointer to the newly-created
1059   // instance.
1060   PreprocessorOptions &ImportingPPOpts
1061     = ImportingInstance.getInvocation().getPreprocessorOpts();
1062   if (!ImportingPPOpts.FailedModules)
1063     ImportingPPOpts.FailedModules =
1064         std::make_shared<PreprocessorOptions::FailedModulesSet>();
1065   PPOpts.FailedModules = ImportingPPOpts.FailedModules;
1066 
1067   // If there is a module map file, build the module using the module map.
1068   // Set up the inputs/outputs so that we build the module from its umbrella
1069   // header.
1070   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1071   FrontendOpts.OutputFile = ModuleFileName.str();
1072   FrontendOpts.DisableFree = false;
1073   FrontendOpts.GenerateGlobalModuleIndex = false;
1074   FrontendOpts.BuildingImplicitModule = true;
1075   FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1076   // Force implicitly-built modules to hash the content of the module file.
1077   HSOpts.ModulesHashContent = true;
1078   FrontendOpts.Inputs = {Input};
1079 
1080   // Don't free the remapped file buffers; they are owned by our caller.
1081   PPOpts.RetainRemappedFileBuffers = true;
1082 
1083   Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
1084   assert(ImportingInstance.getInvocation().getModuleHash() ==
1085          Invocation->getModuleHash() && "Module hash mismatch!");
1086 
1087   // Construct a compiler instance that will be used to actually create the
1088   // module.  Since we're sharing an in-memory module cache,
1089   // CompilerInstance::CompilerInstance is responsible for finalizing the
1090   // buffers to prevent use-after-frees.
1091   CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
1092                             &ImportingInstance.getModuleCache());
1093   auto &Inv = *Invocation;
1094   Instance.setInvocation(std::move(Invocation));
1095 
1096   Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
1097                                    ImportingInstance.getDiagnosticClient()),
1098                              /*ShouldOwnClient=*/true);
1099 
1100   // Note that this module is part of the module build stack, so that we
1101   // can detect cycles in the module graph.
1102   Instance.setFileManager(&ImportingInstance.getFileManager());
1103   Instance.createSourceManager(Instance.getFileManager());
1104   SourceManager &SourceMgr = Instance.getSourceManager();
1105   SourceMgr.setModuleBuildStack(
1106     ImportingInstance.getSourceManager().getModuleBuildStack());
1107   SourceMgr.pushModuleBuildStack(ModuleName,
1108     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
1109 
1110   // If we're collecting module dependencies, we need to share a collector
1111   // between all of the module CompilerInstances. Other than that, we don't
1112   // want to produce any dependency output from the module build.
1113   Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
1114   Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1115 
1116   ImportingInstance.getDiagnostics().Report(ImportLoc,
1117                                             diag::remark_module_build)
1118     << ModuleName << ModuleFileName;
1119 
1120   PreBuildStep(Instance);
1121 
1122   // Execute the action to actually build the module in-place. Use a separate
1123   // thread so that we get a stack large enough.
1124   llvm::CrashRecoveryContext CRC;
1125   CRC.RunSafelyOnThread(
1126       [&]() {
1127         GenerateModuleFromModuleMapAction Action;
1128         Instance.ExecuteAction(Action);
1129       },
1130       DesiredStackSize);
1131 
1132   PostBuildStep(Instance);
1133 
1134   ImportingInstance.getDiagnostics().Report(ImportLoc,
1135                                             diag::remark_module_build_done)
1136     << ModuleName;
1137 
1138   // Delete any remaining temporary files related to Instance, in case the
1139   // module generation thread crashed.
1140   Instance.clearOutputFiles(/*EraseFiles=*/true);
1141 
1142   return !Instance.getDiagnostics().hasErrorOccurred();
1143 }
1144 
1145 static const FileEntry *getPublicModuleMap(const FileEntry *File,
1146                                            FileManager &FileMgr) {
1147   StringRef Filename = llvm::sys::path::filename(File->getName());
1148   SmallString<128> PublicFilename(File->getDir()->getName());
1149   if (Filename == "module_private.map")
1150     llvm::sys::path::append(PublicFilename, "module.map");
1151   else if (Filename == "module.private.modulemap")
1152     llvm::sys::path::append(PublicFilename, "module.modulemap");
1153   else
1154     return nullptr;
1155   if (auto FE = FileMgr.getFile(PublicFilename))
1156     return *FE;
1157   return nullptr;
1158 }
1159 
1160 /// Compile a module file for the given module in a separate compiler instance,
1161 /// using the options provided by the importing compiler instance. Returns true
1162 /// if the module was built without errors.
1163 static bool compileModule(CompilerInstance &ImportingInstance,
1164                           SourceLocation ImportLoc, Module *Module,
1165                           StringRef ModuleFileName) {
1166   InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
1167                InputKind::ModuleMap);
1168 
1169   // Get or create the module map that we'll use to build this module.
1170   ModuleMap &ModMap
1171     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1172   bool Result;
1173   if (const FileEntry *ModuleMapFile =
1174           ModMap.getContainingModuleMapFile(Module)) {
1175     // Canonicalize compilation to start with the public module map. This is
1176     // vital for submodules declarations in the private module maps to be
1177     // correctly parsed when depending on a top level module in the public one.
1178     if (const FileEntry *PublicMMFile = getPublicModuleMap(
1179             ModuleMapFile, ImportingInstance.getFileManager()))
1180       ModuleMapFile = PublicMMFile;
1181 
1182     // Use the module map where this module resides.
1183     Result = compileModuleImpl(
1184         ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1185         FrontendInputFile(ModuleMapFile->getName(), IK, +Module->IsSystem),
1186         ModMap.getModuleMapFileForUniquing(Module)->getName(),
1187         ModuleFileName);
1188   } else {
1189     // FIXME: We only need to fake up an input file here as a way of
1190     // transporting the module's directory to the module map parser. We should
1191     // be able to do that more directly, and parse from a memory buffer without
1192     // inventing this file.
1193     SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1194     llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1195 
1196     std::string InferredModuleMapContent;
1197     llvm::raw_string_ostream OS(InferredModuleMapContent);
1198     Module->print(OS);
1199     OS.flush();
1200 
1201     Result = compileModuleImpl(
1202         ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1203         FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1204         ModMap.getModuleMapFileForUniquing(Module)->getName(),
1205         ModuleFileName,
1206         [&](CompilerInstance &Instance) {
1207       std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1208           llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1209       ModuleMapFile = Instance.getFileManager().getVirtualFile(
1210           FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1211       Instance.getSourceManager().overrideFileContents(
1212           ModuleMapFile, std::move(ModuleMapBuffer));
1213     });
1214   }
1215 
1216   // We've rebuilt a module. If we're allowed to generate or update the global
1217   // module index, record that fact in the importing compiler instance.
1218   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1219     ImportingInstance.setBuildGlobalModuleIndex(true);
1220   }
1221 
1222   return Result;
1223 }
1224 
1225 /// Compile a module in a separate compiler instance and read the AST,
1226 /// returning true if the module compiles without errors.
1227 ///
1228 /// Uses a lock file manager and exponential backoff to reduce the chances that
1229 /// multiple instances will compete to create the same module.  On timeout,
1230 /// deletes the lock file in order to avoid deadlock from crashing processes or
1231 /// bugs in the lock file manager.
1232 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1233                                     SourceLocation ImportLoc,
1234                                     SourceLocation ModuleNameLoc,
1235                                     Module *Module, StringRef ModuleFileName) {
1236   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1237 
1238   auto diagnoseBuildFailure = [&] {
1239     Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1240         << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1241   };
1242 
1243   // FIXME: have LockFileManager return an error_code so that we can
1244   // avoid the mkdir when the directory already exists.
1245   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1246   llvm::sys::fs::create_directories(Dir);
1247 
1248   while (1) {
1249     unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1250     llvm::LockFileManager Locked(ModuleFileName);
1251     switch (Locked) {
1252     case llvm::LockFileManager::LFS_Error:
1253       // ModuleCache takes care of correctness and locks are only necessary for
1254       // performance. Fallback to building the module in case of any lock
1255       // related errors.
1256       Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1257           << Module->Name << Locked.getErrorMessage();
1258       // Clear out any potential leftover.
1259       Locked.unsafeRemoveLockFile();
1260       LLVM_FALLTHROUGH;
1261     case llvm::LockFileManager::LFS_Owned:
1262       // We're responsible for building the module ourselves.
1263       if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
1264                          ModuleFileName)) {
1265         diagnoseBuildFailure();
1266         return false;
1267       }
1268       break;
1269 
1270     case llvm::LockFileManager::LFS_Shared:
1271       // Someone else is responsible for building the module. Wait for them to
1272       // finish.
1273       switch (Locked.waitForUnlock()) {
1274       case llvm::LockFileManager::Res_Success:
1275         ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1276         break;
1277       case llvm::LockFileManager::Res_OwnerDied:
1278         continue; // try again to get the lock.
1279       case llvm::LockFileManager::Res_Timeout:
1280         // Since ModuleCache takes care of correctness, we try waiting for
1281         // another process to complete the build so clang does not do it done
1282         // twice. If case of timeout, build it ourselves.
1283         Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1284             << Module->Name;
1285         // Clear the lock file so that future invocations can make progress.
1286         Locked.unsafeRemoveLockFile();
1287         continue;
1288       }
1289       break;
1290     }
1291 
1292     // Try to read the module file, now that we've compiled it.
1293     ASTReader::ASTReadResult ReadResult =
1294         ImportingInstance.getASTReader()->ReadAST(
1295             ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1296             ModuleLoadCapabilities);
1297 
1298     if (ReadResult == ASTReader::OutOfDate &&
1299         Locked == llvm::LockFileManager::LFS_Shared) {
1300       // The module may be out of date in the presence of file system races,
1301       // or if one of its imports depends on header search paths that are not
1302       // consistent with this ImportingInstance.  Try again...
1303       continue;
1304     } else if (ReadResult == ASTReader::Missing) {
1305       diagnoseBuildFailure();
1306     } else if (ReadResult != ASTReader::Success &&
1307                !Diags.hasErrorOccurred()) {
1308       // The ASTReader didn't diagnose the error, so conservatively report it.
1309       diagnoseBuildFailure();
1310     }
1311     return ReadResult == ASTReader::Success;
1312   }
1313 }
1314 
1315 /// Diagnose differences between the current definition of the given
1316 /// configuration macro and the definition provided on the command line.
1317 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1318                              Module *Mod, SourceLocation ImportLoc) {
1319   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1320   SourceManager &SourceMgr = PP.getSourceManager();
1321 
1322   // If this identifier has never had a macro definition, then it could
1323   // not have changed.
1324   if (!Id->hadMacroDefinition())
1325     return;
1326   auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1327 
1328   // Find the macro definition from the command line.
1329   MacroInfo *CmdLineDefinition = nullptr;
1330   for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1331     // We only care about the predefines buffer.
1332     FileID FID = SourceMgr.getFileID(MD->getLocation());
1333     if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1334       continue;
1335     if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1336       CmdLineDefinition = DMD->getMacroInfo();
1337     break;
1338   }
1339 
1340   auto *CurrentDefinition = PP.getMacroInfo(Id);
1341   if (CurrentDefinition == CmdLineDefinition) {
1342     // Macro matches. Nothing to do.
1343   } else if (!CurrentDefinition) {
1344     // This macro was defined on the command line, then #undef'd later.
1345     // Complain.
1346     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1347       << true << ConfigMacro << Mod->getFullModuleName();
1348     auto LatestDef = LatestLocalMD->getDefinition();
1349     assert(LatestDef.isUndefined() &&
1350            "predefined macro went away with no #undef?");
1351     PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1352       << true;
1353     return;
1354   } else if (!CmdLineDefinition) {
1355     // There was no definition for this macro in the predefines buffer,
1356     // but there was a local definition. Complain.
1357     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1358       << false << ConfigMacro << Mod->getFullModuleName();
1359     PP.Diag(CurrentDefinition->getDefinitionLoc(),
1360             diag::note_module_def_undef_here)
1361       << false;
1362   } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1363                                                /*Syntactically=*/true)) {
1364     // The macro definitions differ.
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   }
1371 }
1372 
1373 /// Write a new timestamp file with the given path.
1374 static void writeTimestampFile(StringRef TimestampFile) {
1375   std::error_code EC;
1376   llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
1377 }
1378 
1379 /// Prune the module cache of modules that haven't been accessed in
1380 /// a long time.
1381 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1382   llvm::sys::fs::file_status StatBuf;
1383   llvm::SmallString<128> TimestampFile;
1384   TimestampFile = HSOpts.ModuleCachePath;
1385   assert(!TimestampFile.empty());
1386   llvm::sys::path::append(TimestampFile, "modules.timestamp");
1387 
1388   // Try to stat() the timestamp file.
1389   if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
1390     // If the timestamp file wasn't there, create one now.
1391     if (EC == std::errc::no_such_file_or_directory) {
1392       writeTimestampFile(TimestampFile);
1393     }
1394     return;
1395   }
1396 
1397   // Check whether the time stamp is older than our pruning interval.
1398   // If not, do nothing.
1399   time_t TimeStampModTime =
1400       llvm::sys::toTimeT(StatBuf.getLastModificationTime());
1401   time_t CurrentTime = time(nullptr);
1402   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1403     return;
1404 
1405   // Write a new timestamp file so that nobody else attempts to prune.
1406   // There is a benign race condition here, if two Clang instances happen to
1407   // notice at the same time that the timestamp is out-of-date.
1408   writeTimestampFile(TimestampFile);
1409 
1410   // Walk the entire module cache, looking for unused module files and module
1411   // indices.
1412   std::error_code EC;
1413   SmallString<128> ModuleCachePathNative;
1414   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1415   for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1416        Dir != DirEnd && !EC; Dir.increment(EC)) {
1417     // If we don't have a directory, there's nothing to look into.
1418     if (!llvm::sys::fs::is_directory(Dir->path()))
1419       continue;
1420 
1421     // Walk all of the files within this directory.
1422     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1423          File != FileEnd && !EC; File.increment(EC)) {
1424       // We only care about module and global module index files.
1425       StringRef Extension = llvm::sys::path::extension(File->path());
1426       if (Extension != ".pcm" && Extension != ".timestamp" &&
1427           llvm::sys::path::filename(File->path()) != "modules.idx")
1428         continue;
1429 
1430       // Look at this file. If we can't stat it, there's nothing interesting
1431       // there.
1432       if (llvm::sys::fs::status(File->path(), StatBuf))
1433         continue;
1434 
1435       // If the file has been used recently enough, leave it there.
1436       time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
1437       if (CurrentTime - FileAccessTime <=
1438               time_t(HSOpts.ModuleCachePruneAfter)) {
1439         continue;
1440       }
1441 
1442       // Remove the file.
1443       llvm::sys::fs::remove(File->path());
1444 
1445       // Remove the timestamp file.
1446       std::string TimpestampFilename = File->path() + ".timestamp";
1447       llvm::sys::fs::remove(TimpestampFilename);
1448     }
1449 
1450     // If we removed all of the files in the directory, remove the directory
1451     // itself.
1452     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1453             llvm::sys::fs::directory_iterator() && !EC)
1454       llvm::sys::fs::remove(Dir->path());
1455   }
1456 }
1457 
1458 void CompilerInstance::createASTReader() {
1459   if (TheASTReader)
1460     return;
1461 
1462   if (!hasASTContext())
1463     createASTContext();
1464 
1465   // If we're implicitly building modules but not currently recursively
1466   // building a module, check whether we need to prune the module cache.
1467   if (getSourceManager().getModuleBuildStack().empty() &&
1468       !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1469       getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1470       getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1471     pruneModuleCache(getHeaderSearchOpts());
1472   }
1473 
1474   HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1475   std::string Sysroot = HSOpts.Sysroot;
1476   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1477   const FrontendOptions &FEOpts = getFrontendOpts();
1478   std::unique_ptr<llvm::Timer> ReadTimer;
1479 
1480   if (FrontendTimerGroup)
1481     ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1482                                                 "Reading modules",
1483                                                 *FrontendTimerGroup);
1484   TheASTReader = new ASTReader(
1485       getPreprocessor(), getModuleCache(), &getASTContext(),
1486       getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
1487       Sysroot.empty() ? "" : Sysroot.c_str(),
1488       PPOpts.DisablePCHOrModuleValidation,
1489       /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1490       /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders,
1491       HSOpts.ValidateASTInputFilesContent,
1492       getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1493   if (hasASTConsumer()) {
1494     TheASTReader->setDeserializationListener(
1495         getASTConsumer().GetASTDeserializationListener());
1496     getASTContext().setASTMutationListener(
1497       getASTConsumer().GetASTMutationListener());
1498   }
1499   getASTContext().setExternalSource(TheASTReader);
1500   if (hasSema())
1501     TheASTReader->InitializeSema(getSema());
1502   if (hasASTConsumer())
1503     TheASTReader->StartTranslationUnit(&getASTConsumer());
1504 
1505   for (auto &Listener : DependencyCollectors)
1506     Listener->attachToASTReader(*TheASTReader);
1507 }
1508 
1509 bool CompilerInstance::loadModuleFile(StringRef FileName) {
1510   llvm::Timer Timer;
1511   if (FrontendTimerGroup)
1512     Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1513                *FrontendTimerGroup);
1514   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1515 
1516   // Helper to recursively read the module names for all modules we're adding.
1517   // We mark these as known and redirect any attempt to load that module to
1518   // the files we were handed.
1519   struct ReadModuleNames : ASTReaderListener {
1520     CompilerInstance &CI;
1521     llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
1522 
1523     ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
1524 
1525     void ReadModuleName(StringRef ModuleName) override {
1526       LoadedModules.push_back(
1527           CI.getPreprocessor().getIdentifierInfo(ModuleName));
1528     }
1529 
1530     void registerAll() {
1531       ModuleMap &MM = CI.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1532       for (auto *II : LoadedModules)
1533         MM.cacheModuleLoad(*II, MM.findModule(II->getName()));
1534       LoadedModules.clear();
1535     }
1536 
1537     void markAllUnavailable() {
1538       for (auto *II : LoadedModules) {
1539         if (Module *M = CI.getPreprocessor()
1540                             .getHeaderSearchInfo()
1541                             .getModuleMap()
1542                             .findModule(II->getName())) {
1543           M->HasIncompatibleModuleFile = true;
1544 
1545           // Mark module as available if the only reason it was unavailable
1546           // was missing headers.
1547           SmallVector<Module *, 2> Stack;
1548           Stack.push_back(M);
1549           while (!Stack.empty()) {
1550             Module *Current = Stack.pop_back_val();
1551             if (Current->IsUnimportable) continue;
1552             Current->IsAvailable = true;
1553             Stack.insert(Stack.end(),
1554                          Current->submodule_begin(), Current->submodule_end());
1555           }
1556         }
1557       }
1558       LoadedModules.clear();
1559     }
1560   };
1561 
1562   // If we don't already have an ASTReader, create one now.
1563   if (!TheASTReader)
1564     createASTReader();
1565 
1566   // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1567   // ASTReader to diagnose it, since it can produce better errors that we can.
1568   bool ConfigMismatchIsRecoverable =
1569       getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
1570                                           SourceLocation())
1571         <= DiagnosticsEngine::Warning;
1572 
1573   auto Listener = std::make_unique<ReadModuleNames>(*this);
1574   auto &ListenerRef = *Listener;
1575   ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1576                                                    std::move(Listener));
1577 
1578   // Try to load the module file.
1579   switch (TheASTReader->ReadAST(
1580       FileName, serialization::MK_ExplicitModule, SourceLocation(),
1581       ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) {
1582   case ASTReader::Success:
1583     // We successfully loaded the module file; remember the set of provided
1584     // modules so that we don't try to load implicit modules for them.
1585     ListenerRef.registerAll();
1586     return true;
1587 
1588   case ASTReader::ConfigurationMismatch:
1589     // Ignore unusable module files.
1590     getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1591         << FileName;
1592     // All modules provided by any files we tried and failed to load are now
1593     // unavailable; includes of those modules should now be handled textually.
1594     ListenerRef.markAllUnavailable();
1595     return true;
1596 
1597   default:
1598     return false;
1599   }
1600 }
1601 
1602 namespace {
1603 enum ModuleSource {
1604   MS_ModuleNotFound,
1605   MS_ModuleCache,
1606   MS_PrebuiltModulePath,
1607   MS_ModuleBuildPragma
1608 };
1609 } // end namespace
1610 
1611 /// Select a source for loading the named module and compute the filename to
1612 /// load it from.
1613 static ModuleSource selectModuleSource(
1614     Module *M, StringRef ModuleName, std::string &ModuleFilename,
1615     const std::map<std::string, std::string, std::less<>> &BuiltModules,
1616     HeaderSearch &HS) {
1617   assert(ModuleFilename.empty() && "Already has a module source?");
1618 
1619   // Check to see if the module has been built as part of this compilation
1620   // via a module build pragma.
1621   auto BuiltModuleIt = BuiltModules.find(ModuleName);
1622   if (BuiltModuleIt != BuiltModules.end()) {
1623     ModuleFilename = BuiltModuleIt->second;
1624     return MS_ModuleBuildPragma;
1625   }
1626 
1627   // Try to load the module from the prebuilt module path.
1628   const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1629   if (!HSOpts.PrebuiltModuleFiles.empty() ||
1630       !HSOpts.PrebuiltModulePaths.empty()) {
1631     ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1632     if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1633       ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1634     if (!ModuleFilename.empty())
1635       return MS_PrebuiltModulePath;
1636   }
1637 
1638   // Try to load the module from the module cache.
1639   if (M) {
1640     ModuleFilename = HS.getCachedModuleFileName(M);
1641     return MS_ModuleCache;
1642   }
1643 
1644   return MS_ModuleNotFound;
1645 }
1646 
1647 ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1648     StringRef ModuleName, SourceLocation ImportLoc,
1649     SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
1650   // Search for a module with the given name.
1651   HeaderSearch &HS = PP->getHeaderSearchInfo();
1652   Module *M = HS.lookupModule(ModuleName, true, !IsInclusionDirective);
1653 
1654   // Select the source and filename for loading the named module.
1655   std::string ModuleFilename;
1656   ModuleSource Source =
1657       selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1658   if (Source == MS_ModuleNotFound) {
1659     // We can't find a module, error out here.
1660     getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1661         << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1662     ModuleBuildFailed = true;
1663     // FIXME: Why is this not cached?
1664     return ModuleLoadResult::OtherUncachedFailure;
1665   }
1666   if (ModuleFilename.empty()) {
1667     if (M && M->HasIncompatibleModuleFile) {
1668       // We tried and failed to load a module file for this module. Fall
1669       // back to textual inclusion for its headers.
1670       return ModuleLoadResult::ConfigMismatch;
1671     }
1672 
1673     getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1674         << ModuleName;
1675     ModuleBuildFailed = true;
1676     // FIXME: Why is this not cached?
1677     return ModuleLoadResult::OtherUncachedFailure;
1678   }
1679 
1680   // Create an ASTReader on demand.
1681   if (!getASTReader())
1682     createASTReader();
1683 
1684   // Time how long it takes to load the module.
1685   llvm::Timer Timer;
1686   if (FrontendTimerGroup)
1687     Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
1688                *FrontendTimerGroup);
1689   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1690   llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1691 
1692   // Try to load the module file. If we are not trying to load from the
1693   // module cache, we don't know how to rebuild modules.
1694   unsigned ARRFlags = Source == MS_ModuleCache
1695                           ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing
1696                           : Source == MS_PrebuiltModulePath
1697                                 ? 0
1698                                 : ASTReader::ARR_ConfigurationMismatch;
1699   switch (getASTReader()->ReadAST(ModuleFilename,
1700                                   Source == MS_PrebuiltModulePath
1701                                       ? serialization::MK_PrebuiltModule
1702                                       : Source == MS_ModuleBuildPragma
1703                                             ? serialization::MK_ExplicitModule
1704                                             : serialization::MK_ImplicitModule,
1705                                   ImportLoc, ARRFlags)) {
1706   case ASTReader::Success: {
1707     if (M)
1708       return M;
1709     assert(Source != MS_ModuleCache &&
1710            "missing module, but file loaded from cache");
1711 
1712     // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1713     // until the first call to ReadAST.  Look it up now.
1714     M = HS.lookupModule(ModuleName, true, !IsInclusionDirective);
1715 
1716     // Check whether M refers to the file in the prebuilt module path.
1717     if (M && M->getASTFile())
1718       if (auto ModuleFile = FileMgr->getFile(ModuleFilename))
1719         if (*ModuleFile == M->getASTFile())
1720           return M;
1721 
1722     ModuleBuildFailed = true;
1723     getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1724         << ModuleName;
1725     return ModuleLoadResult();
1726   }
1727 
1728   case ASTReader::OutOfDate:
1729   case ASTReader::Missing:
1730     // The most interesting case.
1731     break;
1732 
1733   case ASTReader::ConfigurationMismatch:
1734     if (Source == MS_PrebuiltModulePath)
1735       // FIXME: We shouldn't be setting HadFatalFailure below if we only
1736       // produce a warning here!
1737       getDiagnostics().Report(SourceLocation(),
1738                               diag::warn_module_config_mismatch)
1739           << ModuleFilename;
1740     // Fall through to error out.
1741     LLVM_FALLTHROUGH;
1742   case ASTReader::VersionMismatch:
1743   case ASTReader::HadErrors:
1744     // FIXME: Should this set ModuleBuildFailed = true?
1745     ModuleLoader::HadFatalFailure = true;
1746     // FIXME: The ASTReader will already have complained, but can we shoehorn
1747     // that diagnostic information into a more useful form?
1748     return ModuleLoadResult();
1749 
1750   case ASTReader::Failure:
1751     // FIXME: Should this set ModuleBuildFailed = true?
1752     ModuleLoader::HadFatalFailure = true;
1753     return ModuleLoadResult();
1754   }
1755 
1756   // ReadAST returned Missing or OutOfDate.
1757   if (Source != MS_ModuleCache) {
1758     // We don't know the desired configuration for this module and don't
1759     // necessarily even have a module map. Since ReadAST already produces
1760     // diagnostics for these two cases, we simply error out here.
1761     ModuleBuildFailed = true;
1762     return ModuleLoadResult();
1763   }
1764 
1765   // The module file is missing or out-of-date. Build it.
1766   assert(M && "missing module, but trying to compile for cache");
1767 
1768   // Check whether there is a cycle in the module graph.
1769   ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1770   ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1771   for (; Pos != PosEnd; ++Pos) {
1772     if (Pos->first == ModuleName)
1773       break;
1774   }
1775 
1776   if (Pos != PosEnd) {
1777     SmallString<256> CyclePath;
1778     for (; Pos != PosEnd; ++Pos) {
1779       CyclePath += Pos->first;
1780       CyclePath += " -> ";
1781     }
1782     CyclePath += ModuleName;
1783 
1784     getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1785         << ModuleName << CyclePath;
1786     // FIXME: Should this set ModuleBuildFailed = true?
1787     // FIXME: Why is this not cached?
1788     return ModuleLoadResult::OtherUncachedFailure;
1789   }
1790 
1791   // Check whether we have already attempted to build this module (but
1792   // failed).
1793   if (getPreprocessorOpts().FailedModules &&
1794       getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1795     getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1796         << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1797     ModuleBuildFailed = true;
1798     // FIXME: Why is this not cached?
1799     return ModuleLoadResult::OtherUncachedFailure;
1800   }
1801 
1802   // Try to compile and then read the AST.
1803   if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
1804                                ModuleFilename)) {
1805     assert(getDiagnostics().hasErrorOccurred() &&
1806            "undiagnosed error in compileModuleAndReadAST");
1807     if (getPreprocessorOpts().FailedModules)
1808       getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1809     ModuleBuildFailed = true;
1810     // FIXME: Why is this not cached?
1811     return ModuleLoadResult::OtherUncachedFailure;
1812   }
1813 
1814   // Okay, we've rebuilt and now loaded the module.
1815   return M;
1816 }
1817 
1818 ModuleLoadResult
1819 CompilerInstance::loadModule(SourceLocation ImportLoc,
1820                              ModuleIdPath Path,
1821                              Module::NameVisibilityKind Visibility,
1822                              bool IsInclusionDirective) {
1823   // Determine what file we're searching from.
1824   StringRef ModuleName = Path[0].first->getName();
1825   SourceLocation ModuleNameLoc = Path[0].second;
1826 
1827   // If we've already handled this import, just return the cached result.
1828   // This one-element cache is important to eliminate redundant diagnostics
1829   // when both the preprocessor and parser see the same import declaration.
1830   if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1831     // Make the named module visible.
1832     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1833       TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
1834                                       ImportLoc);
1835     return LastModuleImportResult;
1836   }
1837 
1838   // If we don't already have information on this module, load the module now.
1839   Module *Module = nullptr;
1840   ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1841   if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) {
1842     // Use the cached result, which may be nullptr.
1843     Module = *MaybeModule;
1844   } else if (ModuleName == getLangOpts().CurrentModule) {
1845     // This is the module we're building.
1846     Module = PP->getHeaderSearchInfo().lookupModule(
1847         ModuleName, /*AllowSearch*/ true,
1848         /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
1849     /// FIXME: perhaps we should (a) look for a module using the module name
1850     //  to file map (PrebuiltModuleFiles) and (b) diagnose if still not found?
1851     //if (Module == nullptr) {
1852     //  getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1853     //    << ModuleName;
1854     //  ModuleBuildFailed = true;
1855     //  return ModuleLoadResult();
1856     //}
1857     MM.cacheModuleLoad(*Path[0].first, Module);
1858   } else {
1859     ModuleLoadResult Result = findOrCompileModuleAndReadAST(
1860         ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
1861     // FIXME: Can we pull 'ModuleBuildFailed = true' out of the return
1862     // sequences for findOrCompileModuleAndReadAST and do it here (as long as
1863     // the result is not a config mismatch)?  See FIXMEs there.
1864     if (!Result.isNormal())
1865       return Result;
1866     Module = Result;
1867     MM.cacheModuleLoad(*Path[0].first, Module);
1868     if (!Module)
1869       return Module;
1870   }
1871 
1872   // If we never found the module, fail.  Otherwise, verify the module and link
1873   // it up.
1874   if (!Module)
1875     return ModuleLoadResult();
1876 
1877   // Verify that the rest of the module path actually corresponds to
1878   // a submodule.
1879   bool MapPrivateSubModToTopLevel = false;
1880   if (Path.size() > 1) {
1881     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1882       StringRef Name = Path[I].first->getName();
1883       clang::Module *Sub = Module->findSubmodule(Name);
1884 
1885       // If the user is requesting Foo.Private and it doesn't exist, try to
1886       // match Foo_Private and emit a warning asking for the user to write
1887       // @import Foo_Private instead. FIXME: remove this when existing clients
1888       // migrate off of Foo.Private syntax.
1889       if (!Sub && PP->getLangOpts().ImplicitModules && Name == "Private" &&
1890           Module == Module->getTopLevelModule()) {
1891         SmallString<128> PrivateModule(Module->Name);
1892         PrivateModule.append("_Private");
1893 
1894         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
1895         auto &II = PP->getIdentifierTable().get(
1896             PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
1897         PrivPath.push_back(std::make_pair(&II, Path[0].second));
1898 
1899         if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, true,
1900                                                    !IsInclusionDirective))
1901           Sub =
1902               loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
1903         if (Sub) {
1904           MapPrivateSubModToTopLevel = true;
1905           if (!getDiagnostics().isIgnored(
1906                   diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
1907             getDiagnostics().Report(Path[I].second,
1908                                     diag::warn_no_priv_submodule_use_toplevel)
1909                 << Path[I].first << Module->getFullModuleName() << PrivateModule
1910                 << SourceRange(Path[0].second, Path[I].second)
1911                 << FixItHint::CreateReplacement(SourceRange(Path[0].second),
1912                                                 PrivateModule);
1913             getDiagnostics().Report(Sub->DefinitionLoc,
1914                                     diag::note_private_top_level_defined);
1915           }
1916         }
1917       }
1918 
1919       if (!Sub) {
1920         // Attempt to perform typo correction to find a module name that works.
1921         SmallVector<StringRef, 2> Best;
1922         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1923 
1924         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1925                                             JEnd = Module->submodule_end();
1926              J != JEnd; ++J) {
1927           unsigned ED = Name.edit_distance((*J)->Name,
1928                                            /*AllowReplacements=*/true,
1929                                            BestEditDistance);
1930           if (ED <= BestEditDistance) {
1931             if (ED < BestEditDistance) {
1932               Best.clear();
1933               BestEditDistance = ED;
1934             }
1935 
1936             Best.push_back((*J)->Name);
1937           }
1938         }
1939 
1940         // If there was a clear winner, user it.
1941         if (Best.size() == 1) {
1942           getDiagnostics().Report(Path[I].second,
1943                                   diag::err_no_submodule_suggest)
1944             << Path[I].first << Module->getFullModuleName() << Best[0]
1945             << SourceRange(Path[0].second, Path[I-1].second)
1946             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1947                                             Best[0]);
1948 
1949           Sub = Module->findSubmodule(Best[0]);
1950         }
1951       }
1952 
1953       if (!Sub) {
1954         // No submodule by this name. Complain, and don't look for further
1955         // submodules.
1956         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1957           << Path[I].first << Module->getFullModuleName()
1958           << SourceRange(Path[0].second, Path[I-1].second);
1959         break;
1960       }
1961 
1962       Module = Sub;
1963     }
1964   }
1965 
1966   // Make the named module visible, if it's not already part of the module
1967   // we are parsing.
1968   if (ModuleName != getLangOpts().CurrentModule) {
1969     if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
1970       // We have an umbrella header or directory that doesn't actually include
1971       // all of the headers within the directory it covers. Complain about
1972       // this missing submodule and recover by forgetting that we ever saw
1973       // this submodule.
1974       // FIXME: Should we detect this at module load time? It seems fairly
1975       // expensive (and rare).
1976       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1977         << Module->getFullModuleName()
1978         << SourceRange(Path.front().second, Path.back().second);
1979 
1980       return ModuleLoadResult::MissingExpected;
1981     }
1982 
1983     // Check whether this module is available.
1984     if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
1985                                              getDiagnostics(), Module)) {
1986       getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
1987         << SourceRange(Path.front().second, Path.back().second);
1988       LastModuleImportLoc = ImportLoc;
1989       LastModuleImportResult = ModuleLoadResult();
1990       return ModuleLoadResult();
1991     }
1992 
1993     TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
1994   }
1995 
1996   // Check for any configuration macros that have changed.
1997   clang::Module *TopModule = Module->getTopLevelModule();
1998   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1999     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
2000                      Module, ImportLoc);
2001   }
2002 
2003   // Resolve any remaining module using export_as for this one.
2004   getPreprocessor()
2005       .getHeaderSearchInfo()
2006       .getModuleMap()
2007       .resolveLinkAsDependencies(TopModule);
2008 
2009   LastModuleImportLoc = ImportLoc;
2010   LastModuleImportResult = ModuleLoadResult(Module);
2011   return LastModuleImportResult;
2012 }
2013 
2014 void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
2015                                               StringRef ModuleName,
2016                                               StringRef Source) {
2017   // Avoid creating filenames with special characters.
2018   SmallString<128> CleanModuleName(ModuleName);
2019   for (auto &C : CleanModuleName)
2020     if (!isAlphanumeric(C))
2021       C = '_';
2022 
2023   // FIXME: Using a randomized filename here means that our intermediate .pcm
2024   // output is nondeterministic (as .pcm files refer to each other by name).
2025   // Can this affect the output in any way?
2026   SmallString<128> ModuleFileName;
2027   if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2028           CleanModuleName, "pcm", ModuleFileName)) {
2029     getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2030         << ModuleFileName << EC.message();
2031     return;
2032   }
2033   std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2034 
2035   FrontendInputFile Input(
2036       ModuleMapFileName,
2037       InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
2038                 InputKind::ModuleMap, /*Preprocessed*/true));
2039 
2040   std::string NullTerminatedSource(Source.str());
2041 
2042   auto PreBuildStep = [&](CompilerInstance &Other) {
2043     // Create a virtual file containing our desired source.
2044     // FIXME: We shouldn't need to do this.
2045     const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
2046         ModuleMapFileName, NullTerminatedSource.size(), 0);
2047     Other.getSourceManager().overrideFileContents(
2048         ModuleMapFile,
2049         llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
2050 
2051     Other.BuiltModules = std::move(BuiltModules);
2052     Other.DeleteBuiltModules = false;
2053   };
2054 
2055   auto PostBuildStep = [this](CompilerInstance &Other) {
2056     BuiltModules = std::move(Other.BuiltModules);
2057   };
2058 
2059   // Build the module, inheriting any modules that we've built locally.
2060   if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
2061                         ModuleFileName, PreBuildStep, PostBuildStep)) {
2062     BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str());
2063     llvm::sys::RemoveFileOnSignal(ModuleFileName);
2064   }
2065 }
2066 
2067 void CompilerInstance::makeModuleVisible(Module *Mod,
2068                                          Module::NameVisibilityKind Visibility,
2069                                          SourceLocation ImportLoc) {
2070   if (!TheASTReader)
2071     createASTReader();
2072   if (!TheASTReader)
2073     return;
2074 
2075   TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2076 }
2077 
2078 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
2079     SourceLocation TriggerLoc) {
2080   if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2081     return nullptr;
2082   if (!TheASTReader)
2083     createASTReader();
2084   // Can't do anything if we don't have the module manager.
2085   if (!TheASTReader)
2086     return nullptr;
2087   // Get an existing global index.  This loads it if not already
2088   // loaded.
2089   TheASTReader->loadGlobalIndex();
2090   GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2091   // If the global index doesn't exist, create it.
2092   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2093       hasPreprocessor()) {
2094     llvm::sys::fs::create_directories(
2095       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2096     if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2097             getFileManager(), getPCHContainerReader(),
2098             getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2099       // FIXME this drops the error on the floor. This code is only used for
2100       // typo correction and drops more than just this one source of errors
2101       // (such as the directory creation failure above). It should handle the
2102       // error.
2103       consumeError(std::move(Err));
2104       return nullptr;
2105     }
2106     TheASTReader->resetForReload();
2107     TheASTReader->loadGlobalIndex();
2108     GlobalIndex = TheASTReader->getGlobalIndex();
2109   }
2110   // For finding modules needing to be imported for fixit messages,
2111   // we need to make the global index cover all modules, so we do that here.
2112   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2113     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2114     bool RecreateIndex = false;
2115     for (ModuleMap::module_iterator I = MMap.module_begin(),
2116         E = MMap.module_end(); I != E; ++I) {
2117       Module *TheModule = I->second;
2118       const FileEntry *Entry = TheModule->getASTFile();
2119       if (!Entry) {
2120         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2121         Path.push_back(std::make_pair(
2122             getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
2123         std::reverse(Path.begin(), Path.end());
2124         // Load a module as hidden.  This also adds it to the global index.
2125         loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2126         RecreateIndex = true;
2127       }
2128     }
2129     if (RecreateIndex) {
2130       if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2131               getFileManager(), getPCHContainerReader(),
2132               getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2133         // FIXME As above, this drops the error on the floor.
2134         consumeError(std::move(Err));
2135         return nullptr;
2136       }
2137       TheASTReader->resetForReload();
2138       TheASTReader->loadGlobalIndex();
2139       GlobalIndex = TheASTReader->getGlobalIndex();
2140     }
2141     HaveFullGlobalModuleIndex = true;
2142   }
2143   return GlobalIndex;
2144 }
2145 
2146 // Check global module index for missing imports.
2147 bool
2148 CompilerInstance::lookupMissingImports(StringRef Name,
2149                                        SourceLocation TriggerLoc) {
2150   // Look for the symbol in non-imported modules, but only if an error
2151   // actually occurred.
2152   if (!buildingModule()) {
2153     // Load global module index, or retrieve a previously loaded one.
2154     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
2155       TriggerLoc);
2156 
2157     // Only if we have a global index.
2158     if (GlobalIndex) {
2159       GlobalModuleIndex::HitSet FoundModules;
2160 
2161       // Find the modules that reference the identifier.
2162       // Note that this only finds top-level modules.
2163       // We'll let diagnoseTypo find the actual declaration module.
2164       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2165         return true;
2166     }
2167   }
2168 
2169   return false;
2170 }
2171 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2172 
2173 void CompilerInstance::setExternalSemaSource(
2174     IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
2175   ExternalSemaSrc = std::move(ESS);
2176 }
2177