xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision dbdc036858b04a888cd855e270187bdd03c31353)
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 bool compileAndLoadModule(CompilerInstance &ImportingInstance,
900                                  SourceLocation ImportLoc,
901                                  SourceLocation ModuleNameLoc,
902                                  Module *Module,
903                                  StringRef ModuleFileName) {
904   // FIXME: have LockFileManager return an error_code so that we can
905   // avoid the mkdir when the directory already exists.
906   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
907   llvm::sys::fs::create_directories(Dir);
908 
909   while (1) {
910     unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
911     llvm::LockFileManager Locked(ModuleFileName);
912     switch (Locked) {
913     case llvm::LockFileManager::LFS_Error:
914       return false;
915 
916     case llvm::LockFileManager::LFS_Owned:
917       // We're responsible for building the module ourselves.
918       // FIXME: if there are errors, don't attempt to load the module.
919       compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
920                         ModuleFileName);
921       break;
922 
923     case llvm::LockFileManager::LFS_Shared:
924       // Someone else is responsible for building the module. Wait for them to
925       // finish.
926       if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied)
927         continue; // try again to get the lock.
928       ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
929       break;
930     }
931 
932     // Try to read the module file, now that we've compiled it.
933     ASTReader::ASTReadResult ReadResult =
934         ImportingInstance.getModuleManager()->ReadAST(
935             ModuleFileName, serialization::MK_Module, ImportLoc,
936             ModuleLoadCapabilities);
937 
938     if (ReadResult == ASTReader::OutOfDate &&
939         Locked == llvm::LockFileManager::LFS_Shared) {
940       // The module may be out of date in the presence of file system races,
941       // or if one of its imports depends on header search paths that are not
942       // consistent with this ImportingInstance.  Try again...
943       continue;
944     } else if (ReadResult == ASTReader::Missing) {
945       ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
946                                                 diag::err_module_not_built)
947           << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
948     }
949     return ReadResult == ASTReader::Success;
950   }
951 }
952 
953 /// \brief Diagnose differences between the current definition of the given
954 /// configuration macro and the definition provided on the command line.
955 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
956                              Module *Mod, SourceLocation ImportLoc) {
957   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
958   SourceManager &SourceMgr = PP.getSourceManager();
959 
960   // If this identifier has never had a macro definition, then it could
961   // not have changed.
962   if (!Id->hadMacroDefinition())
963     return;
964 
965   // If this identifier does not currently have a macro definition,
966   // check whether it had one on the command line.
967   if (!Id->hasMacroDefinition()) {
968     MacroDirective::DefInfo LatestDef =
969         PP.getMacroDirectiveHistory(Id)->getDefinition();
970     for (MacroDirective::DefInfo Def = LatestDef; Def;
971            Def = Def.getPreviousDefinition()) {
972       FileID FID = SourceMgr.getFileID(Def.getLocation());
973       if (FID.isInvalid())
974         continue;
975 
976       // We only care about the predefines buffer.
977       if (FID != PP.getPredefinesFileID())
978         continue;
979 
980       // This macro was defined on the command line, then #undef'd later.
981       // Complain.
982       PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
983         << true << ConfigMacro << Mod->getFullModuleName();
984       if (LatestDef.isUndefined())
985         PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
986           << true;
987       return;
988     }
989 
990     // Okay: no definition in the predefines buffer.
991     return;
992   }
993 
994   // This identifier has a macro definition. Check whether we had a definition
995   // on the command line.
996   MacroDirective::DefInfo LatestDef =
997       PP.getMacroDirectiveHistory(Id)->getDefinition();
998   MacroDirective::DefInfo PredefinedDef;
999   for (MacroDirective::DefInfo Def = LatestDef; Def;
1000          Def = Def.getPreviousDefinition()) {
1001     FileID FID = SourceMgr.getFileID(Def.getLocation());
1002     if (FID.isInvalid())
1003       continue;
1004 
1005     // We only care about the predefines buffer.
1006     if (FID != PP.getPredefinesFileID())
1007       continue;
1008 
1009     PredefinedDef = Def;
1010     break;
1011   }
1012 
1013   // If there was no definition for this macro in the predefines buffer,
1014   // complain.
1015   if (!PredefinedDef ||
1016       (!PredefinedDef.getLocation().isValid() &&
1017        PredefinedDef.getUndefLocation().isValid())) {
1018     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1019       << false << ConfigMacro << Mod->getFullModuleName();
1020     PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
1021       << false;
1022     return;
1023   }
1024 
1025   // If the current macro definition is the same as the predefined macro
1026   // definition, it's okay.
1027   if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
1028       LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
1029                                               /*Syntactically=*/true))
1030     return;
1031 
1032   // The macro definitions differ.
1033   PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1034     << false << ConfigMacro << Mod->getFullModuleName();
1035   PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
1036     << false;
1037 }
1038 
1039 /// \brief Write a new timestamp file with the given path.
1040 static void writeTimestampFile(StringRef TimestampFile) {
1041   std::string ErrorInfo;
1042   llvm::raw_fd_ostream Out(TimestampFile.str().c_str(), ErrorInfo,
1043                            llvm::sys::fs::F_None);
1044 }
1045 
1046 /// \brief Prune the module cache of modules that haven't been accessed in
1047 /// a long time.
1048 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1049   struct stat StatBuf;
1050   llvm::SmallString<128> TimestampFile;
1051   TimestampFile = HSOpts.ModuleCachePath;
1052   llvm::sys::path::append(TimestampFile, "modules.timestamp");
1053 
1054   // Try to stat() the timestamp file.
1055   if (::stat(TimestampFile.c_str(), &StatBuf)) {
1056     // If the timestamp file wasn't there, create one now.
1057     if (errno == ENOENT) {
1058       writeTimestampFile(TimestampFile);
1059     }
1060     return;
1061   }
1062 
1063   // Check whether the time stamp is older than our pruning interval.
1064   // If not, do nothing.
1065   time_t TimeStampModTime = StatBuf.st_mtime;
1066   time_t CurrentTime = time(nullptr);
1067   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1068     return;
1069 
1070   // Write a new timestamp file so that nobody else attempts to prune.
1071   // There is a benign race condition here, if two Clang instances happen to
1072   // notice at the same time that the timestamp is out-of-date.
1073   writeTimestampFile(TimestampFile);
1074 
1075   // Walk the entire module cache, looking for unused module files and module
1076   // indices.
1077   std::error_code EC;
1078   SmallString<128> ModuleCachePathNative;
1079   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1080   for (llvm::sys::fs::directory_iterator
1081          Dir(ModuleCachePathNative.str(), EC), DirEnd;
1082        Dir != DirEnd && !EC; Dir.increment(EC)) {
1083     // If we don't have a directory, there's nothing to look into.
1084     if (!llvm::sys::fs::is_directory(Dir->path()))
1085       continue;
1086 
1087     // Walk all of the files within this directory.
1088     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1089          File != FileEnd && !EC; File.increment(EC)) {
1090       // We only care about module and global module index files.
1091       StringRef Extension = llvm::sys::path::extension(File->path());
1092       if (Extension != ".pcm" && Extension != ".timestamp" &&
1093           llvm::sys::path::filename(File->path()) != "modules.idx")
1094         continue;
1095 
1096       // Look at this file. If we can't stat it, there's nothing interesting
1097       // there.
1098       if (::stat(File->path().c_str(), &StatBuf))
1099         continue;
1100 
1101       // If the file has been used recently enough, leave it there.
1102       time_t FileAccessTime = StatBuf.st_atime;
1103       if (CurrentTime - FileAccessTime <=
1104               time_t(HSOpts.ModuleCachePruneAfter)) {
1105         continue;
1106       }
1107 
1108       // Remove the file.
1109       llvm::sys::fs::remove(File->path());
1110 
1111       // Remove the timestamp file.
1112       std::string TimpestampFilename = File->path() + ".timestamp";
1113       llvm::sys::fs::remove(TimpestampFilename);
1114     }
1115 
1116     // If we removed all of the files in the directory, remove the directory
1117     // itself.
1118     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1119             llvm::sys::fs::directory_iterator() && !EC)
1120       llvm::sys::fs::remove(Dir->path());
1121   }
1122 }
1123 
1124 void CompilerInstance::createModuleManager() {
1125   if (!ModuleManager) {
1126     if (!hasASTContext())
1127       createASTContext();
1128 
1129     // If we're not recursively building a module, check whether we
1130     // need to prune the module cache.
1131     if (getSourceManager().getModuleBuildStack().empty() &&
1132         getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1133         getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1134       pruneModuleCache(getHeaderSearchOpts());
1135     }
1136 
1137     HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1138     std::string Sysroot = HSOpts.Sysroot;
1139     const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1140     ModuleManager = new ASTReader(getPreprocessor(), *Context,
1141                                   Sysroot.empty() ? "" : Sysroot.c_str(),
1142                                   PPOpts.DisablePCHValidation,
1143                                   /*AllowASTWithCompilerErrors=*/false,
1144                                   /*AllowConfigurationMismatch=*/false,
1145                                   HSOpts.ModulesValidateSystemHeaders,
1146                                   getFrontendOpts().UseGlobalModuleIndex);
1147     if (hasASTConsumer()) {
1148       ModuleManager->setDeserializationListener(
1149         getASTConsumer().GetASTDeserializationListener());
1150       getASTContext().setASTMutationListener(
1151         getASTConsumer().GetASTMutationListener());
1152     }
1153     getASTContext().setExternalSource(ModuleManager);
1154     if (hasSema())
1155       ModuleManager->InitializeSema(getSema());
1156     if (hasASTConsumer())
1157       ModuleManager->StartTranslationUnit(&getASTConsumer());
1158   }
1159 }
1160 
1161 ModuleLoadResult
1162 CompilerInstance::loadModule(SourceLocation ImportLoc,
1163                              ModuleIdPath Path,
1164                              Module::NameVisibilityKind Visibility,
1165                              bool IsInclusionDirective) {
1166   // Determine what file we're searching from.
1167   StringRef ModuleName = Path[0].first->getName();
1168   SourceLocation ModuleNameLoc = Path[0].second;
1169 
1170   // If we've already handled this import, just return the cached result.
1171   // This one-element cache is important to eliminate redundant diagnostics
1172   // when both the preprocessor and parser see the same import declaration.
1173   if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
1174     // Make the named module visible.
1175     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1176       ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1177                                        ImportLoc, /*Complain=*/false);
1178     return LastModuleImportResult;
1179   }
1180 
1181   clang::Module *Module = nullptr;
1182 
1183   // If we don't already have information on this module, load the module now.
1184   llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1185     = KnownModules.find(Path[0].first);
1186   if (Known != KnownModules.end()) {
1187     // Retrieve the cached top-level module.
1188     Module = Known->second;
1189   } else if (ModuleName == getLangOpts().CurrentModule) {
1190     // This is the module we're building.
1191     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1192     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1193   } else {
1194     // Search for a module with the given name.
1195     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1196     if (!Module) {
1197       getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1198       << ModuleName
1199       << SourceRange(ImportLoc, ModuleNameLoc);
1200       ModuleBuildFailed = true;
1201       return ModuleLoadResult();
1202     }
1203 
1204     std::string ModuleFileName =
1205         PP->getHeaderSearchInfo().getModuleFileName(Module);
1206 
1207     // If we don't already have an ASTReader, create one now.
1208     if (!ModuleManager)
1209       createModuleManager();
1210 
1211     if (TheDependencyFileGenerator)
1212       TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
1213 
1214     // Try to load the module file.
1215     unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
1216     switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module,
1217                                    ImportLoc, ARRFlags)) {
1218     case ASTReader::Success:
1219       break;
1220 
1221     case ASTReader::OutOfDate:
1222     case ASTReader::Missing: {
1223       // The module file is missing or out-of-date. Build it.
1224       assert(Module && "missing module file");
1225       // Check whether there is a cycle in the module graph.
1226       ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1227       ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1228       for (; Pos != PosEnd; ++Pos) {
1229         if (Pos->first == ModuleName)
1230           break;
1231       }
1232 
1233       if (Pos != PosEnd) {
1234         SmallString<256> CyclePath;
1235         for (; Pos != PosEnd; ++Pos) {
1236           CyclePath += Pos->first;
1237           CyclePath += " -> ";
1238         }
1239         CyclePath += ModuleName;
1240 
1241         getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1242           << ModuleName << CyclePath;
1243         return ModuleLoadResult();
1244       }
1245 
1246       getDiagnostics().Report(ImportLoc, diag::remark_module_build)
1247           << ModuleName << ModuleFileName;
1248 
1249       // Check whether we have already attempted to build this module (but
1250       // failed).
1251       if (getPreprocessorOpts().FailedModules &&
1252           getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1253         getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1254           << ModuleName
1255           << SourceRange(ImportLoc, ModuleNameLoc);
1256         ModuleBuildFailed = true;
1257         return ModuleLoadResult();
1258       }
1259 
1260       // Try to compile and then load the module.
1261       if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
1262                                 ModuleFileName)) {
1263         if (getPreprocessorOpts().FailedModules)
1264           getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1265         KnownModules[Path[0].first] = nullptr;
1266         ModuleBuildFailed = true;
1267         return ModuleLoadResult();
1268       }
1269 
1270       // Okay, we've rebuilt and now loaded the module.
1271       break;
1272     }
1273 
1274     case ASTReader::VersionMismatch:
1275     case ASTReader::ConfigurationMismatch:
1276     case ASTReader::HadErrors:
1277       ModuleLoader::HadFatalFailure = true;
1278       // FIXME: The ASTReader will already have complained, but can we showhorn
1279       // that diagnostic information into a more useful form?
1280       KnownModules[Path[0].first] = nullptr;
1281       return ModuleLoadResult();
1282 
1283     case ASTReader::Failure:
1284       ModuleLoader::HadFatalFailure = true;
1285       // Already complained, but note now that we failed.
1286       KnownModules[Path[0].first] = nullptr;
1287       ModuleBuildFailed = true;
1288       return ModuleLoadResult();
1289     }
1290 
1291     // Cache the result of this top-level module lookup for later.
1292     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1293   }
1294 
1295   // If we never found the module, fail.
1296   if (!Module)
1297     return ModuleLoadResult();
1298 
1299   // Verify that the rest of the module path actually corresponds to
1300   // a submodule.
1301   if (Path.size() > 1) {
1302     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1303       StringRef Name = Path[I].first->getName();
1304       clang::Module *Sub = Module->findSubmodule(Name);
1305 
1306       if (!Sub) {
1307         // Attempt to perform typo correction to find a module name that works.
1308         SmallVector<StringRef, 2> Best;
1309         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1310 
1311         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1312                                             JEnd = Module->submodule_end();
1313              J != JEnd; ++J) {
1314           unsigned ED = Name.edit_distance((*J)->Name,
1315                                            /*AllowReplacements=*/true,
1316                                            BestEditDistance);
1317           if (ED <= BestEditDistance) {
1318             if (ED < BestEditDistance) {
1319               Best.clear();
1320               BestEditDistance = ED;
1321             }
1322 
1323             Best.push_back((*J)->Name);
1324           }
1325         }
1326 
1327         // If there was a clear winner, user it.
1328         if (Best.size() == 1) {
1329           getDiagnostics().Report(Path[I].second,
1330                                   diag::err_no_submodule_suggest)
1331             << Path[I].first << Module->getFullModuleName() << Best[0]
1332             << SourceRange(Path[0].second, Path[I-1].second)
1333             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1334                                             Best[0]);
1335 
1336           Sub = Module->findSubmodule(Best[0]);
1337         }
1338       }
1339 
1340       if (!Sub) {
1341         // No submodule by this name. Complain, and don't look for further
1342         // submodules.
1343         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1344           << Path[I].first << Module->getFullModuleName()
1345           << SourceRange(Path[0].second, Path[I-1].second);
1346         break;
1347       }
1348 
1349       Module = Sub;
1350     }
1351   }
1352 
1353   // Make the named module visible, if it's not already part of the module
1354   // we are parsing.
1355   if (ModuleName != getLangOpts().CurrentModule) {
1356     if (!Module->IsFromModuleFile) {
1357       // We have an umbrella header or directory that doesn't actually include
1358       // all of the headers within the directory it covers. Complain about
1359       // this missing submodule and recover by forgetting that we ever saw
1360       // this submodule.
1361       // FIXME: Should we detect this at module load time? It seems fairly
1362       // expensive (and rare).
1363       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1364         << Module->getFullModuleName()
1365         << SourceRange(Path.front().second, Path.back().second);
1366 
1367       return ModuleLoadResult(nullptr, true);
1368     }
1369 
1370     // Check whether this module is available.
1371     clang::Module::Requirement Requirement;
1372     clang::Module::HeaderDirective MissingHeader;
1373     if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
1374                              MissingHeader)) {
1375       if (MissingHeader.FileNameLoc.isValid()) {
1376         getDiagnostics().Report(MissingHeader.FileNameLoc,
1377                                 diag::err_module_header_missing)
1378           << MissingHeader.IsUmbrella << MissingHeader.FileName;
1379       } else {
1380         getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1381           << Module->getFullModuleName()
1382           << Requirement.second << Requirement.first
1383           << SourceRange(Path.front().second, Path.back().second);
1384       }
1385       LastModuleImportLoc = ImportLoc;
1386       LastModuleImportResult = ModuleLoadResult();
1387       return ModuleLoadResult();
1388     }
1389 
1390     ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
1391                                      /*Complain=*/true);
1392   }
1393 
1394   // Check for any configuration macros that have changed.
1395   clang::Module *TopModule = Module->getTopLevelModule();
1396   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1397     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
1398                      Module, ImportLoc);
1399   }
1400 
1401   // If this module import was due to an inclusion directive, create an
1402   // implicit import declaration to capture it in the AST.
1403   if (IsInclusionDirective && hasASTContext()) {
1404     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1405     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
1406                                                      ImportLoc, Module,
1407                                                      Path.back().second);
1408     TU->addDecl(ImportD);
1409     if (Consumer)
1410       Consumer->HandleImplicitImportDecl(ImportD);
1411   }
1412 
1413   LastModuleImportLoc = ImportLoc;
1414   LastModuleImportResult = ModuleLoadResult(Module, false);
1415   return LastModuleImportResult;
1416 }
1417 
1418 void CompilerInstance::makeModuleVisible(Module *Mod,
1419                                          Module::NameVisibilityKind Visibility,
1420                                          SourceLocation ImportLoc,
1421                                          bool Complain){
1422   ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
1423 }
1424 
1425 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
1426     SourceLocation TriggerLoc) {
1427   if (!ModuleManager)
1428     createModuleManager();
1429   // Can't do anything if we don't have the module manager.
1430   if (!ModuleManager)
1431     return nullptr;
1432   // Get an existing global index.  This loads it if not already
1433   // loaded.
1434   ModuleManager->loadGlobalIndex();
1435   GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1436   // If the global index doesn't exist, create it.
1437   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
1438       hasPreprocessor()) {
1439     llvm::sys::fs::create_directories(
1440       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1441     GlobalModuleIndex::writeIndex(
1442       getFileManager(),
1443       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1444     ModuleManager->resetForReload();
1445     ModuleManager->loadGlobalIndex();
1446     GlobalIndex = ModuleManager->getGlobalIndex();
1447   }
1448   // For finding modules needing to be imported for fixit messages,
1449   // we need to make the global index cover all modules, so we do that here.
1450   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
1451     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1452     bool RecreateIndex = false;
1453     for (ModuleMap::module_iterator I = MMap.module_begin(),
1454         E = MMap.module_end(); I != E; ++I) {
1455       Module *TheModule = I->second;
1456       const FileEntry *Entry = TheModule->getASTFile();
1457       if (!Entry) {
1458         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1459         Path.push_back(std::make_pair(
1460 				  getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
1461         std::reverse(Path.begin(), Path.end());
1462 		    // Load a module as hidden.  This also adds it to the global index.
1463         loadModule(TheModule->DefinitionLoc, Path,
1464                                              Module::Hidden, false);
1465         RecreateIndex = true;
1466       }
1467     }
1468     if (RecreateIndex) {
1469       GlobalModuleIndex::writeIndex(
1470         getFileManager(),
1471         getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1472       ModuleManager->resetForReload();
1473       ModuleManager->loadGlobalIndex();
1474       GlobalIndex = ModuleManager->getGlobalIndex();
1475     }
1476     HaveFullGlobalModuleIndex = true;
1477   }
1478   return GlobalIndex;
1479 }
1480 
1481 // Check global module index for missing imports.
1482 bool
1483 CompilerInstance::lookupMissingImports(StringRef Name,
1484                                        SourceLocation TriggerLoc) {
1485   // Look for the symbol in non-imported modules, but only if an error
1486   // actually occurred.
1487   if (!buildingModule()) {
1488     // Load global module index, or retrieve a previously loaded one.
1489     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
1490       TriggerLoc);
1491 
1492     // Only if we have a global index.
1493     if (GlobalIndex) {
1494       GlobalModuleIndex::HitSet FoundModules;
1495 
1496       // Find the modules that reference the identifier.
1497       // Note that this only finds top-level modules.
1498       // We'll let diagnoseTypo find the actual declaration module.
1499       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
1500         return true;
1501     }
1502   }
1503 
1504   return false;
1505 }
1506