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