xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision 1daf4801469021590a814e0f8fbdade459d42b27)
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       switch (Locked.waitForUnlock()) {
1026       case llvm::LockFileManager::Res_Success:
1027         ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1028         break;
1029       case llvm::LockFileManager::Res_OwnerDied:
1030         continue; // try again to get the lock.
1031       case llvm::LockFileManager::Res_Timeout:
1032         Diags.Report(ModuleNameLoc, diag::err_module_lock_timeout)
1033             << Module->Name;
1034         // Clear the lock file so that future invokations can make progress.
1035         Locked.unsafeRemoveLockFile();
1036         return false;
1037       }
1038       break;
1039     }
1040 
1041     // Try to read the module file, now that we've compiled it.
1042     ASTReader::ASTReadResult ReadResult =
1043         ImportingInstance.getModuleManager()->ReadAST(
1044             ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1045             ModuleLoadCapabilities);
1046 
1047     if (ReadResult == ASTReader::OutOfDate &&
1048         Locked == llvm::LockFileManager::LFS_Shared) {
1049       // The module may be out of date in the presence of file system races,
1050       // or if one of its imports depends on header search paths that are not
1051       // consistent with this ImportingInstance.  Try again...
1052       continue;
1053     } else if (ReadResult == ASTReader::Missing) {
1054       diagnoseBuildFailure();
1055     } else if (ReadResult != ASTReader::Success &&
1056                !Diags.hasErrorOccurred()) {
1057       // The ASTReader didn't diagnose the error, so conservatively report it.
1058       diagnoseBuildFailure();
1059     }
1060     return ReadResult == ASTReader::Success;
1061   }
1062 }
1063 
1064 /// \brief Diagnose differences between the current definition of the given
1065 /// configuration macro and the definition provided on the command line.
1066 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1067                              Module *Mod, SourceLocation ImportLoc) {
1068   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1069   SourceManager &SourceMgr = PP.getSourceManager();
1070 
1071   // If this identifier has never had a macro definition, then it could
1072   // not have changed.
1073   if (!Id->hadMacroDefinition())
1074     return;
1075 
1076   // If this identifier does not currently have a macro definition,
1077   // check whether it had one on the command line.
1078   if (!Id->hasMacroDefinition()) {
1079     MacroDirective::DefInfo LatestDef =
1080         PP.getMacroDirectiveHistory(Id)->getDefinition();
1081     for (MacroDirective::DefInfo Def = LatestDef; Def;
1082            Def = Def.getPreviousDefinition()) {
1083       FileID FID = SourceMgr.getFileID(Def.getLocation());
1084       if (FID.isInvalid())
1085         continue;
1086 
1087       // We only care about the predefines buffer.
1088       if (FID != PP.getPredefinesFileID())
1089         continue;
1090 
1091       // This macro was defined on the command line, then #undef'd later.
1092       // Complain.
1093       PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1094         << true << ConfigMacro << Mod->getFullModuleName();
1095       if (LatestDef.isUndefined())
1096         PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1097           << true;
1098       return;
1099     }
1100 
1101     // Okay: no definition in the predefines buffer.
1102     return;
1103   }
1104 
1105   // This identifier has a macro definition. Check whether we had a definition
1106   // on the command line.
1107   MacroDirective::DefInfo LatestDef =
1108       PP.getMacroDirectiveHistory(Id)->getDefinition();
1109   MacroDirective::DefInfo PredefinedDef;
1110   for (MacroDirective::DefInfo Def = LatestDef; Def;
1111          Def = Def.getPreviousDefinition()) {
1112     FileID FID = SourceMgr.getFileID(Def.getLocation());
1113     if (FID.isInvalid())
1114       continue;
1115 
1116     // We only care about the predefines buffer.
1117     if (FID != PP.getPredefinesFileID())
1118       continue;
1119 
1120     PredefinedDef = Def;
1121     break;
1122   }
1123 
1124   // If there was no definition for this macro in the predefines buffer,
1125   // complain.
1126   if (!PredefinedDef ||
1127       (!PredefinedDef.getLocation().isValid() &&
1128        PredefinedDef.getUndefLocation().isValid())) {
1129     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1130       << false << ConfigMacro << Mod->getFullModuleName();
1131     PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
1132       << false;
1133     return;
1134   }
1135 
1136   // If the current macro definition is the same as the predefined macro
1137   // definition, it's okay.
1138   if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
1139       LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
1140                                               /*Syntactically=*/true))
1141     return;
1142 
1143   // The macro definitions differ.
1144   PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1145     << false << ConfigMacro << Mod->getFullModuleName();
1146   PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
1147     << false;
1148 }
1149 
1150 /// \brief Write a new timestamp file with the given path.
1151 static void writeTimestampFile(StringRef TimestampFile) {
1152   std::error_code EC;
1153   llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
1154 }
1155 
1156 /// \brief Prune the module cache of modules that haven't been accessed in
1157 /// a long time.
1158 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1159   struct stat StatBuf;
1160   llvm::SmallString<128> TimestampFile;
1161   TimestampFile = HSOpts.ModuleCachePath;
1162   llvm::sys::path::append(TimestampFile, "modules.timestamp");
1163 
1164   // Try to stat() the timestamp file.
1165   if (::stat(TimestampFile.c_str(), &StatBuf)) {
1166     // If the timestamp file wasn't there, create one now.
1167     if (errno == ENOENT) {
1168       writeTimestampFile(TimestampFile);
1169     }
1170     return;
1171   }
1172 
1173   // Check whether the time stamp is older than our pruning interval.
1174   // If not, do nothing.
1175   time_t TimeStampModTime = StatBuf.st_mtime;
1176   time_t CurrentTime = time(nullptr);
1177   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1178     return;
1179 
1180   // Write a new timestamp file so that nobody else attempts to prune.
1181   // There is a benign race condition here, if two Clang instances happen to
1182   // notice at the same time that the timestamp is out-of-date.
1183   writeTimestampFile(TimestampFile);
1184 
1185   // Walk the entire module cache, looking for unused module files and module
1186   // indices.
1187   std::error_code EC;
1188   SmallString<128> ModuleCachePathNative;
1189   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1190   for (llvm::sys::fs::directory_iterator
1191          Dir(ModuleCachePathNative.str(), EC), DirEnd;
1192        Dir != DirEnd && !EC; Dir.increment(EC)) {
1193     // If we don't have a directory, there's nothing to look into.
1194     if (!llvm::sys::fs::is_directory(Dir->path()))
1195       continue;
1196 
1197     // Walk all of the files within this directory.
1198     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1199          File != FileEnd && !EC; File.increment(EC)) {
1200       // We only care about module and global module index files.
1201       StringRef Extension = llvm::sys::path::extension(File->path());
1202       if (Extension != ".pcm" && Extension != ".timestamp" &&
1203           llvm::sys::path::filename(File->path()) != "modules.idx")
1204         continue;
1205 
1206       // Look at this file. If we can't stat it, there's nothing interesting
1207       // there.
1208       if (::stat(File->path().c_str(), &StatBuf))
1209         continue;
1210 
1211       // If the file has been used recently enough, leave it there.
1212       time_t FileAccessTime = StatBuf.st_atime;
1213       if (CurrentTime - FileAccessTime <=
1214               time_t(HSOpts.ModuleCachePruneAfter)) {
1215         continue;
1216       }
1217 
1218       // Remove the file.
1219       llvm::sys::fs::remove(File->path());
1220 
1221       // Remove the timestamp file.
1222       std::string TimpestampFilename = File->path() + ".timestamp";
1223       llvm::sys::fs::remove(TimpestampFilename);
1224     }
1225 
1226     // If we removed all of the files in the directory, remove the directory
1227     // itself.
1228     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1229             llvm::sys::fs::directory_iterator() && !EC)
1230       llvm::sys::fs::remove(Dir->path());
1231   }
1232 }
1233 
1234 void CompilerInstance::createModuleManager() {
1235   if (!ModuleManager) {
1236     if (!hasASTContext())
1237       createASTContext();
1238 
1239     // If we're not recursively building a module, check whether we
1240     // need to prune the module cache.
1241     if (getSourceManager().getModuleBuildStack().empty() &&
1242         getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1243         getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1244       pruneModuleCache(getHeaderSearchOpts());
1245     }
1246 
1247     HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1248     std::string Sysroot = HSOpts.Sysroot;
1249     const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1250     ModuleManager = new ASTReader(getPreprocessor(), *Context,
1251                                   Sysroot.empty() ? "" : Sysroot.c_str(),
1252                                   PPOpts.DisablePCHValidation,
1253                                   /*AllowASTWithCompilerErrors=*/false,
1254                                   /*AllowConfigurationMismatch=*/false,
1255                                   HSOpts.ModulesValidateSystemHeaders,
1256                                   getFrontendOpts().UseGlobalModuleIndex);
1257     if (hasASTConsumer()) {
1258       ModuleManager->setDeserializationListener(
1259         getASTConsumer().GetASTDeserializationListener());
1260       getASTContext().setASTMutationListener(
1261         getASTConsumer().GetASTMutationListener());
1262     }
1263     getASTContext().setExternalSource(ModuleManager);
1264     if (hasSema())
1265       ModuleManager->InitializeSema(getSema());
1266     if (hasASTConsumer())
1267       ModuleManager->StartTranslationUnit(&getASTConsumer());
1268   }
1269 }
1270 
1271 bool CompilerInstance::loadModuleFile(StringRef FileName) {
1272   // Helper to recursively read the module names for all modules we're adding.
1273   // We mark these as known and redirect any attempt to load that module to
1274   // the files we were handed.
1275   struct ReadModuleNames : ASTReaderListener {
1276     CompilerInstance &CI;
1277     std::vector<StringRef> ModuleFileStack;
1278     bool Failed;
1279     bool TopFileIsModule;
1280 
1281     ReadModuleNames(CompilerInstance &CI)
1282         : CI(CI), Failed(false), TopFileIsModule(false) {}
1283 
1284     bool needsImportVisitation() const override { return true; }
1285 
1286     void visitImport(StringRef FileName) override {
1287       ModuleFileStack.push_back(FileName);
1288       if (ASTReader::readASTFileControlBlock(FileName, CI.getFileManager(),
1289                                              *this)) {
1290         CI.getDiagnostics().Report(SourceLocation(),
1291                                    diag::err_module_file_not_found)
1292             << FileName;
1293         // FIXME: Produce a note stack explaining how we got here.
1294         Failed = true;
1295       }
1296       ModuleFileStack.pop_back();
1297     }
1298 
1299     void ReadModuleName(StringRef ModuleName) override {
1300       if (ModuleFileStack.size() == 1)
1301         TopFileIsModule = true;
1302 
1303       auto &ModuleFile = CI.ModuleFileOverrides[ModuleName];
1304       if (!ModuleFile.empty() &&
1305           CI.getFileManager().getFile(ModuleFile) !=
1306               CI.getFileManager().getFile(ModuleFileStack.back()))
1307         CI.getDiagnostics().Report(SourceLocation(),
1308                                    diag::err_conflicting_module_files)
1309             << ModuleName << ModuleFile << ModuleFileStack.back();
1310       ModuleFile = ModuleFileStack.back();
1311     }
1312   } RMN(*this);
1313 
1314   RMN.visitImport(FileName);
1315 
1316   if (RMN.Failed)
1317     return false;
1318 
1319   // If we never found a module name for the top file, then it's not a module,
1320   // it's a PCH or preamble or something.
1321   if (!RMN.TopFileIsModule) {
1322     getDiagnostics().Report(SourceLocation(), diag::err_module_file_not_module)
1323       << FileName;
1324     return false;
1325   }
1326 
1327   return true;
1328 }
1329 
1330 ModuleLoadResult
1331 CompilerInstance::loadModule(SourceLocation ImportLoc,
1332                              ModuleIdPath Path,
1333                              Module::NameVisibilityKind Visibility,
1334                              bool IsInclusionDirective) {
1335   // Determine what file we're searching from.
1336   StringRef ModuleName = Path[0].first->getName();
1337   SourceLocation ModuleNameLoc = Path[0].second;
1338 
1339   // If we've already handled this import, just return the cached result.
1340   // This one-element cache is important to eliminate redundant diagnostics
1341   // when both the preprocessor and parser see the same import declaration.
1342   if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
1343     // Make the named module visible.
1344     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule &&
1345         ModuleName != getLangOpts().ImplementationOfModule)
1346       ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1347                                        ImportLoc, /*Complain=*/false);
1348     return LastModuleImportResult;
1349   }
1350 
1351   clang::Module *Module = nullptr;
1352 
1353   // If we don't already have information on this module, load the module now.
1354   llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1355     = KnownModules.find(Path[0].first);
1356   if (Known != KnownModules.end()) {
1357     // Retrieve the cached top-level module.
1358     Module = Known->second;
1359   } else if (ModuleName == getLangOpts().CurrentModule ||
1360              ModuleName == getLangOpts().ImplementationOfModule) {
1361     // This is the module we're building.
1362     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1363     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1364   } else {
1365     // Search for a module with the given name.
1366     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1367     if (!Module) {
1368       getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1369       << ModuleName
1370       << SourceRange(ImportLoc, ModuleNameLoc);
1371       ModuleBuildFailed = true;
1372       return ModuleLoadResult();
1373     }
1374 
1375     auto Override = ModuleFileOverrides.find(ModuleName);
1376     bool Explicit = Override != ModuleFileOverrides.end();
1377 
1378     std::string ModuleFileName =
1379         Explicit ? Override->second
1380                  : PP->getHeaderSearchInfo().getModuleFileName(Module);
1381 
1382     // If we don't already have an ASTReader, create one now.
1383     if (!ModuleManager)
1384       createModuleManager();
1385 
1386     if (TheDependencyFileGenerator)
1387       TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
1388 
1389     if (ModuleDepCollector)
1390       ModuleDepCollector->attachToASTReader(*ModuleManager);
1391 
1392     for (auto &Listener : DependencyCollectors)
1393       Listener->attachToASTReader(*ModuleManager);
1394 
1395     // Try to load the module file.
1396     unsigned ARRFlags =
1397         Explicit ? 0 : ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
1398     switch (ModuleManager->ReadAST(ModuleFileName,
1399                                    Explicit ? serialization::MK_ExplicitModule
1400                                             : serialization::MK_ImplicitModule,
1401                                    ImportLoc, ARRFlags)) {
1402     case ASTReader::Success:
1403       break;
1404 
1405     case ASTReader::OutOfDate:
1406     case ASTReader::Missing: {
1407       if (Explicit) {
1408         // ReadAST has already complained for us.
1409         ModuleLoader::HadFatalFailure = true;
1410         KnownModules[Path[0].first] = nullptr;
1411         return ModuleLoadResult();
1412       }
1413 
1414       // The module file is missing or out-of-date. Build it.
1415       assert(Module && "missing module file");
1416       // Check whether there is a cycle in the module graph.
1417       ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1418       ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1419       for (; Pos != PosEnd; ++Pos) {
1420         if (Pos->first == ModuleName)
1421           break;
1422       }
1423 
1424       if (Pos != PosEnd) {
1425         SmallString<256> CyclePath;
1426         for (; Pos != PosEnd; ++Pos) {
1427           CyclePath += Pos->first;
1428           CyclePath += " -> ";
1429         }
1430         CyclePath += ModuleName;
1431 
1432         getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1433           << ModuleName << CyclePath;
1434         return ModuleLoadResult();
1435       }
1436 
1437       // Check whether we have already attempted to build this module (but
1438       // failed).
1439       if (getPreprocessorOpts().FailedModules &&
1440           getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1441         getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1442           << ModuleName
1443           << SourceRange(ImportLoc, ModuleNameLoc);
1444         ModuleBuildFailed = true;
1445         return ModuleLoadResult();
1446       }
1447 
1448       // Try to compile and then load the module.
1449       if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
1450                                 ModuleFileName)) {
1451         assert(getDiagnostics().hasErrorOccurred() &&
1452                "undiagnosed error in compileAndLoadModule");
1453         if (getPreprocessorOpts().FailedModules)
1454           getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1455         KnownModules[Path[0].first] = nullptr;
1456         ModuleBuildFailed = true;
1457         return ModuleLoadResult();
1458       }
1459 
1460       // Okay, we've rebuilt and now loaded the module.
1461       break;
1462     }
1463 
1464     case ASTReader::VersionMismatch:
1465     case ASTReader::ConfigurationMismatch:
1466     case ASTReader::HadErrors:
1467       ModuleLoader::HadFatalFailure = true;
1468       // FIXME: The ASTReader will already have complained, but can we showhorn
1469       // that diagnostic information into a more useful form?
1470       KnownModules[Path[0].first] = nullptr;
1471       return ModuleLoadResult();
1472 
1473     case ASTReader::Failure:
1474       ModuleLoader::HadFatalFailure = true;
1475       // Already complained, but note now that we failed.
1476       KnownModules[Path[0].first] = nullptr;
1477       ModuleBuildFailed = true;
1478       return ModuleLoadResult();
1479     }
1480 
1481     // Cache the result of this top-level module lookup for later.
1482     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1483   }
1484 
1485   // If we never found the module, fail.
1486   if (!Module)
1487     return ModuleLoadResult();
1488 
1489   // Verify that the rest of the module path actually corresponds to
1490   // a submodule.
1491   if (Path.size() > 1) {
1492     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1493       StringRef Name = Path[I].first->getName();
1494       clang::Module *Sub = Module->findSubmodule(Name);
1495 
1496       if (!Sub) {
1497         // Attempt to perform typo correction to find a module name that works.
1498         SmallVector<StringRef, 2> Best;
1499         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1500 
1501         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1502                                             JEnd = Module->submodule_end();
1503              J != JEnd; ++J) {
1504           unsigned ED = Name.edit_distance((*J)->Name,
1505                                            /*AllowReplacements=*/true,
1506                                            BestEditDistance);
1507           if (ED <= BestEditDistance) {
1508             if (ED < BestEditDistance) {
1509               Best.clear();
1510               BestEditDistance = ED;
1511             }
1512 
1513             Best.push_back((*J)->Name);
1514           }
1515         }
1516 
1517         // If there was a clear winner, user it.
1518         if (Best.size() == 1) {
1519           getDiagnostics().Report(Path[I].second,
1520                                   diag::err_no_submodule_suggest)
1521             << Path[I].first << Module->getFullModuleName() << Best[0]
1522             << SourceRange(Path[0].second, Path[I-1].second)
1523             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1524                                             Best[0]);
1525 
1526           Sub = Module->findSubmodule(Best[0]);
1527         }
1528       }
1529 
1530       if (!Sub) {
1531         // No submodule by this name. Complain, and don't look for further
1532         // submodules.
1533         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1534           << Path[I].first << Module->getFullModuleName()
1535           << SourceRange(Path[0].second, Path[I-1].second);
1536         break;
1537       }
1538 
1539       Module = Sub;
1540     }
1541   }
1542 
1543   // Don't make the module visible if we are in the implementation.
1544   if (ModuleName == getLangOpts().ImplementationOfModule)
1545     return ModuleLoadResult(Module, false);
1546 
1547   // Make the named module visible, if it's not already part of the module
1548   // we are parsing.
1549   if (ModuleName != getLangOpts().CurrentModule) {
1550     if (!Module->IsFromModuleFile) {
1551       // We have an umbrella header or directory that doesn't actually include
1552       // all of the headers within the directory it covers. Complain about
1553       // this missing submodule and recover by forgetting that we ever saw
1554       // this submodule.
1555       // FIXME: Should we detect this at module load time? It seems fairly
1556       // expensive (and rare).
1557       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1558         << Module->getFullModuleName()
1559         << SourceRange(Path.front().second, Path.back().second);
1560 
1561       return ModuleLoadResult(nullptr, true);
1562     }
1563 
1564     // Check whether this module is available.
1565     clang::Module::Requirement Requirement;
1566     clang::Module::UnresolvedHeaderDirective MissingHeader;
1567     if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
1568                              MissingHeader)) {
1569       if (MissingHeader.FileNameLoc.isValid()) {
1570         getDiagnostics().Report(MissingHeader.FileNameLoc,
1571                                 diag::err_module_header_missing)
1572           << MissingHeader.IsUmbrella << MissingHeader.FileName;
1573       } else {
1574         getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1575           << Module->getFullModuleName()
1576           << Requirement.second << Requirement.first
1577           << SourceRange(Path.front().second, Path.back().second);
1578       }
1579       LastModuleImportLoc = ImportLoc;
1580       LastModuleImportResult = ModuleLoadResult();
1581       return ModuleLoadResult();
1582     }
1583 
1584     ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
1585                                      /*Complain=*/true);
1586   }
1587 
1588   // Check for any configuration macros that have changed.
1589   clang::Module *TopModule = Module->getTopLevelModule();
1590   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1591     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
1592                      Module, ImportLoc);
1593   }
1594 
1595   // Determine whether we're in the #include buffer for a module. The #includes
1596   // in that buffer do not qualify as module imports; they're just an
1597   // implementation detail of us building the module.
1598   bool IsInModuleIncludes = !getLangOpts().CurrentModule.empty() &&
1599                             getSourceManager().getFileID(ImportLoc) ==
1600                                 getSourceManager().getMainFileID();
1601 
1602   // If this module import was due to an inclusion directive, create an
1603   // implicit import declaration to capture it in the AST.
1604   if (IsInclusionDirective && hasASTContext() && !IsInModuleIncludes) {
1605     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1606     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
1607                                                      ImportLoc, Module,
1608                                                      Path.back().second);
1609     TU->addDecl(ImportD);
1610     if (Consumer)
1611       Consumer->HandleImplicitImportDecl(ImportD);
1612   }
1613 
1614   LastModuleImportLoc = ImportLoc;
1615   LastModuleImportResult = ModuleLoadResult(Module, false);
1616   return LastModuleImportResult;
1617 }
1618 
1619 void CompilerInstance::makeModuleVisible(Module *Mod,
1620                                          Module::NameVisibilityKind Visibility,
1621                                          SourceLocation ImportLoc,
1622                                          bool Complain){
1623   ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
1624 }
1625 
1626 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
1627     SourceLocation TriggerLoc) {
1628   if (!ModuleManager)
1629     createModuleManager();
1630   // Can't do anything if we don't have the module manager.
1631   if (!ModuleManager)
1632     return nullptr;
1633   // Get an existing global index.  This loads it if not already
1634   // loaded.
1635   ModuleManager->loadGlobalIndex();
1636   GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1637   // If the global index doesn't exist, create it.
1638   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
1639       hasPreprocessor()) {
1640     llvm::sys::fs::create_directories(
1641       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1642     GlobalModuleIndex::writeIndex(
1643       getFileManager(),
1644       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1645     ModuleManager->resetForReload();
1646     ModuleManager->loadGlobalIndex();
1647     GlobalIndex = ModuleManager->getGlobalIndex();
1648   }
1649   // For finding modules needing to be imported for fixit messages,
1650   // we need to make the global index cover all modules, so we do that here.
1651   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
1652     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1653     bool RecreateIndex = false;
1654     for (ModuleMap::module_iterator I = MMap.module_begin(),
1655         E = MMap.module_end(); I != E; ++I) {
1656       Module *TheModule = I->second;
1657       const FileEntry *Entry = TheModule->getASTFile();
1658       if (!Entry) {
1659         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1660         Path.push_back(std::make_pair(
1661 				  getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
1662         std::reverse(Path.begin(), Path.end());
1663 		    // Load a module as hidden.  This also adds it to the global index.
1664         loadModule(TheModule->DefinitionLoc, Path,
1665                                              Module::Hidden, false);
1666         RecreateIndex = true;
1667       }
1668     }
1669     if (RecreateIndex) {
1670       GlobalModuleIndex::writeIndex(
1671         getFileManager(),
1672         getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1673       ModuleManager->resetForReload();
1674       ModuleManager->loadGlobalIndex();
1675       GlobalIndex = ModuleManager->getGlobalIndex();
1676     }
1677     HaveFullGlobalModuleIndex = true;
1678   }
1679   return GlobalIndex;
1680 }
1681 
1682 // Check global module index for missing imports.
1683 bool
1684 CompilerInstance::lookupMissingImports(StringRef Name,
1685                                        SourceLocation TriggerLoc) {
1686   // Look for the symbol in non-imported modules, but only if an error
1687   // actually occurred.
1688   if (!buildingModule()) {
1689     // Load global module index, or retrieve a previously loaded one.
1690     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
1691       TriggerLoc);
1692 
1693     // Only if we have a global index.
1694     if (GlobalIndex) {
1695       GlobalModuleIndex::HitSet FoundModules;
1696 
1697       // Find the modules that reference the identifier.
1698       // Note that this only finds top-level modules.
1699       // We'll let diagnoseTypo find the actual declaration module.
1700       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
1701         return true;
1702     }
1703   }
1704 
1705   return false;
1706 }
1707 void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); }
1708