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