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