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