xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision 4eca9b93720b8f5746159eed43a0b3c0bf496db0)
1 //===--- CompilerInstance.cpp ---------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Frontend/CompilerInstance.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Basic/Version.h"
19 #include "clang/Config/config.h"
20 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
21 #include "clang/Frontend/FrontendAction.h"
22 #include "clang/Frontend/FrontendActions.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "clang/Frontend/LogDiagnosticPrinter.h"
25 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
26 #include "clang/Frontend/TextDiagnosticPrinter.h"
27 #include "clang/Frontend/Utils.h"
28 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
29 #include "clang/Lex/HeaderSearch.h"
30 #include "clang/Lex/PTHManager.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CodeCompleteConsumer.h"
33 #include "clang/Sema/Sema.h"
34 #include "clang/Serialization/ASTReader.h"
35 #include "clang/Serialization/GlobalModuleIndex.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/CrashRecoveryContext.h"
38 #include "llvm/Support/Errc.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/LockFileManager.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Program.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <sys/stat.h>
49 #include <system_error>
50 #include <time.h>
51 
52 using namespace clang;
53 
54 CompilerInstance::CompilerInstance(bool BuildingModule)
55   : ModuleLoader(BuildingModule),
56     Invocation(new CompilerInvocation()), ModuleManager(nullptr),
57     BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false),
58     ModuleBuildFailed(false) {
59 }
60 
61 CompilerInstance::~CompilerInstance() {
62   assert(OutputFiles.empty() && "Still output files in flight?");
63 }
64 
65 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
66   Invocation = Value;
67 }
68 
69 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
70   return (BuildGlobalModuleIndex ||
71           (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
72            getFrontendOpts().GenerateGlobalModuleIndex)) &&
73          !ModuleBuildFailed;
74 }
75 
76 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
77   Diagnostics = Value;
78 }
79 
80 void CompilerInstance::setTarget(TargetInfo *Value) {
81   Target = Value;
82 }
83 
84 void CompilerInstance::setFileManager(FileManager *Value) {
85   FileMgr = Value;
86   if (Value)
87     VirtualFileSystem = Value->getVirtualFileSystem();
88   else
89     VirtualFileSystem.reset();
90 }
91 
92 void CompilerInstance::setSourceManager(SourceManager *Value) {
93   SourceMgr = Value;
94 }
95 
96 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
97 
98 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
99 
100 void CompilerInstance::setSema(Sema *S) {
101   TheSema.reset(S);
102 }
103 
104 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
105   Consumer = std::move(Value);
106 }
107 
108 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
109   CompletionConsumer.reset(Value);
110 }
111 
112 std::unique_ptr<Sema> CompilerInstance::takeSema() {
113   return std::move(TheSema);
114 }
115 
116 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
117   return ModuleManager;
118 }
119 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
120   ModuleManager = Reader;
121 }
122 
123 std::shared_ptr<ModuleDependencyCollector>
124 CompilerInstance::getModuleDepCollector() const {
125   return ModuleDepCollector;
126 }
127 
128 void CompilerInstance::setModuleDepCollector(
129     std::shared_ptr<ModuleDependencyCollector> Collector) {
130   ModuleDepCollector = Collector;
131 }
132 
133 // Diagnostics
134 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
135                                const CodeGenOptions *CodeGenOpts,
136                                DiagnosticsEngine &Diags) {
137   std::error_code EC;
138   std::unique_ptr<raw_ostream> StreamOwner;
139   raw_ostream *OS = &llvm::errs();
140   if (DiagOpts->DiagnosticLogFile != "-") {
141     // Create the output stream.
142     auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
143         DiagOpts->DiagnosticLogFile, EC,
144         llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
145     if (EC) {
146       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
147           << DiagOpts->DiagnosticLogFile << EC.message();
148     } else {
149       FileOS->SetUnbuffered();
150       FileOS->SetUseAtomicWrites(true);
151       OS = FileOS.get();
152       StreamOwner = std::move(FileOS);
153     }
154   }
155 
156   // Chain in the diagnostic client which will log the diagnostics.
157   auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
158                                                         std::move(StreamOwner));
159   if (CodeGenOpts)
160     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
161   assert(Diags.ownsClient());
162   Diags.setClient(
163       new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
164 }
165 
166 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
167                                        DiagnosticsEngine &Diags,
168                                        StringRef OutputFile) {
169   auto SerializedConsumer =
170       clang::serialized_diags::create(OutputFile, DiagOpts);
171 
172   if (Diags.ownsClient()) {
173     Diags.setClient(new ChainedDiagnosticConsumer(
174         Diags.takeClient(), std::move(SerializedConsumer)));
175   } else {
176     Diags.setClient(new ChainedDiagnosticConsumer(
177         Diags.getClient(), std::move(SerializedConsumer)));
178   }
179 }
180 
181 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
182                                          bool ShouldOwnClient) {
183   Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
184                                   ShouldOwnClient, &getCodeGenOpts());
185 }
186 
187 IntrusiveRefCntPtr<DiagnosticsEngine>
188 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
189                                     DiagnosticConsumer *Client,
190                                     bool ShouldOwnClient,
191                                     const CodeGenOptions *CodeGenOpts) {
192   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
193   IntrusiveRefCntPtr<DiagnosticsEngine>
194       Diags(new DiagnosticsEngine(DiagID, Opts));
195 
196   // Create the diagnostic client for reporting errors or for
197   // implementing -verify.
198   if (Client) {
199     Diags->setClient(Client, ShouldOwnClient);
200   } else
201     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
202 
203   // Chain in -verify checker, if requested.
204   if (Opts->VerifyDiagnostics)
205     Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
206 
207   // Chain in -diagnostic-log-file dumper, if requested.
208   if (!Opts->DiagnosticLogFile.empty())
209     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
210 
211   if (!Opts->DiagnosticSerializationFile.empty())
212     SetupSerializedDiagnostics(Opts, *Diags,
213                                Opts->DiagnosticSerializationFile);
214 
215   // Configure our handling of diagnostics.
216   ProcessWarningOptions(*Diags, *Opts);
217 
218   return Diags;
219 }
220 
221 // File Manager
222 
223 void CompilerInstance::createFileManager() {
224   if (!hasVirtualFileSystem()) {
225     // TODO: choose the virtual file system based on the CompilerInvocation.
226     setVirtualFileSystem(vfs::getRealFileSystem());
227   }
228   FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
229 }
230 
231 // Source Manager
232 
233 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
234   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
235 }
236 
237 // Initialize the remapping of files to alternative contents, e.g.,
238 // those specified through other files.
239 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
240                                     SourceManager &SourceMgr,
241                                     FileManager &FileMgr,
242                                     const PreprocessorOptions &InitOpts) {
243   // Remap files in the source manager (with buffers).
244   for (const auto &RB : InitOpts.RemappedFileBuffers) {
245     // Create the file entry for the file that we're mapping from.
246     const FileEntry *FromFile =
247         FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
248     if (!FromFile) {
249       Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
250       if (!InitOpts.RetainRemappedFileBuffers)
251         delete RB.second;
252       continue;
253     }
254 
255     // Override the contents of the "from" file with the contents of
256     // the "to" file.
257     SourceMgr.overrideFileContents(FromFile, RB.second,
258                                    InitOpts.RetainRemappedFileBuffers);
259   }
260 
261   // Remap files in the source manager (with other files).
262   for (const auto &RF : InitOpts.RemappedFiles) {
263     // Find the file that we're mapping to.
264     const FileEntry *ToFile = FileMgr.getFile(RF.second);
265     if (!ToFile) {
266       Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
267       continue;
268     }
269 
270     // Create the file entry for the file that we're mapping from.
271     const FileEntry *FromFile =
272         FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
273     if (!FromFile) {
274       Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
275       continue;
276     }
277 
278     // Override the contents of the "from" file with the contents of
279     // the "to" file.
280     SourceMgr.overrideFileContents(FromFile, ToFile);
281   }
282 
283   SourceMgr.setOverridenFilesKeepOriginalName(
284       InitOpts.RemappedFilesKeepOriginalName);
285 }
286 
287 // Preprocessor
288 
289 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
290   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
291 
292   // Create a PTH manager if we are using some form of a token cache.
293   PTHManager *PTHMgr = nullptr;
294   if (!PPOpts.TokenCache.empty())
295     PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
296 
297   // Create the Preprocessor.
298   HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
299                                               getSourceManager(),
300                                               getDiagnostics(),
301                                               getLangOpts(),
302                                               &getTarget());
303   PP = new Preprocessor(&getPreprocessorOpts(), getDiagnostics(), getLangOpts(),
304                         getSourceManager(), *HeaderInfo, *this, PTHMgr,
305                         /*OwnsHeaderSearch=*/true, TUKind);
306   PP->Initialize(getTarget());
307 
308   // Note that this is different then passing PTHMgr to Preprocessor's ctor.
309   // That argument is used as the IdentifierInfoLookup argument to
310   // IdentifierTable's ctor.
311   if (PTHMgr) {
312     PTHMgr->setPreprocessor(&*PP);
313     PP->setPTHManager(PTHMgr);
314   }
315 
316   if (PPOpts.DetailedRecord)
317     PP->createPreprocessingRecord();
318 
319   // Apply remappings to the source manager.
320   InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
321                           PP->getFileManager(), PPOpts);
322 
323   // Predefine macros and configure the preprocessor.
324   InitializePreprocessor(*PP, PPOpts, getFrontendOpts());
325 
326   // Initialize the header search object.
327   ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
328                            PP->getLangOpts(), PP->getTargetInfo().getTriple());
329 
330   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
331 
332   // Set up the module path, including the hash for the
333   // module-creation options.
334   SmallString<256> SpecificModuleCache(
335                            getHeaderSearchOpts().ModuleCachePath);
336   if (!getHeaderSearchOpts().DisableModuleHash)
337     llvm::sys::path::append(SpecificModuleCache,
338                             getInvocation().getModuleHash());
339   PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
340 
341   // Handle generating dependencies, if requested.
342   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
343   if (!DepOpts.OutputFile.empty())
344     TheDependencyFileGenerator.reset(
345         DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
346   if (!DepOpts.DOTOutputFile.empty())
347     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
348                              getHeaderSearchOpts().Sysroot);
349 
350   for (auto &Listener : DependencyCollectors)
351     Listener->attachToPreprocessor(*PP);
352 
353   // If we don't have a collector, but we are collecting module dependencies,
354   // then we're the top level compiler instance and need to create one.
355   if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty())
356     ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
357         DepOpts.ModuleDependencyOutputDir);
358 
359   // Handle generating header include information, if requested.
360   if (DepOpts.ShowHeaderIncludes)
361     AttachHeaderIncludeGen(*PP);
362   if (!DepOpts.HeaderIncludeOutputFile.empty()) {
363     StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
364     if (OutputPath == "-")
365       OutputPath = "";
366     AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
367                            /*ShowDepth=*/false);
368   }
369 
370   if (DepOpts.PrintShowIncludes) {
371     AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"",
372                            /*ShowDepth=*/true, /*MSStyle=*/true);
373   }
374 }
375 
376 // ASTContext
377 
378 void CompilerInstance::createASTContext() {
379   Preprocessor &PP = getPreprocessor();
380   Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
381                            PP.getIdentifierTable(), PP.getSelectorTable(),
382                            PP.getBuiltinInfo());
383   Context->InitBuiltinTypes(getTarget());
384 }
385 
386 // ExternalASTSource
387 
388 void CompilerInstance::createPCHExternalASTSource(
389     StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
390     void *DeserializationListener, bool OwnDeserializationListener) {
391   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
392   ModuleManager = createPCHExternalASTSource(
393       Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
394       AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
395       DeserializationListener, OwnDeserializationListener, Preamble,
396       getFrontendOpts().UseGlobalModuleIndex);
397 }
398 
399 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
400     StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
401     bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
402     void *DeserializationListener, bool OwnDeserializationListener,
403     bool Preamble, bool UseGlobalModuleIndex) {
404   HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
405 
406   IntrusiveRefCntPtr<ASTReader> Reader(
407       new ASTReader(PP, Context, Sysroot.empty() ? "" : Sysroot.c_str(),
408                     DisablePCHValidation, AllowPCHWithCompilerErrors,
409                     /*AllowConfigurationMismatch*/ false,
410                     HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex));
411 
412   // We need the external source to be set up before we read the AST, because
413   // eagerly-deserialized declarations may use it.
414   Context.setExternalSource(Reader.get());
415 
416   Reader->setDeserializationListener(
417       static_cast<ASTDeserializationListener *>(DeserializationListener),
418       /*TakeOwnership=*/OwnDeserializationListener);
419   switch (Reader->ReadAST(Path,
420                           Preamble ? serialization::MK_Preamble
421                                    : serialization::MK_PCH,
422                           SourceLocation(),
423                           ASTReader::ARR_None)) {
424   case ASTReader::Success:
425     // Set the predefines buffer as suggested by the PCH reader. Typically, the
426     // predefines buffer will be empty.
427     PP.setPredefines(Reader->getSuggestedPredefines());
428     return Reader;
429 
430   case ASTReader::Failure:
431     // Unrecoverable failure: don't even try to process the input file.
432     break;
433 
434   case ASTReader::Missing:
435   case ASTReader::OutOfDate:
436   case ASTReader::VersionMismatch:
437   case ASTReader::ConfigurationMismatch:
438   case ASTReader::HadErrors:
439     // No suitable PCH file could be found. Return an error.
440     break;
441   }
442 
443   Context.setExternalSource(nullptr);
444   return nullptr;
445 }
446 
447 // Code Completion
448 
449 static bool EnableCodeCompletion(Preprocessor &PP,
450                                  const std::string &Filename,
451                                  unsigned Line,
452                                  unsigned Column) {
453   // Tell the source manager to chop off the given file at a specific
454   // line and column.
455   const FileEntry *Entry = PP.getFileManager().getFile(Filename);
456   if (!Entry) {
457     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
458       << Filename;
459     return true;
460   }
461 
462   // Truncate the named file at the given line/column.
463   PP.SetCodeCompletionPoint(Entry, Line, Column);
464   return false;
465 }
466 
467 void CompilerInstance::createCodeCompletionConsumer() {
468   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
469   if (!CompletionConsumer) {
470     setCodeCompletionConsumer(
471       createCodeCompletionConsumer(getPreprocessor(),
472                                    Loc.FileName, Loc.Line, Loc.Column,
473                                    getFrontendOpts().CodeCompleteOpts,
474                                    llvm::outs()));
475     if (!CompletionConsumer)
476       return;
477   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
478                                   Loc.Line, Loc.Column)) {
479     setCodeCompletionConsumer(nullptr);
480     return;
481   }
482 
483   if (CompletionConsumer->isOutputBinary() &&
484       llvm::sys::ChangeStdoutToBinary()) {
485     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
486     setCodeCompletionConsumer(nullptr);
487   }
488 }
489 
490 void CompilerInstance::createFrontendTimer() {
491   FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
492 }
493 
494 CodeCompleteConsumer *
495 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
496                                                const std::string &Filename,
497                                                unsigned Line,
498                                                unsigned Column,
499                                                const CodeCompleteOptions &Opts,
500                                                raw_ostream &OS) {
501   if (EnableCodeCompletion(PP, Filename, Line, Column))
502     return nullptr;
503 
504   // Set up the creation routine for code-completion.
505   return new PrintingCodeCompleteConsumer(Opts, OS);
506 }
507 
508 void CompilerInstance::createSema(TranslationUnitKind TUKind,
509                                   CodeCompleteConsumer *CompletionConsumer) {
510   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
511                          TUKind, CompletionConsumer));
512 }
513 
514 // Output Files
515 
516 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
517   assert(OutFile.OS && "Attempt to add empty stream to output list!");
518   OutputFiles.push_back(OutFile);
519 }
520 
521 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
522   for (std::list<OutputFile>::iterator
523          it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
524     delete it->OS;
525     if (!it->TempFilename.empty()) {
526       if (EraseFiles) {
527         llvm::sys::fs::remove(it->TempFilename);
528       } else {
529         SmallString<128> NewOutFile(it->Filename);
530 
531         // If '-working-directory' was passed, the output filename should be
532         // relative to that.
533         FileMgr->FixupRelativePath(NewOutFile);
534         if (std::error_code ec =
535                 llvm::sys::fs::rename(it->TempFilename, NewOutFile.str())) {
536           getDiagnostics().Report(diag::err_unable_to_rename_temp)
537             << it->TempFilename << it->Filename << ec.message();
538 
539           llvm::sys::fs::remove(it->TempFilename);
540         }
541       }
542     } else if (!it->Filename.empty() && EraseFiles)
543       llvm::sys::fs::remove(it->Filename);
544 
545   }
546   OutputFiles.clear();
547 }
548 
549 llvm::raw_fd_ostream *
550 CompilerInstance::createDefaultOutputFile(bool Binary,
551                                           StringRef InFile,
552                                           StringRef Extension) {
553   return createOutputFile(getFrontendOpts().OutputFile, Binary,
554                           /*RemoveFileOnSignal=*/true, InFile, Extension,
555                           /*UseTemporary=*/true);
556 }
557 
558 llvm::raw_null_ostream *CompilerInstance::createNullOutputFile() {
559   llvm::raw_null_ostream *OS = new llvm::raw_null_ostream();
560   addOutputFile(OutputFile("", "", OS));
561   return OS;
562 }
563 
564 llvm::raw_fd_ostream *
565 CompilerInstance::createOutputFile(StringRef OutputPath,
566                                    bool Binary, bool RemoveFileOnSignal,
567                                    StringRef InFile,
568                                    StringRef Extension,
569                                    bool UseTemporary,
570                                    bool CreateMissingDirectories) {
571   std::string OutputPathName, TempPathName;
572   std::error_code EC;
573   llvm::raw_fd_ostream *OS = createOutputFile(
574       OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
575       UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
576   if (!OS) {
577     getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
578                                                                 << EC.message();
579     return nullptr;
580   }
581 
582   // Add the output file -- but don't try to remove "-", since this means we are
583   // using stdin.
584   addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
585                 TempPathName, OS));
586 
587   return OS;
588 }
589 
590 llvm::raw_fd_ostream *CompilerInstance::createOutputFile(
591     StringRef OutputPath, std::error_code &Error, bool Binary,
592     bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
593     bool UseTemporary, bool CreateMissingDirectories,
594     std::string *ResultPathName, std::string *TempPathName) {
595   assert((!CreateMissingDirectories || UseTemporary) &&
596          "CreateMissingDirectories is only allowed when using temporary files");
597 
598   std::string OutFile, TempFile;
599   if (!OutputPath.empty()) {
600     OutFile = OutputPath;
601   } else if (InFile == "-") {
602     OutFile = "-";
603   } else if (!Extension.empty()) {
604     SmallString<128> Path(InFile);
605     llvm::sys::path::replace_extension(Path, Extension);
606     OutFile = Path.str();
607   } else {
608     OutFile = "-";
609   }
610 
611   std::unique_ptr<llvm::raw_fd_ostream> OS;
612   std::string OSFile;
613 
614   if (UseTemporary) {
615     if (OutFile == "-")
616       UseTemporary = false;
617     else {
618       llvm::sys::fs::file_status Status;
619       llvm::sys::fs::status(OutputPath, Status);
620       if (llvm::sys::fs::exists(Status)) {
621         // Fail early if we can't write to the final destination.
622         if (!llvm::sys::fs::can_write(OutputPath))
623           return nullptr;
624 
625         // Don't use a temporary if the output is a special file. This handles
626         // things like '-o /dev/null'
627         if (!llvm::sys::fs::is_regular_file(Status))
628           UseTemporary = false;
629       }
630     }
631   }
632 
633   if (UseTemporary) {
634     // Create a temporary file.
635     SmallString<128> TempPath;
636     TempPath = OutFile;
637     TempPath += "-%%%%%%%%";
638     int fd;
639     std::error_code EC =
640         llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
641 
642     if (CreateMissingDirectories &&
643         EC == llvm::errc::no_such_file_or_directory) {
644       StringRef Parent = llvm::sys::path::parent_path(OutputPath);
645       EC = llvm::sys::fs::create_directories(Parent);
646       if (!EC) {
647         EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
648       }
649     }
650 
651     if (!EC) {
652       OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
653       OSFile = TempFile = TempPath.str();
654     }
655     // If we failed to create the temporary, fallback to writing to the file
656     // directly. This handles the corner case where we cannot write to the
657     // directory, but can write to the file.
658   }
659 
660   if (!OS) {
661     OSFile = OutFile;
662     OS.reset(new llvm::raw_fd_ostream(
663         OSFile, Error,
664         (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
665     if (Error)
666       return nullptr;
667   }
668 
669   // Make sure the out stream file gets removed if we crash.
670   if (RemoveFileOnSignal)
671     llvm::sys::RemoveFileOnSignal(OSFile);
672 
673   if (ResultPathName)
674     *ResultPathName = OutFile;
675   if (TempPathName)
676     *TempPathName = TempFile;
677 
678   return OS.release();
679 }
680 
681 // Initialization Utilities
682 
683 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
684   return InitializeSourceManager(Input, getDiagnostics(),
685                                  getFileManager(), getSourceManager(),
686                                  getFrontendOpts());
687 }
688 
689 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
690                                                DiagnosticsEngine &Diags,
691                                                FileManager &FileMgr,
692                                                SourceManager &SourceMgr,
693                                                const FrontendOptions &Opts) {
694   SrcMgr::CharacteristicKind
695     Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
696 
697   if (Input.isBuffer()) {
698     SourceMgr.setMainFileID(SourceMgr.createFileID(
699         std::unique_ptr<llvm::MemoryBuffer>(Input.getBuffer()), Kind));
700     assert(!SourceMgr.getMainFileID().isInvalid() &&
701            "Couldn't establish MainFileID!");
702     return true;
703   }
704 
705   StringRef InputFile = Input.getFile();
706 
707   // Figure out where to get and map in the main file.
708   if (InputFile != "-") {
709     const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
710     if (!File) {
711       Diags.Report(diag::err_fe_error_reading) << InputFile;
712       return false;
713     }
714 
715     // The natural SourceManager infrastructure can't currently handle named
716     // pipes, but we would at least like to accept them for the main
717     // file. Detect them here, read them with the volatile flag so FileMgr will
718     // pick up the correct size, and simply override their contents as we do for
719     // STDIN.
720     if (File->isNamedPipe()) {
721       auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
722       if (MB) {
723         // Create a new virtual file that will have the correct size.
724         File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
725         SourceMgr.overrideFileContents(File, std::move(*MB));
726       } else {
727         Diags.Report(diag::err_cannot_open_file) << InputFile
728                                                  << MB.getError().message();
729         return false;
730       }
731     }
732 
733     SourceMgr.setMainFileID(
734         SourceMgr.createFileID(File, SourceLocation(), Kind));
735   } else {
736     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
737         llvm::MemoryBuffer::getSTDIN();
738     if (std::error_code EC = SBOrErr.getError()) {
739       Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
740       return false;
741     }
742     std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
743 
744     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
745                                                    SB->getBufferSize(), 0);
746     SourceMgr.setMainFileID(
747         SourceMgr.createFileID(File, SourceLocation(), Kind));
748     SourceMgr.overrideFileContents(File, std::move(SB));
749   }
750 
751   assert(!SourceMgr.getMainFileID().isInvalid() &&
752          "Couldn't establish MainFileID!");
753   return true;
754 }
755 
756 // High-Level Operations
757 
758 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
759   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
760   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
761   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
762 
763   // FIXME: Take this as an argument, once all the APIs we used have moved to
764   // taking it as an input instead of hard-coding llvm::errs.
765   raw_ostream &OS = llvm::errs();
766 
767   // Create the target instance.
768   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
769                                          getInvocation().TargetOpts));
770   if (!hasTarget())
771     return false;
772 
773   // Inform the target of the language options.
774   //
775   // FIXME: We shouldn't need to do this, the target should be immutable once
776   // created. This complexity should be lifted elsewhere.
777   getTarget().adjust(getLangOpts());
778 
779   // rewriter project will change target built-in bool type from its default.
780   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
781     getTarget().noSignedCharForObjCBool();
782 
783   // Validate/process some options.
784   if (getHeaderSearchOpts().Verbose)
785     OS << "clang -cc1 version " CLANG_VERSION_STRING
786        << " based upon " << BACKEND_PACKAGE_STRING
787        << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
788 
789   if (getFrontendOpts().ShowTimers)
790     createFrontendTimer();
791 
792   if (getFrontendOpts().ShowStats)
793     llvm::EnableStatistics();
794 
795   for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
796     // Reset the ID tables if we are reusing the SourceManager and parsing
797     // regular files.
798     if (hasSourceManager() && !Act.isModelParsingAction())
799       getSourceManager().clearIDTables();
800 
801     if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
802       Act.Execute();
803       Act.EndSourceFile();
804     }
805   }
806 
807   // Notify the diagnostic client that all files were processed.
808   getDiagnostics().getClient()->finish();
809 
810   if (getDiagnosticOpts().ShowCarets) {
811     // We can have multiple diagnostics sharing one diagnostic client.
812     // Get the total number of warnings/errors from the client.
813     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
814     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
815 
816     if (NumWarnings)
817       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
818     if (NumWarnings && NumErrors)
819       OS << " and ";
820     if (NumErrors)
821       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
822     if (NumWarnings || NumErrors)
823       OS << " generated.\n";
824   }
825 
826   if (getFrontendOpts().ShowStats && hasFileManager()) {
827     getFileManager().PrintStats();
828     OS << "\n";
829   }
830 
831   return !getDiagnostics().getClient()->getNumErrors();
832 }
833 
834 /// \brief Determine the appropriate source input kind based on language
835 /// options.
836 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
837   if (LangOpts.OpenCL)
838     return IK_OpenCL;
839   if (LangOpts.CUDA)
840     return IK_CUDA;
841   if (LangOpts.ObjC1)
842     return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
843   return LangOpts.CPlusPlus? IK_CXX : IK_C;
844 }
845 
846 /// \brief Compile a module file for the given module, using the options
847 /// provided by the importing compiler instance. Returns true if the module
848 /// was built without errors.
849 static bool compileModuleImpl(CompilerInstance &ImportingInstance,
850                               SourceLocation ImportLoc,
851                               Module *Module,
852                               StringRef ModuleFileName) {
853   ModuleMap &ModMap
854     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
855 
856   // Construct a compiler invocation for creating this module.
857   IntrusiveRefCntPtr<CompilerInvocation> Invocation
858     (new CompilerInvocation(ImportingInstance.getInvocation()));
859 
860   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
861 
862   // For any options that aren't intended to affect how a module is built,
863   // reset them to their default values.
864   Invocation->getLangOpts()->resetNonModularOptions();
865   PPOpts.resetNonModularOptions();
866 
867   // Remove any macro definitions that are explicitly ignored by the module.
868   // They aren't supposed to affect how the module is built anyway.
869   const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
870   PPOpts.Macros.erase(
871       std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
872                      [&HSOpts](const std::pair<std::string, bool> &def) {
873         StringRef MacroDef = def.first;
874         return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
875       }),
876       PPOpts.Macros.end());
877 
878   // Note the name of the module we're building.
879   Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
880 
881   // Make sure that the failed-module structure has been allocated in
882   // the importing instance, and propagate the pointer to the newly-created
883   // instance.
884   PreprocessorOptions &ImportingPPOpts
885     = ImportingInstance.getInvocation().getPreprocessorOpts();
886   if (!ImportingPPOpts.FailedModules)
887     ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
888   PPOpts.FailedModules = ImportingPPOpts.FailedModules;
889 
890   // If there is a module map file, build the module using the module map.
891   // Set up the inputs/outputs so that we build the module from its umbrella
892   // header.
893   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
894   FrontendOpts.OutputFile = ModuleFileName.str();
895   FrontendOpts.DisableFree = false;
896   FrontendOpts.GenerateGlobalModuleIndex = false;
897   FrontendOpts.Inputs.clear();
898   InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
899 
900   // Don't free the remapped file buffers; they are owned by our caller.
901   PPOpts.RetainRemappedFileBuffers = true;
902 
903   Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
904   assert(ImportingInstance.getInvocation().getModuleHash() ==
905          Invocation->getModuleHash() && "Module hash mismatch!");
906 
907   // Construct a compiler instance that will be used to actually create the
908   // module.
909   CompilerInstance Instance(/*BuildingModule=*/true);
910   Instance.setInvocation(&*Invocation);
911 
912   Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
913                                    ImportingInstance.getDiagnosticClient()),
914                              /*ShouldOwnClient=*/true);
915 
916   Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
917 
918   // Note that this module is part of the module build stack, so that we
919   // can detect cycles in the module graph.
920   Instance.setFileManager(&ImportingInstance.getFileManager());
921   Instance.createSourceManager(Instance.getFileManager());
922   SourceManager &SourceMgr = Instance.getSourceManager();
923   SourceMgr.setModuleBuildStack(
924     ImportingInstance.getSourceManager().getModuleBuildStack());
925   SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
926     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
927 
928   // If we're collecting module dependencies, we need to share a collector
929   // between all of the module CompilerInstances.
930   Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
931 
932   // Get or create the module map that we'll use to build this module.
933   std::string InferredModuleMapContent;
934   if (const FileEntry *ModuleMapFile =
935           ModMap.getContainingModuleMapFile(Module)) {
936     // Use the module map where this module resides.
937     FrontendOpts.Inputs.push_back(
938         FrontendInputFile(ModuleMapFile->getName(), IK));
939   } else {
940     llvm::raw_string_ostream OS(InferredModuleMapContent);
941     Module->print(OS);
942     OS.flush();
943     FrontendOpts.Inputs.push_back(
944         FrontendInputFile("__inferred_module.map", IK));
945 
946     std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
947         llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
948     ModuleMapFile = Instance.getFileManager().getVirtualFile(
949         "__inferred_module.map", InferredModuleMapContent.size(), 0);
950     SourceMgr.overrideFileContents(ModuleMapFile, std::move(ModuleMapBuffer));
951   }
952 
953   // Construct a module-generating action. Passing through the module map is
954   // safe because the FileManager is shared between the compiler instances.
955   GenerateModuleAction CreateModuleAction(
956       ModMap.getModuleMapFileForUniquing(Module), Module->IsSystem);
957 
958   ImportingInstance.getDiagnostics().Report(ImportLoc,
959                                             diag::remark_module_build)
960     << Module->Name << ModuleFileName;
961 
962   // Execute the action to actually build the module in-place. Use a separate
963   // thread so that we get a stack large enough.
964   const unsigned ThreadStackSize = 8 << 20;
965   llvm::CrashRecoveryContext CRC;
966   CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
967                         ThreadStackSize);
968 
969   ImportingInstance.getDiagnostics().Report(ImportLoc,
970                                             diag::remark_module_build_done)
971     << Module->Name;
972 
973   // Delete the temporary module map file.
974   // FIXME: Even though we're executing under crash protection, it would still
975   // be nice to do this with RemoveFileOnSignal when we can. However, that
976   // doesn't make sense for all clients, so clean this up manually.
977   Instance.clearOutputFiles(/*EraseFiles=*/true);
978 
979   // We've rebuilt a module. If we're allowed to generate or update the global
980   // module index, record that fact in the importing compiler instance.
981   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
982     ImportingInstance.setBuildGlobalModuleIndex(true);
983   }
984 
985   return !Instance.getDiagnostics().hasErrorOccurred();
986 }
987 
988 static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
989                                  SourceLocation ImportLoc,
990                                  SourceLocation ModuleNameLoc, Module *Module,
991                                  StringRef ModuleFileName) {
992   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
993 
994   auto diagnoseBuildFailure = [&] {
995     Diags.Report(ModuleNameLoc, diag::err_module_not_built)
996         << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
997   };
998 
999   // FIXME: have LockFileManager return an error_code so that we can
1000   // avoid the mkdir when the directory already exists.
1001   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1002   llvm::sys::fs::create_directories(Dir);
1003 
1004   while (1) {
1005     unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1006     llvm::LockFileManager Locked(ModuleFileName);
1007     switch (Locked) {
1008     case llvm::LockFileManager::LFS_Error:
1009       Diags.Report(ModuleNameLoc, diag::err_module_lock_failure)
1010           << Module->Name;
1011       return false;
1012 
1013     case llvm::LockFileManager::LFS_Owned:
1014       // We're responsible for building the module ourselves.
1015       if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
1016                              ModuleFileName)) {
1017         diagnoseBuildFailure();
1018         return false;
1019       }
1020       break;
1021 
1022     case llvm::LockFileManager::LFS_Shared:
1023       // Someone else is responsible for building the module. Wait for them to
1024       // finish.
1025       if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied)
1026         continue; // try again to get the lock.
1027       ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1028       break;
1029     }
1030 
1031     // Try to read the module file, now that we've compiled it.
1032     ASTReader::ASTReadResult ReadResult =
1033         ImportingInstance.getModuleManager()->ReadAST(
1034             ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1035             ModuleLoadCapabilities);
1036 
1037     if (ReadResult == ASTReader::OutOfDate &&
1038         Locked == llvm::LockFileManager::LFS_Shared) {
1039       // The module may be out of date in the presence of file system races,
1040       // or if one of its imports depends on header search paths that are not
1041       // consistent with this ImportingInstance.  Try again...
1042       continue;
1043     } else if (ReadResult == ASTReader::Missing) {
1044       diagnoseBuildFailure();
1045     } else if (ReadResult != ASTReader::Success &&
1046                !Diags.hasErrorOccurred()) {
1047       // The ASTReader didn't diagnose the error, so conservatively report it.
1048       diagnoseBuildFailure();
1049     }
1050     return ReadResult == ASTReader::Success;
1051   }
1052 }
1053 
1054 /// \brief Diagnose differences between the current definition of the given
1055 /// configuration macro and the definition provided on the command line.
1056 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1057                              Module *Mod, SourceLocation ImportLoc) {
1058   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1059   SourceManager &SourceMgr = PP.getSourceManager();
1060 
1061   // If this identifier has never had a macro definition, then it could
1062   // not have changed.
1063   if (!Id->hadMacroDefinition())
1064     return;
1065 
1066   // If this identifier does not currently have a macro definition,
1067   // check whether it had one on the command line.
1068   if (!Id->hasMacroDefinition()) {
1069     MacroDirective::DefInfo LatestDef =
1070         PP.getMacroDirectiveHistory(Id)->getDefinition();
1071     for (MacroDirective::DefInfo Def = LatestDef; Def;
1072            Def = Def.getPreviousDefinition()) {
1073       FileID FID = SourceMgr.getFileID(Def.getLocation());
1074       if (FID.isInvalid())
1075         continue;
1076 
1077       // We only care about the predefines buffer.
1078       if (FID != PP.getPredefinesFileID())
1079         continue;
1080 
1081       // This macro was defined on the command line, then #undef'd later.
1082       // Complain.
1083       PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1084         << true << ConfigMacro << Mod->getFullModuleName();
1085       if (LatestDef.isUndefined())
1086         PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1087           << true;
1088       return;
1089     }
1090 
1091     // Okay: no definition in the predefines buffer.
1092     return;
1093   }
1094 
1095   // This identifier has a macro definition. Check whether we had a definition
1096   // on the command line.
1097   MacroDirective::DefInfo LatestDef =
1098       PP.getMacroDirectiveHistory(Id)->getDefinition();
1099   MacroDirective::DefInfo PredefinedDef;
1100   for (MacroDirective::DefInfo Def = LatestDef; Def;
1101          Def = Def.getPreviousDefinition()) {
1102     FileID FID = SourceMgr.getFileID(Def.getLocation());
1103     if (FID.isInvalid())
1104       continue;
1105 
1106     // We only care about the predefines buffer.
1107     if (FID != PP.getPredefinesFileID())
1108       continue;
1109 
1110     PredefinedDef = Def;
1111     break;
1112   }
1113 
1114   // If there was no definition for this macro in the predefines buffer,
1115   // complain.
1116   if (!PredefinedDef ||
1117       (!PredefinedDef.getLocation().isValid() &&
1118        PredefinedDef.getUndefLocation().isValid())) {
1119     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1120       << false << ConfigMacro << Mod->getFullModuleName();
1121     PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
1122       << false;
1123     return;
1124   }
1125 
1126   // If the current macro definition is the same as the predefined macro
1127   // definition, it's okay.
1128   if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
1129       LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
1130                                               /*Syntactically=*/true))
1131     return;
1132 
1133   // The macro definitions differ.
1134   PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1135     << false << ConfigMacro << Mod->getFullModuleName();
1136   PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
1137     << false;
1138 }
1139 
1140 /// \brief Write a new timestamp file with the given path.
1141 static void writeTimestampFile(StringRef TimestampFile) {
1142   std::error_code EC;
1143   llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
1144 }
1145 
1146 /// \brief Prune the module cache of modules that haven't been accessed in
1147 /// a long time.
1148 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1149   struct stat StatBuf;
1150   llvm::SmallString<128> TimestampFile;
1151   TimestampFile = HSOpts.ModuleCachePath;
1152   llvm::sys::path::append(TimestampFile, "modules.timestamp");
1153 
1154   // Try to stat() the timestamp file.
1155   if (::stat(TimestampFile.c_str(), &StatBuf)) {
1156     // If the timestamp file wasn't there, create one now.
1157     if (errno == ENOENT) {
1158       writeTimestampFile(TimestampFile);
1159     }
1160     return;
1161   }
1162 
1163   // Check whether the time stamp is older than our pruning interval.
1164   // If not, do nothing.
1165   time_t TimeStampModTime = StatBuf.st_mtime;
1166   time_t CurrentTime = time(nullptr);
1167   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1168     return;
1169 
1170   // Write a new timestamp file so that nobody else attempts to prune.
1171   // There is a benign race condition here, if two Clang instances happen to
1172   // notice at the same time that the timestamp is out-of-date.
1173   writeTimestampFile(TimestampFile);
1174 
1175   // Walk the entire module cache, looking for unused module files and module
1176   // indices.
1177   std::error_code EC;
1178   SmallString<128> ModuleCachePathNative;
1179   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1180   for (llvm::sys::fs::directory_iterator
1181          Dir(ModuleCachePathNative.str(), EC), DirEnd;
1182        Dir != DirEnd && !EC; Dir.increment(EC)) {
1183     // If we don't have a directory, there's nothing to look into.
1184     if (!llvm::sys::fs::is_directory(Dir->path()))
1185       continue;
1186 
1187     // Walk all of the files within this directory.
1188     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1189          File != FileEnd && !EC; File.increment(EC)) {
1190       // We only care about module and global module index files.
1191       StringRef Extension = llvm::sys::path::extension(File->path());
1192       if (Extension != ".pcm" && Extension != ".timestamp" &&
1193           llvm::sys::path::filename(File->path()) != "modules.idx")
1194         continue;
1195 
1196       // Look at this file. If we can't stat it, there's nothing interesting
1197       // there.
1198       if (::stat(File->path().c_str(), &StatBuf))
1199         continue;
1200 
1201       // If the file has been used recently enough, leave it there.
1202       time_t FileAccessTime = StatBuf.st_atime;
1203       if (CurrentTime - FileAccessTime <=
1204               time_t(HSOpts.ModuleCachePruneAfter)) {
1205         continue;
1206       }
1207 
1208       // Remove the file.
1209       llvm::sys::fs::remove(File->path());
1210 
1211       // Remove the timestamp file.
1212       std::string TimpestampFilename = File->path() + ".timestamp";
1213       llvm::sys::fs::remove(TimpestampFilename);
1214     }
1215 
1216     // If we removed all of the files in the directory, remove the directory
1217     // itself.
1218     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1219             llvm::sys::fs::directory_iterator() && !EC)
1220       llvm::sys::fs::remove(Dir->path());
1221   }
1222 }
1223 
1224 void CompilerInstance::createModuleManager() {
1225   if (!ModuleManager) {
1226     if (!hasASTContext())
1227       createASTContext();
1228 
1229     // If we're not recursively building a module, check whether we
1230     // need to prune the module cache.
1231     if (getSourceManager().getModuleBuildStack().empty() &&
1232         getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1233         getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1234       pruneModuleCache(getHeaderSearchOpts());
1235     }
1236 
1237     HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1238     std::string Sysroot = HSOpts.Sysroot;
1239     const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1240     ModuleManager = new ASTReader(getPreprocessor(), *Context,
1241                                   Sysroot.empty() ? "" : Sysroot.c_str(),
1242                                   PPOpts.DisablePCHValidation,
1243                                   /*AllowASTWithCompilerErrors=*/false,
1244                                   /*AllowConfigurationMismatch=*/false,
1245                                   HSOpts.ModulesValidateSystemHeaders,
1246                                   getFrontendOpts().UseGlobalModuleIndex);
1247     if (hasASTConsumer()) {
1248       ModuleManager->setDeserializationListener(
1249         getASTConsumer().GetASTDeserializationListener());
1250       getASTContext().setASTMutationListener(
1251         getASTConsumer().GetASTMutationListener());
1252     }
1253     getASTContext().setExternalSource(ModuleManager);
1254     if (hasSema())
1255       ModuleManager->InitializeSema(getSema());
1256     if (hasASTConsumer())
1257       ModuleManager->StartTranslationUnit(&getASTConsumer());
1258   }
1259 }
1260 
1261 bool CompilerInstance::loadModuleFile(StringRef FileName) {
1262   // Helper to recursively read the module names for all modules we're adding.
1263   // We mark these as known and redirect any attempt to load that module to
1264   // the files we were handed.
1265   struct ReadModuleNames : ASTReaderListener {
1266     CompilerInstance &CI;
1267     std::vector<StringRef> ModuleFileStack;
1268     bool Failed;
1269     bool TopFileIsModule;
1270 
1271     ReadModuleNames(CompilerInstance &CI)
1272         : CI(CI), Failed(false), TopFileIsModule(false) {}
1273 
1274     bool needsImportVisitation() const override { return true; }
1275 
1276     void visitImport(StringRef FileName) override {
1277       ModuleFileStack.push_back(FileName);
1278       if (ASTReader::readASTFileControlBlock(FileName, CI.getFileManager(),
1279                                              *this)) {
1280         CI.getDiagnostics().Report(SourceLocation(),
1281                                    diag::err_module_file_not_found)
1282             << FileName;
1283         // FIXME: Produce a note stack explaining how we got here.
1284         Failed = true;
1285       }
1286       ModuleFileStack.pop_back();
1287     }
1288 
1289     void ReadModuleName(StringRef ModuleName) override {
1290       if (ModuleFileStack.size() == 1)
1291         TopFileIsModule = true;
1292 
1293       auto &ModuleFile = CI.ModuleFileOverrides[ModuleName];
1294       if (!ModuleFile.empty() &&
1295           CI.getFileManager().getFile(ModuleFile) !=
1296               CI.getFileManager().getFile(ModuleFileStack.back()))
1297         CI.getDiagnostics().Report(SourceLocation(),
1298                                    diag::err_conflicting_module_files)
1299             << ModuleName << ModuleFile << ModuleFileStack.back();
1300       ModuleFile = ModuleFileStack.back();
1301     }
1302   } RMN(*this);
1303 
1304   RMN.visitImport(FileName);
1305 
1306   if (RMN.Failed)
1307     return false;
1308 
1309   // If we never found a module name for the top file, then it's not a module,
1310   // it's a PCH or preamble or something.
1311   if (!RMN.TopFileIsModule) {
1312     getDiagnostics().Report(SourceLocation(), diag::err_module_file_not_module)
1313       << FileName;
1314     return false;
1315   }
1316 
1317   return true;
1318 }
1319 
1320 ModuleLoadResult
1321 CompilerInstance::loadModule(SourceLocation ImportLoc,
1322                              ModuleIdPath Path,
1323                              Module::NameVisibilityKind Visibility,
1324                              bool IsInclusionDirective) {
1325   // Determine what file we're searching from.
1326   StringRef ModuleName = Path[0].first->getName();
1327   SourceLocation ModuleNameLoc = Path[0].second;
1328 
1329   // If we've already handled this import, just return the cached result.
1330   // This one-element cache is important to eliminate redundant diagnostics
1331   // when both the preprocessor and parser see the same import declaration.
1332   if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
1333     // Make the named module visible.
1334     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule &&
1335         ModuleName != getLangOpts().ImplementationOfModule)
1336       ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1337                                        ImportLoc, /*Complain=*/false);
1338     return LastModuleImportResult;
1339   }
1340 
1341   clang::Module *Module = nullptr;
1342 
1343   // If we don't already have information on this module, load the module now.
1344   llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1345     = KnownModules.find(Path[0].first);
1346   if (Known != KnownModules.end()) {
1347     // Retrieve the cached top-level module.
1348     Module = Known->second;
1349   } else if (ModuleName == getLangOpts().CurrentModule ||
1350              ModuleName == getLangOpts().ImplementationOfModule) {
1351     // This is the module we're building.
1352     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1353     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1354   } else {
1355     // Search for a module with the given name.
1356     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1357     if (!Module) {
1358       getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1359       << ModuleName
1360       << SourceRange(ImportLoc, ModuleNameLoc);
1361       ModuleBuildFailed = true;
1362       return ModuleLoadResult();
1363     }
1364 
1365     auto Override = ModuleFileOverrides.find(ModuleName);
1366     bool Explicit = Override != ModuleFileOverrides.end();
1367 
1368     std::string ModuleFileName =
1369         Explicit ? Override->second
1370                  : PP->getHeaderSearchInfo().getModuleFileName(Module);
1371 
1372     // If we don't already have an ASTReader, create one now.
1373     if (!ModuleManager)
1374       createModuleManager();
1375 
1376     if (TheDependencyFileGenerator)
1377       TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
1378 
1379     if (ModuleDepCollector)
1380       ModuleDepCollector->attachToASTReader(*ModuleManager);
1381 
1382     for (auto &Listener : DependencyCollectors)
1383       Listener->attachToASTReader(*ModuleManager);
1384 
1385     // Try to load the module file.
1386     unsigned ARRFlags =
1387         Explicit ? 0 : ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
1388     switch (ModuleManager->ReadAST(ModuleFileName,
1389                                    Explicit ? serialization::MK_ExplicitModule
1390                                             : serialization::MK_ImplicitModule,
1391                                    ImportLoc, ARRFlags)) {
1392     case ASTReader::Success:
1393       break;
1394 
1395     case ASTReader::OutOfDate:
1396     case ASTReader::Missing: {
1397       if (Explicit) {
1398         // ReadAST has already complained for us.
1399         ModuleLoader::HadFatalFailure = true;
1400         KnownModules[Path[0].first] = nullptr;
1401         return ModuleLoadResult();
1402       }
1403 
1404       // The module file is missing or out-of-date. Build it.
1405       assert(Module && "missing module file");
1406       // Check whether there is a cycle in the module graph.
1407       ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1408       ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1409       for (; Pos != PosEnd; ++Pos) {
1410         if (Pos->first == ModuleName)
1411           break;
1412       }
1413 
1414       if (Pos != PosEnd) {
1415         SmallString<256> CyclePath;
1416         for (; Pos != PosEnd; ++Pos) {
1417           CyclePath += Pos->first;
1418           CyclePath += " -> ";
1419         }
1420         CyclePath += ModuleName;
1421 
1422         getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1423           << ModuleName << CyclePath;
1424         return ModuleLoadResult();
1425       }
1426 
1427       // Check whether we have already attempted to build this module (but
1428       // failed).
1429       if (getPreprocessorOpts().FailedModules &&
1430           getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1431         getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1432           << ModuleName
1433           << SourceRange(ImportLoc, ModuleNameLoc);
1434         ModuleBuildFailed = true;
1435         return ModuleLoadResult();
1436       }
1437 
1438       // Try to compile and then load the module.
1439       if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
1440                                 ModuleFileName)) {
1441         assert(getDiagnostics().hasErrorOccurred() &&
1442                "undiagnosed error in compileAndLoadModule");
1443         if (getPreprocessorOpts().FailedModules)
1444           getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1445         KnownModules[Path[0].first] = nullptr;
1446         ModuleBuildFailed = true;
1447         return ModuleLoadResult();
1448       }
1449 
1450       // Okay, we've rebuilt and now loaded the module.
1451       break;
1452     }
1453 
1454     case ASTReader::VersionMismatch:
1455     case ASTReader::ConfigurationMismatch:
1456     case ASTReader::HadErrors:
1457       ModuleLoader::HadFatalFailure = true;
1458       // FIXME: The ASTReader will already have complained, but can we showhorn
1459       // that diagnostic information into a more useful form?
1460       KnownModules[Path[0].first] = nullptr;
1461       return ModuleLoadResult();
1462 
1463     case ASTReader::Failure:
1464       ModuleLoader::HadFatalFailure = true;
1465       // Already complained, but note now that we failed.
1466       KnownModules[Path[0].first] = nullptr;
1467       ModuleBuildFailed = true;
1468       return ModuleLoadResult();
1469     }
1470 
1471     // Cache the result of this top-level module lookup for later.
1472     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1473   }
1474 
1475   // If we never found the module, fail.
1476   if (!Module)
1477     return ModuleLoadResult();
1478 
1479   // Verify that the rest of the module path actually corresponds to
1480   // a submodule.
1481   if (Path.size() > 1) {
1482     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1483       StringRef Name = Path[I].first->getName();
1484       clang::Module *Sub = Module->findSubmodule(Name);
1485 
1486       if (!Sub) {
1487         // Attempt to perform typo correction to find a module name that works.
1488         SmallVector<StringRef, 2> Best;
1489         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1490 
1491         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1492                                             JEnd = Module->submodule_end();
1493              J != JEnd; ++J) {
1494           unsigned ED = Name.edit_distance((*J)->Name,
1495                                            /*AllowReplacements=*/true,
1496                                            BestEditDistance);
1497           if (ED <= BestEditDistance) {
1498             if (ED < BestEditDistance) {
1499               Best.clear();
1500               BestEditDistance = ED;
1501             }
1502 
1503             Best.push_back((*J)->Name);
1504           }
1505         }
1506 
1507         // If there was a clear winner, user it.
1508         if (Best.size() == 1) {
1509           getDiagnostics().Report(Path[I].second,
1510                                   diag::err_no_submodule_suggest)
1511             << Path[I].first << Module->getFullModuleName() << Best[0]
1512             << SourceRange(Path[0].second, Path[I-1].second)
1513             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1514                                             Best[0]);
1515 
1516           Sub = Module->findSubmodule(Best[0]);
1517         }
1518       }
1519 
1520       if (!Sub) {
1521         // No submodule by this name. Complain, and don't look for further
1522         // submodules.
1523         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1524           << Path[I].first << Module->getFullModuleName()
1525           << SourceRange(Path[0].second, Path[I-1].second);
1526         break;
1527       }
1528 
1529       Module = Sub;
1530     }
1531   }
1532 
1533   // Don't make the module visible if we are in the implementation.
1534   if (ModuleName == getLangOpts().ImplementationOfModule)
1535     return ModuleLoadResult(Module, false);
1536 
1537   // Make the named module visible, if it's not already part of the module
1538   // we are parsing.
1539   if (ModuleName != getLangOpts().CurrentModule) {
1540     if (!Module->IsFromModuleFile) {
1541       // We have an umbrella header or directory that doesn't actually include
1542       // all of the headers within the directory it covers. Complain about
1543       // this missing submodule and recover by forgetting that we ever saw
1544       // this submodule.
1545       // FIXME: Should we detect this at module load time? It seems fairly
1546       // expensive (and rare).
1547       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1548         << Module->getFullModuleName()
1549         << SourceRange(Path.front().second, Path.back().second);
1550 
1551       return ModuleLoadResult(nullptr, true);
1552     }
1553 
1554     // Check whether this module is available.
1555     clang::Module::Requirement Requirement;
1556     clang::Module::UnresolvedHeaderDirective MissingHeader;
1557     if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
1558                              MissingHeader)) {
1559       if (MissingHeader.FileNameLoc.isValid()) {
1560         getDiagnostics().Report(MissingHeader.FileNameLoc,
1561                                 diag::err_module_header_missing)
1562           << MissingHeader.IsUmbrella << MissingHeader.FileName;
1563       } else {
1564         getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1565           << Module->getFullModuleName()
1566           << Requirement.second << Requirement.first
1567           << SourceRange(Path.front().second, Path.back().second);
1568       }
1569       LastModuleImportLoc = ImportLoc;
1570       LastModuleImportResult = ModuleLoadResult();
1571       return ModuleLoadResult();
1572     }
1573 
1574     ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
1575                                      /*Complain=*/true);
1576   }
1577 
1578   // Check for any configuration macros that have changed.
1579   clang::Module *TopModule = Module->getTopLevelModule();
1580   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1581     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
1582                      Module, ImportLoc);
1583   }
1584 
1585   // Determine whether we're in the #include buffer for a module. The #includes
1586   // in that buffer do not qualify as module imports; they're just an
1587   // implementation detail of us building the module.
1588   bool IsInModuleIncludes = !getLangOpts().CurrentModule.empty() &&
1589                             getSourceManager().getFileID(ImportLoc) ==
1590                                 getSourceManager().getMainFileID();
1591 
1592   // If this module import was due to an inclusion directive, create an
1593   // implicit import declaration to capture it in the AST.
1594   if (IsInclusionDirective && hasASTContext() && !IsInModuleIncludes) {
1595     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1596     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
1597                                                      ImportLoc, Module,
1598                                                      Path.back().second);
1599     TU->addDecl(ImportD);
1600     if (Consumer)
1601       Consumer->HandleImplicitImportDecl(ImportD);
1602   }
1603 
1604   LastModuleImportLoc = ImportLoc;
1605   LastModuleImportResult = ModuleLoadResult(Module, false);
1606   return LastModuleImportResult;
1607 }
1608 
1609 void CompilerInstance::makeModuleVisible(Module *Mod,
1610                                          Module::NameVisibilityKind Visibility,
1611                                          SourceLocation ImportLoc,
1612                                          bool Complain){
1613   ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
1614 }
1615 
1616 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
1617     SourceLocation TriggerLoc) {
1618   if (!ModuleManager)
1619     createModuleManager();
1620   // Can't do anything if we don't have the module manager.
1621   if (!ModuleManager)
1622     return nullptr;
1623   // Get an existing global index.  This loads it if not already
1624   // loaded.
1625   ModuleManager->loadGlobalIndex();
1626   GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1627   // If the global index doesn't exist, create it.
1628   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
1629       hasPreprocessor()) {
1630     llvm::sys::fs::create_directories(
1631       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1632     GlobalModuleIndex::writeIndex(
1633       getFileManager(),
1634       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1635     ModuleManager->resetForReload();
1636     ModuleManager->loadGlobalIndex();
1637     GlobalIndex = ModuleManager->getGlobalIndex();
1638   }
1639   // For finding modules needing to be imported for fixit messages,
1640   // we need to make the global index cover all modules, so we do that here.
1641   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
1642     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1643     bool RecreateIndex = false;
1644     for (ModuleMap::module_iterator I = MMap.module_begin(),
1645         E = MMap.module_end(); I != E; ++I) {
1646       Module *TheModule = I->second;
1647       const FileEntry *Entry = TheModule->getASTFile();
1648       if (!Entry) {
1649         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1650         Path.push_back(std::make_pair(
1651 				  getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
1652         std::reverse(Path.begin(), Path.end());
1653 		    // Load a module as hidden.  This also adds it to the global index.
1654         loadModule(TheModule->DefinitionLoc, Path,
1655                                              Module::Hidden, false);
1656         RecreateIndex = true;
1657       }
1658     }
1659     if (RecreateIndex) {
1660       GlobalModuleIndex::writeIndex(
1661         getFileManager(),
1662         getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1663       ModuleManager->resetForReload();
1664       ModuleManager->loadGlobalIndex();
1665       GlobalIndex = ModuleManager->getGlobalIndex();
1666     }
1667     HaveFullGlobalModuleIndex = true;
1668   }
1669   return GlobalIndex;
1670 }
1671 
1672 // Check global module index for missing imports.
1673 bool
1674 CompilerInstance::lookupMissingImports(StringRef Name,
1675                                        SourceLocation TriggerLoc) {
1676   // Look for the symbol in non-imported modules, but only if an error
1677   // actually occurred.
1678   if (!buildingModule()) {
1679     // Load global module index, or retrieve a previously loaded one.
1680     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
1681       TriggerLoc);
1682 
1683     // Only if we have a global index.
1684     if (GlobalIndex) {
1685       GlobalModuleIndex::HitSet FoundModules;
1686 
1687       // Find the modules that reference the identifier.
1688       // Note that this only finds top-level modules.
1689       // We'll let diagnoseTypo find the actual declaration module.
1690       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
1691         return true;
1692     }
1693   }
1694 
1695   return false;
1696 }
1697 void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); }
1698