xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision 71de0b61cb8b70f1c5662bc5252b9d62c060e28e)
1 //===--- CompilerInstance.cpp ---------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Frontend/CompilerInstance.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Basic/Version.h"
19 #include "clang/Config/config.h"
20 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
21 #include "clang/Frontend/FrontendAction.h"
22 #include "clang/Frontend/FrontendActions.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "clang/Frontend/LogDiagnosticPrinter.h"
25 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
26 #include "clang/Frontend/TextDiagnosticPrinter.h"
27 #include "clang/Frontend/Utils.h"
28 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
29 #include "clang/Lex/HeaderSearch.h"
30 #include "clang/Lex/PTHManager.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CodeCompleteConsumer.h"
33 #include "clang/Sema/Sema.h"
34 #include "clang/Serialization/ASTReader.h"
35 #include "clang/Serialization/GlobalModuleIndex.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/CrashRecoveryContext.h"
38 #include "llvm/Support/Errc.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/LockFileManager.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Program.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <sys/stat.h>
49 #include <system_error>
50 #include <time.h>
51 
52 using namespace clang;
53 
54 CompilerInstance::CompilerInstance(bool BuildingModule)
55   : ModuleLoader(BuildingModule),
56     Invocation(new CompilerInvocation()), ModuleManager(nullptr),
57     BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false),
58     ModuleBuildFailed(false) {
59 }
60 
61 CompilerInstance::~CompilerInstance() {
62   assert(OutputFiles.empty() && "Still output files in flight?");
63 }
64 
65 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
66   Invocation = Value;
67 }
68 
69 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
70   return (BuildGlobalModuleIndex ||
71           (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
72            getFrontendOpts().GenerateGlobalModuleIndex)) &&
73          !ModuleBuildFailed;
74 }
75 
76 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
77   Diagnostics = Value;
78 }
79 
80 void CompilerInstance::setTarget(TargetInfo *Value) {
81   Target = Value;
82 }
83 
84 void CompilerInstance::setFileManager(FileManager *Value) {
85   FileMgr = Value;
86   if (Value)
87     VirtualFileSystem = Value->getVirtualFileSystem();
88   else
89     VirtualFileSystem.reset();
90 }
91 
92 void CompilerInstance::setSourceManager(SourceManager *Value) {
93   SourceMgr = Value;
94 }
95 
96 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
97 
98 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
99 
100 void CompilerInstance::setSema(Sema *S) {
101   TheSema.reset(S);
102 }
103 
104 void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
105   Consumer.reset(Value);
106 }
107 
108 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
109   CompletionConsumer.reset(Value);
110 }
111 
112 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
113   return ModuleManager;
114 }
115 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
116   ModuleManager = Reader;
117 }
118 
119 // Diagnostics
120 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
121                                const CodeGenOptions *CodeGenOpts,
122                                DiagnosticsEngine &Diags) {
123   std::string ErrorInfo;
124   bool OwnsStream = false;
125   raw_ostream *OS = &llvm::errs();
126   if (DiagOpts->DiagnosticLogFile != "-") {
127     // Create the output stream.
128     llvm::raw_fd_ostream *FileOS(new llvm::raw_fd_ostream(
129         DiagOpts->DiagnosticLogFile.c_str(), ErrorInfo,
130         llvm::sys::fs::F_Append | llvm::sys::fs::F_Text));
131     if (!ErrorInfo.empty()) {
132       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
133         << DiagOpts->DiagnosticLogFile << ErrorInfo;
134     } else {
135       FileOS->SetUnbuffered();
136       FileOS->SetUseAtomicWrites(true);
137       OS = FileOS;
138       OwnsStream = true;
139     }
140   }
141 
142   // Chain in the diagnostic client which will log the diagnostics.
143   LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
144                                                           OwnsStream);
145   if (CodeGenOpts)
146     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
147   Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
148 }
149 
150 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
151                                        DiagnosticsEngine &Diags,
152                                        StringRef OutputFile) {
153   std::string ErrorInfo;
154   std::unique_ptr<llvm::raw_fd_ostream> OS;
155   OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
156                                     llvm::sys::fs::F_None));
157 
158   if (!ErrorInfo.empty()) {
159     Diags.Report(diag::warn_fe_serialized_diag_failure)
160       << OutputFile << ErrorInfo;
161     return;
162   }
163 
164   DiagnosticConsumer *SerializedConsumer =
165       clang::serialized_diags::create(OS.release(), DiagOpts);
166 
167   Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
168                                                 SerializedConsumer));
169 }
170 
171 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
172                                          bool ShouldOwnClient) {
173   Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
174                                   ShouldOwnClient, &getCodeGenOpts());
175 }
176 
177 IntrusiveRefCntPtr<DiagnosticsEngine>
178 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
179                                     DiagnosticConsumer *Client,
180                                     bool ShouldOwnClient,
181                                     const CodeGenOptions *CodeGenOpts) {
182   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
183   IntrusiveRefCntPtr<DiagnosticsEngine>
184       Diags(new DiagnosticsEngine(DiagID, Opts));
185 
186   // Create the diagnostic client for reporting errors or for
187   // implementing -verify.
188   if (Client) {
189     Diags->setClient(Client, ShouldOwnClient);
190   } else
191     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
192 
193   // Chain in -verify checker, if requested.
194   if (Opts->VerifyDiagnostics)
195     Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
196 
197   // Chain in -diagnostic-log-file dumper, if requested.
198   if (!Opts->DiagnosticLogFile.empty())
199     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
200 
201   if (!Opts->DiagnosticSerializationFile.empty())
202     SetupSerializedDiagnostics(Opts, *Diags,
203                                Opts->DiagnosticSerializationFile);
204 
205   // Configure our handling of diagnostics.
206   ProcessWarningOptions(*Diags, *Opts);
207 
208   return Diags;
209 }
210 
211 // File Manager
212 
213 void CompilerInstance::createFileManager() {
214   if (!hasVirtualFileSystem()) {
215     // TODO: choose the virtual file system based on the CompilerInvocation.
216     setVirtualFileSystem(vfs::getRealFileSystem());
217   }
218   FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
219 }
220 
221 // Source Manager
222 
223 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
224   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
225 }
226 
227 // Preprocessor
228 
229 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
230   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
231 
232   // Create a PTH manager if we are using some form of a token cache.
233   PTHManager *PTHMgr = nullptr;
234   if (!PPOpts.TokenCache.empty())
235     PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
236 
237   // Create the Preprocessor.
238   HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
239                                               getSourceManager(),
240                                               getDiagnostics(),
241                                               getLangOpts(),
242                                               &getTarget());
243   PP = new Preprocessor(&getPreprocessorOpts(), getDiagnostics(), getLangOpts(),
244                         getSourceManager(), *HeaderInfo, *this, PTHMgr,
245                         /*OwnsHeaderSearch=*/true, TUKind);
246   PP->Initialize(getTarget());
247 
248   // Note that this is different then passing PTHMgr to Preprocessor's ctor.
249   // That argument is used as the IdentifierInfoLookup argument to
250   // IdentifierTable's ctor.
251   if (PTHMgr) {
252     PTHMgr->setPreprocessor(&*PP);
253     PP->setPTHManager(PTHMgr);
254   }
255 
256   if (PPOpts.DetailedRecord)
257     PP->createPreprocessingRecord();
258 
259   InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
260 
261   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
262 
263   // Set up the module path, including the hash for the
264   // module-creation options.
265   SmallString<256> SpecificModuleCache(
266                            getHeaderSearchOpts().ModuleCachePath);
267   if (!getHeaderSearchOpts().DisableModuleHash)
268     llvm::sys::path::append(SpecificModuleCache,
269                             getInvocation().getModuleHash());
270   PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
271 
272   // Handle generating dependencies, if requested.
273   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
274   if (!DepOpts.OutputFile.empty())
275     TheDependencyFileGenerator.reset(
276         DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
277   if (!DepOpts.DOTOutputFile.empty())
278     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
279                              getHeaderSearchOpts().Sysroot);
280 
281 
282   // Handle generating header include information, if requested.
283   if (DepOpts.ShowHeaderIncludes)
284     AttachHeaderIncludeGen(*PP);
285   if (!DepOpts.HeaderIncludeOutputFile.empty()) {
286     StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
287     if (OutputPath == "-")
288       OutputPath = "";
289     AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
290                            /*ShowDepth=*/false);
291   }
292 
293   if (DepOpts.PrintShowIncludes) {
294     AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"",
295                            /*ShowDepth=*/true, /*MSStyle=*/true);
296   }
297 }
298 
299 // ASTContext
300 
301 void CompilerInstance::createASTContext() {
302   Preprocessor &PP = getPreprocessor();
303   Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
304                            PP.getIdentifierTable(), PP.getSelectorTable(),
305                            PP.getBuiltinInfo());
306   Context->InitBuiltinTypes(getTarget());
307 }
308 
309 // ExternalASTSource
310 
311 void CompilerInstance::createPCHExternalASTSource(
312     StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
313     void *DeserializationListener, bool OwnDeserializationListener) {
314   IntrusiveRefCntPtr<ExternalASTSource> Source;
315   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
316   Source = createPCHExternalASTSource(
317       Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
318       AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
319       DeserializationListener, OwnDeserializationListener, Preamble,
320       getFrontendOpts().UseGlobalModuleIndex);
321   ModuleManager = static_cast<ASTReader*>(Source.getPtr());
322   getASTContext().setExternalSource(Source);
323 }
324 
325 ExternalASTSource *CompilerInstance::createPCHExternalASTSource(
326     StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
327     bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
328     void *DeserializationListener, bool OwnDeserializationListener,
329     bool Preamble, bool UseGlobalModuleIndex) {
330   HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
331 
332   std::unique_ptr<ASTReader> Reader;
333   Reader.reset(new ASTReader(PP, Context,
334                              Sysroot.empty() ? "" : Sysroot.c_str(),
335                              DisablePCHValidation,
336                              AllowPCHWithCompilerErrors,
337                              /*AllowConfigurationMismatch*/false,
338                              HSOpts.ModulesValidateSystemHeaders,
339                              UseGlobalModuleIndex));
340 
341   Reader->setDeserializationListener(
342       static_cast<ASTDeserializationListener *>(DeserializationListener),
343       /*TakeOwnership=*/OwnDeserializationListener);
344   switch (Reader->ReadAST(Path,
345                           Preamble ? serialization::MK_Preamble
346                                    : serialization::MK_PCH,
347                           SourceLocation(),
348                           ASTReader::ARR_None)) {
349   case ASTReader::Success:
350     // Set the predefines buffer as suggested by the PCH reader. Typically, the
351     // predefines buffer will be empty.
352     PP.setPredefines(Reader->getSuggestedPredefines());
353     return Reader.release();
354 
355   case ASTReader::Failure:
356     // Unrecoverable failure: don't even try to process the input file.
357     break;
358 
359   case ASTReader::Missing:
360   case ASTReader::OutOfDate:
361   case ASTReader::VersionMismatch:
362   case ASTReader::ConfigurationMismatch:
363   case ASTReader::HadErrors:
364     // No suitable PCH file could be found. Return an error.
365     break;
366   }
367 
368   return nullptr;
369 }
370 
371 // Code Completion
372 
373 static bool EnableCodeCompletion(Preprocessor &PP,
374                                  const std::string &Filename,
375                                  unsigned Line,
376                                  unsigned Column) {
377   // Tell the source manager to chop off the given file at a specific
378   // line and column.
379   const FileEntry *Entry = PP.getFileManager().getFile(Filename);
380   if (!Entry) {
381     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
382       << Filename;
383     return true;
384   }
385 
386   // Truncate the named file at the given line/column.
387   PP.SetCodeCompletionPoint(Entry, Line, Column);
388   return false;
389 }
390 
391 void CompilerInstance::createCodeCompletionConsumer() {
392   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
393   if (!CompletionConsumer) {
394     setCodeCompletionConsumer(
395       createCodeCompletionConsumer(getPreprocessor(),
396                                    Loc.FileName, Loc.Line, Loc.Column,
397                                    getFrontendOpts().CodeCompleteOpts,
398                                    llvm::outs()));
399     if (!CompletionConsumer)
400       return;
401   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
402                                   Loc.Line, Loc.Column)) {
403     setCodeCompletionConsumer(nullptr);
404     return;
405   }
406 
407   if (CompletionConsumer->isOutputBinary() &&
408       llvm::sys::ChangeStdoutToBinary()) {
409     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
410     setCodeCompletionConsumer(nullptr);
411   }
412 }
413 
414 void CompilerInstance::createFrontendTimer() {
415   FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
416 }
417 
418 CodeCompleteConsumer *
419 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
420                                                const std::string &Filename,
421                                                unsigned Line,
422                                                unsigned Column,
423                                                const CodeCompleteOptions &Opts,
424                                                raw_ostream &OS) {
425   if (EnableCodeCompletion(PP, Filename, Line, Column))
426     return nullptr;
427 
428   // Set up the creation routine for code-completion.
429   return new PrintingCodeCompleteConsumer(Opts, OS);
430 }
431 
432 void CompilerInstance::createSema(TranslationUnitKind TUKind,
433                                   CodeCompleteConsumer *CompletionConsumer) {
434   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
435                          TUKind, CompletionConsumer));
436 }
437 
438 // Output Files
439 
440 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
441   assert(OutFile.OS && "Attempt to add empty stream to output list!");
442   OutputFiles.push_back(OutFile);
443 }
444 
445 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
446   for (std::list<OutputFile>::iterator
447          it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
448     delete it->OS;
449     if (!it->TempFilename.empty()) {
450       if (EraseFiles) {
451         llvm::sys::fs::remove(it->TempFilename);
452       } else {
453         SmallString<128> NewOutFile(it->Filename);
454 
455         // If '-working-directory' was passed, the output filename should be
456         // relative to that.
457         FileMgr->FixupRelativePath(NewOutFile);
458         if (std::error_code ec =
459                 llvm::sys::fs::rename(it->TempFilename, NewOutFile.str())) {
460           getDiagnostics().Report(diag::err_unable_to_rename_temp)
461             << it->TempFilename << it->Filename << ec.message();
462 
463           llvm::sys::fs::remove(it->TempFilename);
464         }
465       }
466     } else if (!it->Filename.empty() && EraseFiles)
467       llvm::sys::fs::remove(it->Filename);
468 
469   }
470   OutputFiles.clear();
471 }
472 
473 llvm::raw_fd_ostream *
474 CompilerInstance::createDefaultOutputFile(bool Binary,
475                                           StringRef InFile,
476                                           StringRef Extension) {
477   return createOutputFile(getFrontendOpts().OutputFile, Binary,
478                           /*RemoveFileOnSignal=*/true, InFile, Extension,
479                           /*UseTemporary=*/true);
480 }
481 
482 llvm::raw_null_ostream *CompilerInstance::createNullOutputFile() {
483   llvm::raw_null_ostream *OS = new llvm::raw_null_ostream();
484   addOutputFile(OutputFile("", "", OS));
485   return OS;
486 }
487 
488 llvm::raw_fd_ostream *
489 CompilerInstance::createOutputFile(StringRef OutputPath,
490                                    bool Binary, bool RemoveFileOnSignal,
491                                    StringRef InFile,
492                                    StringRef Extension,
493                                    bool UseTemporary,
494                                    bool CreateMissingDirectories) {
495   std::string Error, OutputPathName, TempPathName;
496   llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
497                                               RemoveFileOnSignal,
498                                               InFile, Extension,
499                                               UseTemporary,
500                                               CreateMissingDirectories,
501                                               &OutputPathName,
502                                               &TempPathName);
503   if (!OS) {
504     getDiagnostics().Report(diag::err_fe_unable_to_open_output)
505       << OutputPath << Error;
506     return nullptr;
507   }
508 
509   // Add the output file -- but don't try to remove "-", since this means we are
510   // using stdin.
511   addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
512                 TempPathName, OS));
513 
514   return OS;
515 }
516 
517 llvm::raw_fd_ostream *
518 CompilerInstance::createOutputFile(StringRef OutputPath,
519                                    std::string &Error,
520                                    bool Binary,
521                                    bool RemoveFileOnSignal,
522                                    StringRef InFile,
523                                    StringRef Extension,
524                                    bool UseTemporary,
525                                    bool CreateMissingDirectories,
526                                    std::string *ResultPathName,
527                                    std::string *TempPathName) {
528   assert((!CreateMissingDirectories || UseTemporary) &&
529          "CreateMissingDirectories is only allowed when using temporary files");
530 
531   std::string OutFile, TempFile;
532   if (!OutputPath.empty()) {
533     OutFile = OutputPath;
534   } else if (InFile == "-") {
535     OutFile = "-";
536   } else if (!Extension.empty()) {
537     SmallString<128> Path(InFile);
538     llvm::sys::path::replace_extension(Path, Extension);
539     OutFile = Path.str();
540   } else {
541     OutFile = "-";
542   }
543 
544   std::unique_ptr<llvm::raw_fd_ostream> OS;
545   std::string OSFile;
546 
547   if (UseTemporary) {
548     if (OutFile == "-")
549       UseTemporary = false;
550     else {
551       llvm::sys::fs::file_status Status;
552       llvm::sys::fs::status(OutputPath, Status);
553       if (llvm::sys::fs::exists(Status)) {
554         // Fail early if we can't write to the final destination.
555         if (!llvm::sys::fs::can_write(OutputPath))
556           return nullptr;
557 
558         // Don't use a temporary if the output is a special file. This handles
559         // things like '-o /dev/null'
560         if (!llvm::sys::fs::is_regular_file(Status))
561           UseTemporary = false;
562       }
563     }
564   }
565 
566   if (UseTemporary) {
567     // Create a temporary file.
568     SmallString<128> TempPath;
569     TempPath = OutFile;
570     TempPath += "-%%%%%%%%";
571     int fd;
572     std::error_code EC =
573         llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
574 
575     if (CreateMissingDirectories &&
576         EC == llvm::errc::no_such_file_or_directory) {
577       StringRef Parent = llvm::sys::path::parent_path(OutputPath);
578       EC = llvm::sys::fs::create_directories(Parent);
579       if (!EC) {
580         EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
581       }
582     }
583 
584     if (!EC) {
585       OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
586       OSFile = TempFile = TempPath.str();
587     }
588     // If we failed to create the temporary, fallback to writing to the file
589     // directly. This handles the corner case where we cannot write to the
590     // directory, but can write to the file.
591   }
592 
593   if (!OS) {
594     OSFile = OutFile;
595     OS.reset(new llvm::raw_fd_ostream(
596         OSFile.c_str(), Error,
597         (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
598     if (!Error.empty())
599       return nullptr;
600   }
601 
602   // Make sure the out stream file gets removed if we crash.
603   if (RemoveFileOnSignal)
604     llvm::sys::RemoveFileOnSignal(OSFile);
605 
606   if (ResultPathName)
607     *ResultPathName = OutFile;
608   if (TempPathName)
609     *TempPathName = TempFile;
610 
611   return OS.release();
612 }
613 
614 // Initialization Utilities
615 
616 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
617   return InitializeSourceManager(Input, getDiagnostics(),
618                                  getFileManager(), getSourceManager(),
619                                  getFrontendOpts());
620 }
621 
622 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
623                                                DiagnosticsEngine &Diags,
624                                                FileManager &FileMgr,
625                                                SourceManager &SourceMgr,
626                                                const FrontendOptions &Opts) {
627   SrcMgr::CharacteristicKind
628     Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
629 
630   if (Input.isBuffer()) {
631     SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
632     assert(!SourceMgr.getMainFileID().isInvalid() &&
633            "Couldn't establish MainFileID!");
634     return true;
635   }
636 
637   StringRef InputFile = Input.getFile();
638 
639   // Figure out where to get and map in the main file.
640   if (InputFile != "-") {
641     const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
642     if (!File) {
643       Diags.Report(diag::err_fe_error_reading) << InputFile;
644       return false;
645     }
646 
647     // The natural SourceManager infrastructure can't currently handle named
648     // pipes, but we would at least like to accept them for the main
649     // file. Detect them here, read them with the volatile flag so FileMgr will
650     // pick up the correct size, and simply override their contents as we do for
651     // STDIN.
652     if (File->isNamedPipe()) {
653       std::string ErrorStr;
654       if (llvm::MemoryBuffer *MB =
655               FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true)) {
656         // Create a new virtual file that will have the correct size.
657         File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0);
658         SourceMgr.overrideFileContents(File, MB);
659       } else {
660         Diags.Report(diag::err_cannot_open_file) << InputFile << ErrorStr;
661         return false;
662       }
663     }
664 
665     SourceMgr.setMainFileID(
666         SourceMgr.createFileID(File, SourceLocation(), Kind));
667   } else {
668     std::unique_ptr<llvm::MemoryBuffer> SB;
669     if (std::error_code ec = llvm::MemoryBuffer::getSTDIN(SB)) {
670       Diags.Report(diag::err_fe_error_reading_stdin) << ec.message();
671       return false;
672     }
673     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
674                                                    SB->getBufferSize(), 0);
675     SourceMgr.setMainFileID(
676         SourceMgr.createFileID(File, SourceLocation(), Kind));
677     SourceMgr.overrideFileContents(File, SB.release());
678   }
679 
680   assert(!SourceMgr.getMainFileID().isInvalid() &&
681          "Couldn't establish MainFileID!");
682   return true;
683 }
684 
685 // High-Level Operations
686 
687 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
688   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
689   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
690   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
691 
692   // FIXME: Take this as an argument, once all the APIs we used have moved to
693   // taking it as an input instead of hard-coding llvm::errs.
694   raw_ostream &OS = llvm::errs();
695 
696   // Create the target instance.
697   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), &getTargetOpts()));
698   if (!hasTarget())
699     return false;
700 
701   // Inform the target of the language options.
702   //
703   // FIXME: We shouldn't need to do this, the target should be immutable once
704   // created. This complexity should be lifted elsewhere.
705   getTarget().setForcedLangOptions(getLangOpts());
706 
707   // rewriter project will change target built-in bool type from its default.
708   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
709     getTarget().noSignedCharForObjCBool();
710 
711   // Validate/process some options.
712   if (getHeaderSearchOpts().Verbose)
713     OS << "clang -cc1 version " CLANG_VERSION_STRING
714        << " based upon " << BACKEND_PACKAGE_STRING
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   std::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