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