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