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