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