• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- CompilerInstance.cpp ---------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Frontend/CompilerInstance.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Basic/Version.h"
19 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
20 #include "clang/Frontend/FrontendAction.h"
21 #include "clang/Frontend/FrontendActions.h"
22 #include "clang/Frontend/FrontendDiagnostic.h"
23 #include "clang/Frontend/LogDiagnosticPrinter.h"
24 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
25 #include "clang/Frontend/TextDiagnosticPrinter.h"
26 #include "clang/Frontend/Utils.h"
27 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
28 #include "clang/Lex/HeaderSearch.h"
29 #include "clang/Lex/PTHManager.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CodeCompleteConsumer.h"
32 #include "clang/Sema/Sema.h"
33 #include "clang/Serialization/ASTReader.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Config/config.h"
36 #include "llvm/Support/CrashRecoveryContext.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/LockFileManager.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Support/system_error.h"
47 
48 using namespace clang;
49 
CompilerInstance()50 CompilerInstance::CompilerInstance()
51   : Invocation(new CompilerInvocation()), ModuleManager(0),
52     BuildGlobalModuleIndex(false), ModuleBuildFailed(false) {
53 }
54 
~CompilerInstance()55 CompilerInstance::~CompilerInstance() {
56   assert(OutputFiles.empty() && "Still output files in flight?");
57 }
58 
setInvocation(CompilerInvocation * Value)59 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
60   Invocation = Value;
61 }
62 
shouldBuildGlobalModuleIndex() const63 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
64   return (BuildGlobalModuleIndex ||
65           (ModuleManager && ModuleManager->isGlobalIndexUnavailable())) &&
66          !ModuleBuildFailed;
67 }
68 
setDiagnostics(DiagnosticsEngine * Value)69 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
70   Diagnostics = Value;
71 }
72 
setTarget(TargetInfo * Value)73 void CompilerInstance::setTarget(TargetInfo *Value) {
74   Target = Value;
75 }
76 
setFileManager(FileManager * Value)77 void CompilerInstance::setFileManager(FileManager *Value) {
78   FileMgr = Value;
79 }
80 
setSourceManager(SourceManager * Value)81 void CompilerInstance::setSourceManager(SourceManager *Value) {
82   SourceMgr = Value;
83 }
84 
setPreprocessor(Preprocessor * Value)85 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
86 
setASTContext(ASTContext * Value)87 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
88 
setSema(Sema * S)89 void CompilerInstance::setSema(Sema *S) {
90   TheSema.reset(S);
91 }
92 
setASTConsumer(ASTConsumer * Value)93 void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
94   Consumer.reset(Value);
95 }
96 
setCodeCompletionConsumer(CodeCompleteConsumer * Value)97 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
98   CompletionConsumer.reset(Value);
99 }
100 
101 // Diagnostics
SetUpDiagnosticLog(DiagnosticOptions * DiagOpts,const CodeGenOptions * CodeGenOpts,DiagnosticsEngine & Diags)102 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
103                                const CodeGenOptions *CodeGenOpts,
104                                DiagnosticsEngine &Diags) {
105   std::string ErrorInfo;
106   bool OwnsStream = false;
107   raw_ostream *OS = &llvm::errs();
108   if (DiagOpts->DiagnosticLogFile != "-") {
109     // Create the output stream.
110     llvm::raw_fd_ostream *FileOS(
111       new llvm::raw_fd_ostream(DiagOpts->DiagnosticLogFile.c_str(),
112                                ErrorInfo, llvm::raw_fd_ostream::F_Append));
113     if (!ErrorInfo.empty()) {
114       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
115         << DiagOpts->DiagnosticLogFile << ErrorInfo;
116     } else {
117       FileOS->SetUnbuffered();
118       FileOS->SetUseAtomicWrites(true);
119       OS = FileOS;
120       OwnsStream = true;
121     }
122   }
123 
124   // Chain in the diagnostic client which will log the diagnostics.
125   LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
126                                                           OwnsStream);
127   if (CodeGenOpts)
128     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
129   Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
130 }
131 
SetupSerializedDiagnostics(DiagnosticOptions * DiagOpts,DiagnosticsEngine & Diags,StringRef OutputFile)132 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
133                                        DiagnosticsEngine &Diags,
134                                        StringRef OutputFile) {
135   std::string ErrorInfo;
136   OwningPtr<llvm::raw_fd_ostream> OS;
137   OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
138                                     llvm::raw_fd_ostream::F_Binary));
139 
140   if (!ErrorInfo.empty()) {
141     Diags.Report(diag::warn_fe_serialized_diag_failure)
142       << OutputFile << ErrorInfo;
143     return;
144   }
145 
146   DiagnosticConsumer *SerializedConsumer =
147     clang::serialized_diags::create(OS.take(), DiagOpts);
148 
149 
150   Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
151                                                 SerializedConsumer));
152 }
153 
createDiagnostics(DiagnosticConsumer * Client,bool ShouldOwnClient,bool ShouldCloneClient)154 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
155                                          bool ShouldOwnClient,
156                                          bool ShouldCloneClient) {
157   Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
158                                   ShouldOwnClient, ShouldCloneClient,
159                                   &getCodeGenOpts());
160 }
161 
162 IntrusiveRefCntPtr<DiagnosticsEngine>
createDiagnostics(DiagnosticOptions * Opts,DiagnosticConsumer * Client,bool ShouldOwnClient,bool ShouldCloneClient,const CodeGenOptions * CodeGenOpts)163 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
164                                     DiagnosticConsumer *Client,
165                                     bool ShouldOwnClient,
166                                     bool ShouldCloneClient,
167                                     const CodeGenOptions *CodeGenOpts) {
168   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
169   IntrusiveRefCntPtr<DiagnosticsEngine>
170       Diags(new DiagnosticsEngine(DiagID, Opts));
171 
172   // Create the diagnostic client for reporting errors or for
173   // implementing -verify.
174   if (Client) {
175     if (ShouldCloneClient)
176       Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
177     else
178       Diags->setClient(Client, ShouldOwnClient);
179   } else
180     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
181 
182   // Chain in -verify checker, if requested.
183   if (Opts->VerifyDiagnostics)
184     Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
185 
186   // Chain in -diagnostic-log-file dumper, if requested.
187   if (!Opts->DiagnosticLogFile.empty())
188     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
189 
190   if (!Opts->DiagnosticSerializationFile.empty())
191     SetupSerializedDiagnostics(Opts, *Diags,
192                                Opts->DiagnosticSerializationFile);
193 
194   // Configure our handling of diagnostics.
195   ProcessWarningOptions(*Diags, *Opts);
196 
197   return Diags;
198 }
199 
200 // File Manager
201 
createFileManager()202 void CompilerInstance::createFileManager() {
203   FileMgr = new FileManager(getFileSystemOpts());
204 }
205 
206 // Source Manager
207 
createSourceManager(FileManager & FileMgr)208 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
209   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
210 }
211 
212 // Preprocessor
213 
createPreprocessor()214 void CompilerInstance::createPreprocessor() {
215   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
216 
217   // Create a PTH manager if we are using some form of a token cache.
218   PTHManager *PTHMgr = 0;
219   if (!PPOpts.TokenCache.empty())
220     PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
221 
222   // Create the Preprocessor.
223   HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
224                                               getFileManager(),
225                                               getDiagnostics(),
226                                               getLangOpts(),
227                                               &getTarget());
228   PP = new Preprocessor(&getPreprocessorOpts(),
229                         getDiagnostics(), getLangOpts(), &getTarget(),
230                         getSourceManager(), *HeaderInfo, *this, PTHMgr,
231                         /*OwnsHeaderSearch=*/true);
232 
233   // Note that this is different then passing PTHMgr to Preprocessor's ctor.
234   // That argument is used as the IdentifierInfoLookup argument to
235   // IdentifierTable's ctor.
236   if (PTHMgr) {
237     PTHMgr->setPreprocessor(&*PP);
238     PP->setPTHManager(PTHMgr);
239   }
240 
241   if (PPOpts.DetailedRecord)
242     PP->createPreprocessingRecord();
243 
244   InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
245 
246   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
247 
248   // Set up the module path, including the hash for the
249   // module-creation options.
250   SmallString<256> SpecificModuleCache(
251                            getHeaderSearchOpts().ModuleCachePath);
252   if (!getHeaderSearchOpts().DisableModuleHash)
253     llvm::sys::path::append(SpecificModuleCache,
254                             getInvocation().getModuleHash());
255   PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
256 
257   // Handle generating dependencies, if requested.
258   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
259   if (!DepOpts.OutputFile.empty())
260     AttachDependencyFileGen(*PP, DepOpts);
261   if (!DepOpts.DOTOutputFile.empty())
262     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
263                              getHeaderSearchOpts().Sysroot);
264 
265 
266   // Handle generating header include information, if requested.
267   if (DepOpts.ShowHeaderIncludes)
268     AttachHeaderIncludeGen(*PP);
269   if (!DepOpts.HeaderIncludeOutputFile.empty()) {
270     StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
271     if (OutputPath == "-")
272       OutputPath = "";
273     AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
274                            /*ShowDepth=*/false);
275   }
276 }
277 
278 // ASTContext
279 
createASTContext()280 void CompilerInstance::createASTContext() {
281   Preprocessor &PP = getPreprocessor();
282   Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
283                            &getTarget(), PP.getIdentifierTable(),
284                            PP.getSelectorTable(), PP.getBuiltinInfo(),
285                            /*size_reserve=*/ 0);
286 }
287 
288 // ExternalASTSource
289 
createPCHExternalASTSource(StringRef Path,bool DisablePCHValidation,bool AllowPCHWithCompilerErrors,void * DeserializationListener)290 void CompilerInstance::createPCHExternalASTSource(StringRef Path,
291                                                   bool DisablePCHValidation,
292                                                 bool AllowPCHWithCompilerErrors,
293                                                  void *DeserializationListener){
294   OwningPtr<ExternalASTSource> Source;
295   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
296   Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
297                                           DisablePCHValidation,
298                                           AllowPCHWithCompilerErrors,
299                                           getPreprocessor(), getASTContext(),
300                                           DeserializationListener,
301                                           Preamble,
302                                        getFrontendOpts().UseGlobalModuleIndex));
303   ModuleManager = static_cast<ASTReader*>(Source.get());
304   getASTContext().setExternalSource(Source);
305 }
306 
307 ExternalASTSource *
createPCHExternalASTSource(StringRef Path,const std::string & Sysroot,bool DisablePCHValidation,bool AllowPCHWithCompilerErrors,Preprocessor & PP,ASTContext & Context,void * DeserializationListener,bool Preamble,bool UseGlobalModuleIndex)308 CompilerInstance::createPCHExternalASTSource(StringRef Path,
309                                              const std::string &Sysroot,
310                                              bool DisablePCHValidation,
311                                              bool AllowPCHWithCompilerErrors,
312                                              Preprocessor &PP,
313                                              ASTContext &Context,
314                                              void *DeserializationListener,
315                                              bool Preamble,
316                                              bool UseGlobalModuleIndex) {
317   OwningPtr<ASTReader> Reader;
318   Reader.reset(new ASTReader(PP, Context,
319                              Sysroot.empty() ? "" : Sysroot.c_str(),
320                              DisablePCHValidation,
321                              AllowPCHWithCompilerErrors,
322                              UseGlobalModuleIndex));
323 
324   Reader->setDeserializationListener(
325             static_cast<ASTDeserializationListener *>(DeserializationListener));
326   switch (Reader->ReadAST(Path,
327                           Preamble ? serialization::MK_Preamble
328                                    : serialization::MK_PCH,
329                           SourceLocation(),
330                           ASTReader::ARR_None)) {
331   case ASTReader::Success:
332     // Set the predefines buffer as suggested by the PCH reader. Typically, the
333     // predefines buffer will be empty.
334     PP.setPredefines(Reader->getSuggestedPredefines());
335     return Reader.take();
336 
337   case ASTReader::Failure:
338     // Unrecoverable failure: don't even try to process the input file.
339     break;
340 
341   case ASTReader::OutOfDate:
342   case ASTReader::VersionMismatch:
343   case ASTReader::ConfigurationMismatch:
344   case ASTReader::HadErrors:
345     // No suitable PCH file could be found. Return an error.
346     break;
347   }
348 
349   return 0;
350 }
351 
352 // Code Completion
353 
EnableCodeCompletion(Preprocessor & PP,const std::string & Filename,unsigned Line,unsigned Column)354 static bool EnableCodeCompletion(Preprocessor &PP,
355                                  const std::string &Filename,
356                                  unsigned Line,
357                                  unsigned Column) {
358   // Tell the source manager to chop off the given file at a specific
359   // line and column.
360   const FileEntry *Entry = PP.getFileManager().getFile(Filename);
361   if (!Entry) {
362     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
363       << Filename;
364     return true;
365   }
366 
367   // Truncate the named file at the given line/column.
368   PP.SetCodeCompletionPoint(Entry, Line, Column);
369   return false;
370 }
371 
createCodeCompletionConsumer()372 void CompilerInstance::createCodeCompletionConsumer() {
373   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
374   if (!CompletionConsumer) {
375     setCodeCompletionConsumer(
376       createCodeCompletionConsumer(getPreprocessor(),
377                                    Loc.FileName, Loc.Line, Loc.Column,
378                                    getFrontendOpts().CodeCompleteOpts,
379                                    llvm::outs()));
380     if (!CompletionConsumer)
381       return;
382   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
383                                   Loc.Line, Loc.Column)) {
384     setCodeCompletionConsumer(0);
385     return;
386   }
387 
388   if (CompletionConsumer->isOutputBinary() &&
389       llvm::sys::Program::ChangeStdoutToBinary()) {
390     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
391     setCodeCompletionConsumer(0);
392   }
393 }
394 
createFrontendTimer()395 void CompilerInstance::createFrontendTimer() {
396   FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
397 }
398 
399 CodeCompleteConsumer *
createCodeCompletionConsumer(Preprocessor & PP,const std::string & Filename,unsigned Line,unsigned Column,const CodeCompleteOptions & Opts,raw_ostream & OS)400 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
401                                                const std::string &Filename,
402                                                unsigned Line,
403                                                unsigned Column,
404                                                const CodeCompleteOptions &Opts,
405                                                raw_ostream &OS) {
406   if (EnableCodeCompletion(PP, Filename, Line, Column))
407     return 0;
408 
409   // Set up the creation routine for code-completion.
410   return new PrintingCodeCompleteConsumer(Opts, OS);
411 }
412 
createSema(TranslationUnitKind TUKind,CodeCompleteConsumer * CompletionConsumer)413 void CompilerInstance::createSema(TranslationUnitKind TUKind,
414                                   CodeCompleteConsumer *CompletionConsumer) {
415   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
416                          TUKind, CompletionConsumer));
417 }
418 
419 // Output Files
420 
addOutputFile(const OutputFile & OutFile)421 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
422   assert(OutFile.OS && "Attempt to add empty stream to output list!");
423   OutputFiles.push_back(OutFile);
424 }
425 
clearOutputFiles(bool EraseFiles)426 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
427   for (std::list<OutputFile>::iterator
428          it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
429     delete it->OS;
430     if (!it->TempFilename.empty()) {
431       if (EraseFiles) {
432         bool existed;
433         llvm::sys::fs::remove(it->TempFilename, existed);
434       } else {
435         SmallString<128> NewOutFile(it->Filename);
436 
437         // If '-working-directory' was passed, the output filename should be
438         // relative to that.
439         FileMgr->FixupRelativePath(NewOutFile);
440         if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
441                                                         NewOutFile.str())) {
442           getDiagnostics().Report(diag::err_unable_to_rename_temp)
443             << it->TempFilename << it->Filename << ec.message();
444 
445           bool existed;
446           llvm::sys::fs::remove(it->TempFilename, existed);
447         }
448       }
449     } else if (!it->Filename.empty() && EraseFiles)
450       llvm::sys::Path(it->Filename).eraseFromDisk();
451 
452   }
453   OutputFiles.clear();
454 }
455 
456 llvm::raw_fd_ostream *
createDefaultOutputFile(bool Binary,StringRef InFile,StringRef Extension)457 CompilerInstance::createDefaultOutputFile(bool Binary,
458                                           StringRef InFile,
459                                           StringRef Extension) {
460   return createOutputFile(getFrontendOpts().OutputFile, Binary,
461                           /*RemoveFileOnSignal=*/true, InFile, Extension,
462                           /*UseTemporary=*/true);
463 }
464 
465 llvm::raw_fd_ostream *
createOutputFile(StringRef OutputPath,bool Binary,bool RemoveFileOnSignal,StringRef InFile,StringRef Extension,bool UseTemporary,bool CreateMissingDirectories)466 CompilerInstance::createOutputFile(StringRef OutputPath,
467                                    bool Binary, bool RemoveFileOnSignal,
468                                    StringRef InFile,
469                                    StringRef Extension,
470                                    bool UseTemporary,
471                                    bool CreateMissingDirectories) {
472   std::string Error, OutputPathName, TempPathName;
473   llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
474                                               RemoveFileOnSignal,
475                                               InFile, Extension,
476                                               UseTemporary,
477                                               CreateMissingDirectories,
478                                               &OutputPathName,
479                                               &TempPathName);
480   if (!OS) {
481     getDiagnostics().Report(diag::err_fe_unable_to_open_output)
482       << OutputPath << Error;
483     return 0;
484   }
485 
486   // Add the output file -- but don't try to remove "-", since this means we are
487   // using stdin.
488   addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
489                 TempPathName, OS));
490 
491   return OS;
492 }
493 
494 llvm::raw_fd_ostream *
createOutputFile(StringRef OutputPath,std::string & Error,bool Binary,bool RemoveFileOnSignal,StringRef InFile,StringRef Extension,bool UseTemporary,bool CreateMissingDirectories,std::string * ResultPathName,std::string * TempPathName)495 CompilerInstance::createOutputFile(StringRef OutputPath,
496                                    std::string &Error,
497                                    bool Binary,
498                                    bool RemoveFileOnSignal,
499                                    StringRef InFile,
500                                    StringRef Extension,
501                                    bool UseTemporary,
502                                    bool CreateMissingDirectories,
503                                    std::string *ResultPathName,
504                                    std::string *TempPathName) {
505   assert((!CreateMissingDirectories || UseTemporary) &&
506          "CreateMissingDirectories is only allowed when using temporary files");
507 
508   std::string OutFile, TempFile;
509   if (!OutputPath.empty()) {
510     OutFile = OutputPath;
511   } else if (InFile == "-") {
512     OutFile = "-";
513   } else if (!Extension.empty()) {
514     llvm::sys::Path Path(InFile);
515     Path.eraseSuffix();
516     Path.appendSuffix(Extension);
517     OutFile = Path.str();
518   } else {
519     OutFile = "-";
520   }
521 
522   OwningPtr<llvm::raw_fd_ostream> OS;
523   std::string OSFile;
524 
525   if (UseTemporary && OutFile != "-") {
526     // Only create the temporary if the parent directory exists (or create
527     // missing directories is true) and we can actually write to OutPath,
528     // otherwise we want to fail early.
529     SmallString<256> AbsPath(OutputPath);
530     llvm::sys::fs::make_absolute(AbsPath);
531     llvm::sys::Path OutPath(AbsPath);
532     bool ParentExists = false;
533     if (llvm::sys::fs::exists(llvm::sys::path::parent_path(AbsPath.str()),
534                               ParentExists))
535       ParentExists = false;
536     bool Exists;
537     if ((CreateMissingDirectories || ParentExists) &&
538         ((llvm::sys::fs::exists(AbsPath.str(), Exists) || !Exists) ||
539          (OutPath.isRegularFile() && OutPath.canWrite()))) {
540       // Create a temporary file.
541       SmallString<128> TempPath;
542       TempPath = OutFile;
543       TempPath += "-%%%%%%%%";
544       int fd;
545       if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
546                                      /*makeAbsolute=*/false, 0664)
547           == llvm::errc::success) {
548         OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
549         OSFile = TempFile = TempPath.str();
550       }
551     }
552   }
553 
554   if (!OS) {
555     OSFile = OutFile;
556     OS.reset(
557       new llvm::raw_fd_ostream(OSFile.c_str(), Error,
558                                (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
559     if (!Error.empty())
560       return 0;
561   }
562 
563   // Make sure the out stream file gets removed if we crash.
564   if (RemoveFileOnSignal)
565     llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
566 
567   if (ResultPathName)
568     *ResultPathName = OutFile;
569   if (TempPathName)
570     *TempPathName = TempFile;
571 
572   return OS.take();
573 }
574 
575 // Initialization Utilities
576 
InitializeSourceManager(const FrontendInputFile & Input)577 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
578   return InitializeSourceManager(Input, getDiagnostics(),
579                                  getFileManager(), getSourceManager(),
580                                  getFrontendOpts());
581 }
582 
InitializeSourceManager(const FrontendInputFile & Input,DiagnosticsEngine & Diags,FileManager & FileMgr,SourceManager & SourceMgr,const FrontendOptions & Opts)583 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
584                                                DiagnosticsEngine &Diags,
585                                                FileManager &FileMgr,
586                                                SourceManager &SourceMgr,
587                                                const FrontendOptions &Opts) {
588   SrcMgr::CharacteristicKind
589     Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
590 
591   if (Input.isBuffer()) {
592     SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind);
593     assert(!SourceMgr.getMainFileID().isInvalid() &&
594            "Couldn't establish MainFileID!");
595     return true;
596   }
597 
598   StringRef InputFile = Input.getFile();
599 
600   // Figure out where to get and map in the main file.
601   if (InputFile != "-") {
602     const FileEntry *File = FileMgr.getFile(InputFile);
603     if (!File) {
604       Diags.Report(diag::err_fe_error_reading) << InputFile;
605       return false;
606     }
607 
608     // The natural SourceManager infrastructure can't currently handle named
609     // pipes, but we would at least like to accept them for the main
610     // file. Detect them here, read them with the more generic MemoryBuffer
611     // function, and simply override their contents as we do for STDIN.
612     if (File->isNamedPipe()) {
613       OwningPtr<llvm::MemoryBuffer> MB;
614       if (llvm::error_code ec = llvm::MemoryBuffer::getFile(InputFile, MB)) {
615         Diags.Report(diag::err_cannot_open_file) << InputFile << ec.message();
616         return false;
617       }
618 
619       // Create a new virtual file that will have the correct size.
620       File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0);
621       SourceMgr.overrideFileContents(File, MB.take());
622     }
623 
624     SourceMgr.createMainFileID(File, Kind);
625   } else {
626     OwningPtr<llvm::MemoryBuffer> SB;
627     if (llvm::MemoryBuffer::getSTDIN(SB)) {
628       // FIXME: Give ec.message() in this diag.
629       Diags.Report(diag::err_fe_error_reading_stdin);
630       return false;
631     }
632     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
633                                                    SB->getBufferSize(), 0);
634     SourceMgr.createMainFileID(File, Kind);
635     SourceMgr.overrideFileContents(File, SB.take());
636   }
637 
638   assert(!SourceMgr.getMainFileID().isInvalid() &&
639          "Couldn't establish MainFileID!");
640   return true;
641 }
642 
643 // High-Level Operations
644 
ExecuteAction(FrontendAction & Act)645 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
646   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
647   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
648   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
649 
650   // FIXME: Take this as an argument, once all the APIs we used have moved to
651   // taking it as an input instead of hard-coding llvm::errs.
652   raw_ostream &OS = llvm::errs();
653 
654   // Create the target instance.
655   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), &getTargetOpts()));
656   if (!hasTarget())
657     return false;
658 
659   // Inform the target of the language options.
660   //
661   // FIXME: We shouldn't need to do this, the target should be immutable once
662   // created. This complexity should be lifted elsewhere.
663   getTarget().setForcedLangOptions(getLangOpts());
664 
665   // rewriter project will change target built-in bool type from its default.
666   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
667     getTarget().noSignedCharForObjCBool();
668 
669   // Validate/process some options.
670   if (getHeaderSearchOpts().Verbose)
671     OS << "clang -cc1 version " CLANG_VERSION_STRING
672        << " based upon " << PACKAGE_STRING
673        << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
674 
675   if (getFrontendOpts().ShowTimers)
676     createFrontendTimer();
677 
678   if (getFrontendOpts().ShowStats)
679     llvm::EnableStatistics();
680 
681   for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
682     // Reset the ID tables if we are reusing the SourceManager.
683     if (hasSourceManager())
684       getSourceManager().clearIDTables();
685 
686     if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
687       Act.Execute();
688       Act.EndSourceFile();
689     }
690   }
691 
692   // Notify the diagnostic client that all files were processed.
693   getDiagnostics().getClient()->finish();
694 
695   if (getDiagnosticOpts().ShowCarets) {
696     // We can have multiple diagnostics sharing one diagnostic client.
697     // Get the total number of warnings/errors from the client.
698     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
699     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
700 
701     if (NumWarnings)
702       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
703     if (NumWarnings && NumErrors)
704       OS << " and ";
705     if (NumErrors)
706       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
707     if (NumWarnings || NumErrors)
708       OS << " generated.\n";
709   }
710 
711   if (getFrontendOpts().ShowStats && hasFileManager()) {
712     getFileManager().PrintStats();
713     OS << "\n";
714   }
715 
716   return !getDiagnostics().getClient()->getNumErrors();
717 }
718 
719 /// \brief Determine the appropriate source input kind based on language
720 /// options.
getSourceInputKindFromOptions(const LangOptions & LangOpts)721 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
722   if (LangOpts.OpenCL)
723     return IK_OpenCL;
724   if (LangOpts.CUDA)
725     return IK_CUDA;
726   if (LangOpts.ObjC1)
727     return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
728   return LangOpts.CPlusPlus? IK_CXX : IK_C;
729 }
730 
731 namespace {
732   struct CompileModuleMapData {
733     CompilerInstance &Instance;
734     GenerateModuleAction &CreateModuleAction;
735   };
736 }
737 
738 /// \brief Helper function that executes the module-generating action under
739 /// a crash recovery context.
doCompileMapModule(void * UserData)740 static void doCompileMapModule(void *UserData) {
741   CompileModuleMapData &Data
742     = *reinterpret_cast<CompileModuleMapData *>(UserData);
743   Data.Instance.ExecuteAction(Data.CreateModuleAction);
744 }
745 
746 namespace {
747   /// \brief Function object that checks with the given macro definition should
748   /// be removed, because it is one of the ignored macros.
749   class RemoveIgnoredMacro {
750     const HeaderSearchOptions &HSOpts;
751 
752   public:
RemoveIgnoredMacro(const HeaderSearchOptions & HSOpts)753     explicit RemoveIgnoredMacro(const HeaderSearchOptions &HSOpts)
754       : HSOpts(HSOpts) { }
755 
operator ()(const std::pair<std::string,bool> & def) const756     bool operator()(const std::pair<std::string, bool> &def) const {
757       StringRef MacroDef = def.first;
758       return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
759     }
760   };
761 }
762 
763 /// \brief Compile a module file for the given module, using the options
764 /// provided by the importing compiler instance.
compileModule(CompilerInstance & ImportingInstance,SourceLocation ImportLoc,Module * Module,StringRef ModuleFileName)765 static void compileModule(CompilerInstance &ImportingInstance,
766                           SourceLocation ImportLoc,
767                           Module *Module,
768                           StringRef ModuleFileName) {
769   llvm::LockFileManager Locked(ModuleFileName);
770   switch (Locked) {
771   case llvm::LockFileManager::LFS_Error:
772     return;
773 
774   case llvm::LockFileManager::LFS_Owned:
775     // We're responsible for building the module ourselves. Do so below.
776     break;
777 
778   case llvm::LockFileManager::LFS_Shared:
779     // Someone else is responsible for building the module. Wait for them to
780     // finish.
781     Locked.waitForUnlock();
782     return;
783   }
784 
785   ModuleMap &ModMap
786     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
787 
788   // Construct a compiler invocation for creating this module.
789   IntrusiveRefCntPtr<CompilerInvocation> Invocation
790     (new CompilerInvocation(ImportingInstance.getInvocation()));
791 
792   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
793 
794   // For any options that aren't intended to affect how a module is built,
795   // reset them to their default values.
796   Invocation->getLangOpts()->resetNonModularOptions();
797   PPOpts.resetNonModularOptions();
798 
799   // Remove any macro definitions that are explicitly ignored by the module.
800   // They aren't supposed to affect how the module is built anyway.
801   const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
802   PPOpts.Macros.erase(std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
803                                      RemoveIgnoredMacro(HSOpts)),
804                       PPOpts.Macros.end());
805 
806 
807   // Note the name of the module we're building.
808   Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
809 
810   // Make sure that the failed-module structure has been allocated in
811   // the importing instance, and propagate the pointer to the newly-created
812   // instance.
813   PreprocessorOptions &ImportingPPOpts
814     = ImportingInstance.getInvocation().getPreprocessorOpts();
815   if (!ImportingPPOpts.FailedModules)
816     ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
817   PPOpts.FailedModules = ImportingPPOpts.FailedModules;
818 
819   // If there is a module map file, build the module using the module map.
820   // Set up the inputs/outputs so that we build the module from its umbrella
821   // header.
822   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
823   FrontendOpts.OutputFile = ModuleFileName.str();
824   FrontendOpts.DisableFree = false;
825   FrontendOpts.GenerateGlobalModuleIndex = false;
826   FrontendOpts.Inputs.clear();
827   InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
828 
829   // Get or create the module map that we'll use to build this module.
830   SmallString<128> TempModuleMapFileName;
831   if (const FileEntry *ModuleMapFile
832                                   = ModMap.getContainingModuleMapFile(Module)) {
833     // Use the module map where this module resides.
834     FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName(),
835                                                     IK));
836   } else {
837     // Create a temporary module map file.
838     TempModuleMapFileName = Module->Name;
839     TempModuleMapFileName += "-%%%%%%%%.map";
840     int FD;
841     if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
842                                    TempModuleMapFileName,
843                                    /*makeAbsolute=*/true)
844           != llvm::errc::success) {
845       ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
846         << TempModuleMapFileName;
847       return;
848     }
849     // Print the module map to this file.
850     llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
851     Module->print(OS);
852     FrontendOpts.Inputs.push_back(
853       FrontendInputFile(TempModuleMapFileName.str().str(), IK));
854   }
855 
856   // Don't free the remapped file buffers; they are owned by our caller.
857   PPOpts.RetainRemappedFileBuffers = true;
858 
859   Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
860   assert(ImportingInstance.getInvocation().getModuleHash() ==
861          Invocation->getModuleHash() && "Module hash mismatch!");
862 
863   // Construct a compiler instance that will be used to actually create the
864   // module.
865   CompilerInstance Instance;
866   Instance.setInvocation(&*Invocation);
867   Instance.createDiagnostics(&ImportingInstance.getDiagnosticClient(),
868                              /*ShouldOwnClient=*/true,
869                              /*ShouldCloneClient=*/true);
870 
871   // Note that this module is part of the module build stack, so that we
872   // can detect cycles in the module graph.
873   Instance.createFileManager(); // FIXME: Adopt file manager from importer?
874   Instance.createSourceManager(Instance.getFileManager());
875   SourceManager &SourceMgr = Instance.getSourceManager();
876   SourceMgr.setModuleBuildStack(
877     ImportingInstance.getSourceManager().getModuleBuildStack());
878   SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
879     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
880 
881 
882   // Construct a module-generating action.
883   GenerateModuleAction CreateModuleAction;
884 
885   // Execute the action to actually build the module in-place. Use a separate
886   // thread so that we get a stack large enough.
887   const unsigned ThreadStackSize = 8 << 20;
888   llvm::CrashRecoveryContext CRC;
889   CompileModuleMapData Data = { Instance, CreateModuleAction };
890   CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
891 
892   // Delete the temporary module map file.
893   // FIXME: Even though we're executing under crash protection, it would still
894   // be nice to do this with RemoveFileOnSignal when we can. However, that
895   // doesn't make sense for all clients, so clean this up manually.
896   Instance.clearOutputFiles(/*EraseFiles=*/true);
897   if (!TempModuleMapFileName.empty())
898     llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
899 
900   // We've rebuilt a module. If we're allowed to generate or update the global
901   // module index, record that fact in the importing compiler instance.
902   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
903     ImportingInstance.setBuildGlobalModuleIndex(true);
904   }
905 }
906 
907 ModuleLoadResult
loadModule(SourceLocation ImportLoc,ModuleIdPath Path,Module::NameVisibilityKind Visibility,bool IsInclusionDirective)908 CompilerInstance::loadModule(SourceLocation ImportLoc,
909                              ModuleIdPath Path,
910                              Module::NameVisibilityKind Visibility,
911                              bool IsInclusionDirective) {
912   // If we've already handled this import, just return the cached result.
913   // This one-element cache is important to eliminate redundant diagnostics
914   // when both the preprocessor and parser see the same import declaration.
915   if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
916     // Make the named module visible.
917     if (LastModuleImportResult)
918       ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
919                                        ImportLoc);
920     return LastModuleImportResult;
921   }
922 
923   // Determine what file we're searching from.
924   StringRef ModuleName = Path[0].first->getName();
925   SourceLocation ModuleNameLoc = Path[0].second;
926 
927   clang::Module *Module = 0;
928 
929   // If we don't already have information on this module, load the module now.
930   llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
931     = KnownModules.find(Path[0].first);
932   if (Known != KnownModules.end()) {
933     // Retrieve the cached top-level module.
934     Module = Known->second;
935   } else if (ModuleName == getLangOpts().CurrentModule) {
936     // This is the module we're building.
937     Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
938     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
939   } else {
940     // Search for a module with the given name.
941     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
942     std::string ModuleFileName;
943     if (Module) {
944       ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module);
945     } else
946       ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(ModuleName);
947 
948     if (ModuleFileName.empty()) {
949       getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
950         << ModuleName
951         << SourceRange(ImportLoc, ModuleNameLoc);
952       LastModuleImportLoc = ImportLoc;
953       LastModuleImportResult = ModuleLoadResult();
954       return LastModuleImportResult;
955     }
956 
957     const FileEntry *ModuleFile
958       = getFileManager().getFile(ModuleFileName, /*OpenFile=*/false,
959                                  /*CacheFailure=*/false);
960     bool BuildingModule = false;
961     if (!ModuleFile && Module) {
962       // The module is not cached, but we have a module map from which we can
963       // build the module.
964 
965       // Check whether there is a cycle in the module graph.
966       ModuleBuildStack Path = getSourceManager().getModuleBuildStack();
967       ModuleBuildStack::iterator Pos = Path.begin(), PosEnd = Path.end();
968       for (; Pos != PosEnd; ++Pos) {
969         if (Pos->first == ModuleName)
970           break;
971       }
972 
973       if (Pos != PosEnd) {
974         SmallString<256> CyclePath;
975         for (; Pos != PosEnd; ++Pos) {
976           CyclePath += Pos->first;
977           CyclePath += " -> ";
978         }
979         CyclePath += ModuleName;
980 
981         getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
982           << ModuleName << CyclePath;
983         return ModuleLoadResult();
984       }
985 
986       // Check whether we have already attempted to build this module (but
987       // failed).
988       if (getPreprocessorOpts().FailedModules &&
989           getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
990         getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
991           << ModuleName
992           << SourceRange(ImportLoc, ModuleNameLoc);
993         ModuleBuildFailed = true;
994         return ModuleLoadResult();
995       }
996 
997       BuildingModule = true;
998       compileModule(*this, ModuleNameLoc, Module, ModuleFileName);
999       ModuleFile = FileMgr->getFile(ModuleFileName, /*OpenFile=*/false,
1000                                     /*CacheFailure=*/false);
1001 
1002       if (!ModuleFile && getPreprocessorOpts().FailedModules)
1003         getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1004     }
1005 
1006     if (!ModuleFile) {
1007       getDiagnostics().Report(ModuleNameLoc,
1008                               BuildingModule? diag::err_module_not_built
1009                                             : diag::err_module_not_found)
1010         << ModuleName
1011         << SourceRange(ImportLoc, ModuleNameLoc);
1012       ModuleBuildFailed = true;
1013       return ModuleLoadResult();
1014     }
1015 
1016     // If there is already a module file associated with this module, make sure
1017     // it is the same as the module file we're looking for. Otherwise, we
1018     // have two module files for the same module.
1019     if (const FileEntry *CurModuleFile = Module? Module->getASTFile() : 0) {
1020       if (CurModuleFile != ModuleFile) {
1021         getDiagnostics().Report(ModuleNameLoc, diag::err_module_file_conflict)
1022           << ModuleName
1023           << CurModuleFile->getName()
1024           << ModuleFile->getName();
1025         ModuleBuildFailed = true;
1026         return ModuleLoadResult();
1027       }
1028     }
1029 
1030     // If we don't already have an ASTReader, create one now.
1031     if (!ModuleManager) {
1032       if (!hasASTContext())
1033         createASTContext();
1034 
1035       std::string Sysroot = getHeaderSearchOpts().Sysroot;
1036       const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1037       ModuleManager = new ASTReader(getPreprocessor(), *Context,
1038                                     Sysroot.empty() ? "" : Sysroot.c_str(),
1039                                     PPOpts.DisablePCHValidation,
1040                                     /*AllowASTWithCompilerErrors=*/false,
1041                                     getFrontendOpts().UseGlobalModuleIndex);
1042       if (hasASTConsumer()) {
1043         ModuleManager->setDeserializationListener(
1044           getASTConsumer().GetASTDeserializationListener());
1045         getASTContext().setASTMutationListener(
1046           getASTConsumer().GetASTMutationListener());
1047         getPreprocessor().setPPMutationListener(
1048           getASTConsumer().GetPPMutationListener());
1049       }
1050       OwningPtr<ExternalASTSource> Source;
1051       Source.reset(ModuleManager);
1052       getASTContext().setExternalSource(Source);
1053       if (hasSema())
1054         ModuleManager->InitializeSema(getSema());
1055       if (hasASTConsumer())
1056         ModuleManager->StartTranslationUnit(&getASTConsumer());
1057     }
1058 
1059     // Try to load the module we found.
1060     unsigned ARRFlags = ASTReader::ARR_None;
1061     if (Module)
1062       ARRFlags |= ASTReader::ARR_OutOfDate;
1063     switch (ModuleManager->ReadAST(ModuleFile->getName(),
1064                                    serialization::MK_Module, ImportLoc,
1065                                    ARRFlags)) {
1066     case ASTReader::Success:
1067       break;
1068 
1069     case ASTReader::OutOfDate: {
1070       // The module file is out-of-date. Rebuild it.
1071       getFileManager().invalidateCache(ModuleFile);
1072       bool Existed;
1073       llvm::sys::fs::remove(ModuleFileName, Existed);
1074 
1075       // Check whether we have already attempted to build this module (but
1076       // failed).
1077       if (getPreprocessorOpts().FailedModules &&
1078           getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1079         getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1080           << ModuleName
1081           << SourceRange(ImportLoc, ModuleNameLoc);
1082         ModuleBuildFailed = true;
1083         return ModuleLoadResult();
1084       }
1085 
1086       compileModule(*this, ModuleNameLoc, Module, ModuleFileName);
1087 
1088       // Try loading the module again.
1089       ModuleFile = FileMgr->getFile(ModuleFileName, /*OpenFile=*/false,
1090                                     /*CacheFailure=*/false);
1091       if (!ModuleFile ||
1092           ModuleManager->ReadAST(ModuleFileName,
1093                                  serialization::MK_Module, ImportLoc,
1094                                  ASTReader::ARR_None) != ASTReader::Success) {
1095         if (getPreprocessorOpts().FailedModules)
1096           getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1097         KnownModules[Path[0].first] = 0;
1098         ModuleBuildFailed = true;
1099         return ModuleLoadResult();
1100       }
1101 
1102       // Okay, we've rebuilt and now loaded the module.
1103       break;
1104     }
1105 
1106     case ASTReader::VersionMismatch:
1107     case ASTReader::ConfigurationMismatch:
1108     case ASTReader::HadErrors:
1109       // FIXME: The ASTReader will already have complained, but can we showhorn
1110       // that diagnostic information into a more useful form?
1111       KnownModules[Path[0].first] = 0;
1112       return ModuleLoadResult();
1113 
1114     case ASTReader::Failure:
1115       // Already complained, but note now that we failed.
1116       KnownModules[Path[0].first] = 0;
1117       ModuleBuildFailed = true;
1118       return ModuleLoadResult();
1119     }
1120 
1121     if (!Module) {
1122       // If we loaded the module directly, without finding a module map first,
1123       // we'll have loaded the module's information from the module itself.
1124       Module = PP->getHeaderSearchInfo().getModuleMap()
1125                  .findModule((Path[0].first->getName()));
1126     }
1127 
1128     if (Module) {
1129       Module->setASTFile(ModuleFile);
1130     }
1131 
1132     // Cache the result of this top-level module lookup for later.
1133     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1134   }
1135 
1136   // If we never found the module, fail.
1137   if (!Module)
1138     return ModuleLoadResult();
1139 
1140   // Verify that the rest of the module path actually corresponds to
1141   // a submodule.
1142   if (Path.size() > 1) {
1143     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1144       StringRef Name = Path[I].first->getName();
1145       clang::Module *Sub = Module->findSubmodule(Name);
1146 
1147       if (!Sub) {
1148         // Attempt to perform typo correction to find a module name that works.
1149         SmallVector<StringRef, 2> Best;
1150         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1151 
1152         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1153                                             JEnd = Module->submodule_end();
1154              J != JEnd; ++J) {
1155           unsigned ED = Name.edit_distance((*J)->Name,
1156                                            /*AllowReplacements=*/true,
1157                                            BestEditDistance);
1158           if (ED <= BestEditDistance) {
1159             if (ED < BestEditDistance) {
1160               Best.clear();
1161               BestEditDistance = ED;
1162             }
1163 
1164             Best.push_back((*J)->Name);
1165           }
1166         }
1167 
1168         // If there was a clear winner, user it.
1169         if (Best.size() == 1) {
1170           getDiagnostics().Report(Path[I].second,
1171                                   diag::err_no_submodule_suggest)
1172             << Path[I].first << Module->getFullModuleName() << Best[0]
1173             << SourceRange(Path[0].second, Path[I-1].second)
1174             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1175                                             Best[0]);
1176 
1177           Sub = Module->findSubmodule(Best[0]);
1178         }
1179       }
1180 
1181       if (!Sub) {
1182         // No submodule by this name. Complain, and don't look for further
1183         // submodules.
1184         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1185           << Path[I].first << Module->getFullModuleName()
1186           << SourceRange(Path[0].second, Path[I-1].second);
1187         break;
1188       }
1189 
1190       Module = Sub;
1191     }
1192   }
1193 
1194   // Make the named module visible, if it's not already part of the module
1195   // we are parsing.
1196   if (ModuleName != getLangOpts().CurrentModule) {
1197     if (!Module->IsFromModuleFile) {
1198       // We have an umbrella header or directory that doesn't actually include
1199       // all of the headers within the directory it covers. Complain about
1200       // this missing submodule and recover by forgetting that we ever saw
1201       // this submodule.
1202       // FIXME: Should we detect this at module load time? It seems fairly
1203       // expensive (and rare).
1204       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1205         << Module->getFullModuleName()
1206         << SourceRange(Path.front().second, Path.back().second);
1207 
1208       return ModuleLoadResult(0, true);
1209     }
1210 
1211     // Check whether this module is available.
1212     StringRef Feature;
1213     if (!Module->isAvailable(getLangOpts(), getTarget(), Feature)) {
1214       getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1215         << Module->getFullModuleName()
1216         << Feature
1217         << SourceRange(Path.front().second, Path.back().second);
1218       LastModuleImportLoc = ImportLoc;
1219       LastModuleImportResult = ModuleLoadResult();
1220       return ModuleLoadResult();
1221     }
1222 
1223     ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
1224   }
1225 
1226   // If this module import was due to an inclusion directive, create an
1227   // implicit import declaration to capture it in the AST.
1228   if (IsInclusionDirective && hasASTContext()) {
1229     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1230     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
1231                                                      ImportLoc, Module,
1232                                                      Path.back().second);
1233     TU->addDecl(ImportD);
1234     if (Consumer)
1235       Consumer->HandleImplicitImportDecl(ImportD);
1236   }
1237 
1238   LastModuleImportLoc = ImportLoc;
1239   LastModuleImportResult = ModuleLoadResult(Module, false);
1240   return LastModuleImportResult;
1241 }
1242 
makeModuleVisible(Module * Mod,Module::NameVisibilityKind Visibility,SourceLocation ImportLoc)1243 void CompilerInstance::makeModuleVisible(Module *Mod,
1244                                          Module::NameVisibilityKind Visibility,
1245                                          SourceLocation ImportLoc){
1246   ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
1247 }
1248 
1249