CompilerInstance.cpp revision 76d991ec6c5cd247ee18fe65c35d43c2d47cf094
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/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/Lex/HeaderSearch.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/PTHManager.h"
22#include "clang/Frontend/ChainedDiagnosticClient.h"
23#include "clang/Frontend/FrontendAction.h"
24#include "clang/Frontend/FrontendActions.h"
25#include "clang/Frontend/FrontendDiagnostic.h"
26#include "clang/Frontend/LogDiagnosticPrinter.h"
27#include "clang/Frontend/TextDiagnosticPrinter.h"
28#include "clang/Frontend/VerifyDiagnosticsClient.h"
29#include "clang/Frontend/Utils.h"
30#include "clang/Serialization/ASTReader.h"
31#include "clang/Sema/CodeCompleteConsumer.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/Support/Timer.h"
37#include "llvm/Support/Host.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Program.h"
40#include "llvm/Support/Signals.h"
41#include "llvm/Support/system_error.h"
42#include "llvm/Config/config.h"
43using namespace clang;
44
45CompilerInstance::CompilerInstance()
46  : Invocation(new CompilerInvocation()), ModuleManager(0) {
47}
48
49CompilerInstance::~CompilerInstance() {
50}
51
52void CompilerInstance::setInvocation(CompilerInvocation *Value) {
53  Invocation = Value;
54}
55
56void CompilerInstance::setDiagnostics(Diagnostic *Value) {
57  Diagnostics = Value;
58}
59
60void CompilerInstance::setTarget(TargetInfo *Value) {
61  Target = Value;
62}
63
64void CompilerInstance::setFileManager(FileManager *Value) {
65  FileMgr = Value;
66}
67
68void CompilerInstance::setSourceManager(SourceManager *Value) {
69  SourceMgr = Value;
70}
71
72void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
73
74void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
75
76void CompilerInstance::setSema(Sema *S) {
77  TheSema.reset(S);
78}
79
80void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
81  Consumer.reset(Value);
82}
83
84void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
85  CompletionConsumer.reset(Value);
86}
87
88// Diagnostics
89static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
90                              unsigned argc, const char* const *argv,
91                              Diagnostic &Diags) {
92  std::string ErrorInfo;
93  llvm::OwningPtr<raw_ostream> OS(
94    new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
95  if (!ErrorInfo.empty()) {
96    Diags.Report(diag::err_fe_unable_to_open_logfile)
97                 << DiagOpts.DumpBuildInformation << ErrorInfo;
98    return;
99  }
100
101  (*OS) << "clang -cc1 command line arguments: ";
102  for (unsigned i = 0; i != argc; ++i)
103    (*OS) << argv[i] << ' ';
104  (*OS) << '\n';
105
106  // Chain in a diagnostic client which will log the diagnostics.
107  DiagnosticClient *Logger =
108    new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
109  Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
110}
111
112static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
113                               const CodeGenOptions *CodeGenOpts,
114                               Diagnostic &Diags) {
115  std::string ErrorInfo;
116  bool OwnsStream = false;
117  raw_ostream *OS = &llvm::errs();
118  if (DiagOpts.DiagnosticLogFile != "-") {
119    // Create the output stream.
120    llvm::raw_fd_ostream *FileOS(
121      new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
122                               ErrorInfo, llvm::raw_fd_ostream::F_Append));
123    if (!ErrorInfo.empty()) {
124      Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
125        << DiagOpts.DumpBuildInformation << ErrorInfo;
126    } else {
127      FileOS->SetUnbuffered();
128      FileOS->SetUseAtomicWrites(true);
129      OS = FileOS;
130      OwnsStream = true;
131    }
132  }
133
134  // Chain in the diagnostic client which will log the diagnostics.
135  LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
136                                                          OwnsStream);
137  if (CodeGenOpts)
138    Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
139  Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
140}
141
142void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
143                                         DiagnosticClient *Client,
144                                         bool ShouldOwnClient) {
145  Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
146                                  ShouldOwnClient, &getCodeGenOpts());
147}
148
149llvm::IntrusiveRefCntPtr<Diagnostic>
150CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
151                                    int Argc, const char* const *Argv,
152                                    DiagnosticClient *Client,
153                                    bool ShouldOwnClient,
154                                    const CodeGenOptions *CodeGenOpts) {
155  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
156  llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
157
158  // Create the diagnostic client for reporting errors or for
159  // implementing -verify.
160  if (Client)
161    Diags->setClient(Client, ShouldOwnClient);
162  else
163    Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
164
165  // Chain in -verify checker, if requested.
166  if (Opts.VerifyDiagnostics)
167    Diags->setClient(new VerifyDiagnosticsClient(*Diags));
168
169  // Chain in -diagnostic-log-file dumper, if requested.
170  if (!Opts.DiagnosticLogFile.empty())
171    SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
172
173  if (!Opts.DumpBuildInformation.empty())
174    SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
175
176  // Configure our handling of diagnostics.
177  ProcessWarningOptions(*Diags, Opts);
178
179  return Diags;
180}
181
182// File Manager
183
184void CompilerInstance::createFileManager() {
185  FileMgr = new FileManager(getFileSystemOpts());
186}
187
188// Source Manager
189
190void CompilerInstance::createSourceManager(FileManager &FileMgr) {
191  SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
192}
193
194// Preprocessor
195
196void CompilerInstance::createPreprocessor() {
197  const PreprocessorOptions &PPOpts = getPreprocessorOpts();
198
199  // Create a PTH manager if we are using some form of a token cache.
200  PTHManager *PTHMgr = 0;
201  if (!PPOpts.TokenCache.empty())
202    PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
203
204  // Create the Preprocessor.
205  HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager());
206  PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
207                        getSourceManager(), *HeaderInfo, *this, PTHMgr,
208                        /*OwnsHeaderSearch=*/true);
209
210  // Note that this is different then passing PTHMgr to Preprocessor's ctor.
211  // That argument is used as the IdentifierInfoLookup argument to
212  // IdentifierTable's ctor.
213  if (PTHMgr) {
214    PTHMgr->setPreprocessor(&*PP);
215    PP->setPTHManager(PTHMgr);
216  }
217
218  if (PPOpts.DetailedRecord)
219    PP->createPreprocessingRecord(
220                                  PPOpts.DetailedRecordIncludesNestedMacroExpansions);
221
222  InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
223
224  // Set up the module path, including the hash for the
225  // module-creation options.
226  llvm::SmallString<256> SpecificModuleCache(
227                           getHeaderSearchOpts().ModuleCachePath);
228  if (!getHeaderSearchOpts().DisableModuleHash)
229    llvm::sys::path::append(SpecificModuleCache,
230                            getInvocation().getModuleHash());
231  PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
232
233  // Handle generating dependencies, if requested.
234  const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
235  if (!DepOpts.OutputFile.empty())
236    AttachDependencyFileGen(*PP, DepOpts);
237
238  // Handle generating header include information, if requested.
239  if (DepOpts.ShowHeaderIncludes)
240    AttachHeaderIncludeGen(*PP);
241  if (!DepOpts.HeaderIncludeOutputFile.empty()) {
242    StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
243    if (OutputPath == "-")
244      OutputPath = "";
245    AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
246                           /*ShowDepth=*/false);
247  }
248}
249
250// ASTContext
251
252void CompilerInstance::createASTContext() {
253  Preprocessor &PP = getPreprocessor();
254  Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
255                           &getTarget(), PP.getIdentifierTable(),
256                           PP.getSelectorTable(), PP.getBuiltinInfo(),
257                           /*size_reserve=*/ 0);
258}
259
260// ExternalASTSource
261
262void CompilerInstance::createPCHExternalASTSource(StringRef Path,
263                                                  bool DisablePCHValidation,
264                                                  bool DisableStatCache,
265                                                 void *DeserializationListener){
266  llvm::OwningPtr<ExternalASTSource> Source;
267  bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
268  Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
269                                          DisablePCHValidation,
270                                          DisableStatCache,
271                                          getPreprocessor(), getASTContext(),
272                                          DeserializationListener,
273                                          Preamble));
274  ModuleManager = static_cast<ASTReader*>(Source.get());
275  getASTContext().setExternalSource(Source);
276}
277
278ExternalASTSource *
279CompilerInstance::createPCHExternalASTSource(StringRef Path,
280                                             const std::string &Sysroot,
281                                             bool DisablePCHValidation,
282                                             bool DisableStatCache,
283                                             Preprocessor &PP,
284                                             ASTContext &Context,
285                                             void *DeserializationListener,
286                                             bool Preamble) {
287  llvm::OwningPtr<ASTReader> Reader;
288  Reader.reset(new ASTReader(PP, Context,
289                             Sysroot.empty() ? "" : Sysroot.c_str(),
290                             DisablePCHValidation, DisableStatCache));
291
292  Reader->setDeserializationListener(
293            static_cast<ASTDeserializationListener *>(DeserializationListener));
294  switch (Reader->ReadAST(Path,
295                          Preamble ? serialization::MK_Preamble
296                                   : serialization::MK_PCH)) {
297  case ASTReader::Success:
298    // Set the predefines buffer as suggested by the PCH reader. Typically, the
299    // predefines buffer will be empty.
300    PP.setPredefines(Reader->getSuggestedPredefines());
301    return Reader.take();
302
303  case ASTReader::Failure:
304    // Unrecoverable failure: don't even try to process the input file.
305    break;
306
307  case ASTReader::IgnorePCH:
308    // No suitable PCH file could be found. Return an error.
309    break;
310  }
311
312  return 0;
313}
314
315// Code Completion
316
317static bool EnableCodeCompletion(Preprocessor &PP,
318                                 const std::string &Filename,
319                                 unsigned Line,
320                                 unsigned Column) {
321  // Tell the source manager to chop off the given file at a specific
322  // line and column.
323  const FileEntry *Entry = PP.getFileManager().getFile(Filename);
324  if (!Entry) {
325    PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
326      << Filename;
327    return true;
328  }
329
330  // Truncate the named file at the given line/column.
331  PP.SetCodeCompletionPoint(Entry, Line, Column);
332  return false;
333}
334
335void CompilerInstance::createCodeCompletionConsumer() {
336  const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
337  if (!CompletionConsumer) {
338    CompletionConsumer.reset(
339      createCodeCompletionConsumer(getPreprocessor(),
340                                   Loc.FileName, Loc.Line, Loc.Column,
341                                   getFrontendOpts().ShowMacrosInCodeCompletion,
342                             getFrontendOpts().ShowCodePatternsInCodeCompletion,
343                           getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
344                                   llvm::outs()));
345    if (!CompletionConsumer)
346      return;
347  } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
348                                  Loc.Line, Loc.Column)) {
349    CompletionConsumer.reset();
350    return;
351  }
352
353  if (CompletionConsumer->isOutputBinary() &&
354      llvm::sys::Program::ChangeStdoutToBinary()) {
355    getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
356    CompletionConsumer.reset();
357  }
358}
359
360void CompilerInstance::createFrontendTimer() {
361  FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
362}
363
364CodeCompleteConsumer *
365CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
366                                               const std::string &Filename,
367                                               unsigned Line,
368                                               unsigned Column,
369                                               bool ShowMacros,
370                                               bool ShowCodePatterns,
371                                               bool ShowGlobals,
372                                               raw_ostream &OS) {
373  if (EnableCodeCompletion(PP, Filename, Line, Column))
374    return 0;
375
376  // Set up the creation routine for code-completion.
377  return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
378                                          ShowGlobals, OS);
379}
380
381void CompilerInstance::createSema(TranslationUnitKind TUKind,
382                                  CodeCompleteConsumer *CompletionConsumer) {
383  TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
384                         TUKind, CompletionConsumer));
385}
386
387// Output Files
388
389void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
390  assert(OutFile.OS && "Attempt to add empty stream to output list!");
391  OutputFiles.push_back(OutFile);
392}
393
394void CompilerInstance::clearOutputFiles(bool EraseFiles) {
395  for (std::list<OutputFile>::iterator
396         it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
397    delete it->OS;
398    if (!it->TempFilename.empty()) {
399      if (EraseFiles) {
400        bool existed;
401        llvm::sys::fs::remove(it->TempFilename, existed);
402      } else {
403        llvm::SmallString<128> NewOutFile(it->Filename);
404
405        // If '-working-directory' was passed, the output filename should be
406        // relative to that.
407        FileMgr->FixupRelativePath(NewOutFile);
408        if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
409                                                        NewOutFile.str())) {
410          getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
411            << it->TempFilename << it->Filename << ec.message();
412
413          bool existed;
414          llvm::sys::fs::remove(it->TempFilename, existed);
415        }
416      }
417    } else if (!it->Filename.empty() && EraseFiles)
418      llvm::sys::Path(it->Filename).eraseFromDisk();
419
420  }
421  OutputFiles.clear();
422}
423
424llvm::raw_fd_ostream *
425CompilerInstance::createDefaultOutputFile(bool Binary,
426                                          StringRef InFile,
427                                          StringRef Extension) {
428  return createOutputFile(getFrontendOpts().OutputFile, Binary,
429                          /*RemoveFileOnSignal=*/true, InFile, Extension);
430}
431
432llvm::raw_fd_ostream *
433CompilerInstance::createOutputFile(StringRef OutputPath,
434                                   bool Binary, bool RemoveFileOnSignal,
435                                   StringRef InFile,
436                                   StringRef Extension,
437                                   bool UseTemporary) {
438  std::string Error, OutputPathName, TempPathName;
439  llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
440                                              RemoveFileOnSignal,
441                                              InFile, Extension,
442                                              UseTemporary,
443                                              &OutputPathName,
444                                              &TempPathName);
445  if (!OS) {
446    getDiagnostics().Report(diag::err_fe_unable_to_open_output)
447      << OutputPath << Error;
448    return 0;
449  }
450
451  // Add the output file -- but don't try to remove "-", since this means we are
452  // using stdin.
453  addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
454                TempPathName, OS));
455
456  return OS;
457}
458
459llvm::raw_fd_ostream *
460CompilerInstance::createOutputFile(StringRef OutputPath,
461                                   std::string &Error,
462                                   bool Binary,
463                                   bool RemoveFileOnSignal,
464                                   StringRef InFile,
465                                   StringRef Extension,
466                                   bool UseTemporary,
467                                   std::string *ResultPathName,
468                                   std::string *TempPathName) {
469  std::string OutFile, TempFile;
470  if (!OutputPath.empty()) {
471    OutFile = OutputPath;
472  } else if (InFile == "-") {
473    OutFile = "-";
474  } else if (!Extension.empty()) {
475    llvm::sys::Path Path(InFile);
476    Path.eraseSuffix();
477    Path.appendSuffix(Extension);
478    OutFile = Path.str();
479  } else {
480    OutFile = "-";
481  }
482
483  llvm::OwningPtr<llvm::raw_fd_ostream> OS;
484  std::string OSFile;
485
486  if (UseTemporary && OutFile != "-") {
487    llvm::sys::Path OutPath(OutFile);
488    // Only create the temporary if we can actually write to OutPath, otherwise
489    // we want to fail early.
490    bool Exists;
491    if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
492        (OutPath.isRegularFile() && OutPath.canWrite())) {
493      // Create a temporary file.
494      llvm::SmallString<128> TempPath;
495      TempPath = OutFile;
496      TempPath += "-%%%%%%%%";
497      int fd;
498      if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
499                               /*makeAbsolute=*/false) == llvm::errc::success) {
500        OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
501        OSFile = TempFile = TempPath.str();
502      }
503    }
504  }
505
506  if (!OS) {
507    OSFile = OutFile;
508    OS.reset(
509      new llvm::raw_fd_ostream(OSFile.c_str(), Error,
510                               (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
511    if (!Error.empty())
512      return 0;
513  }
514
515  // Make sure the out stream file gets removed if we crash.
516  if (RemoveFileOnSignal)
517    llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
518
519  if (ResultPathName)
520    *ResultPathName = OutFile;
521  if (TempPathName)
522    *TempPathName = TempFile;
523
524  return OS.take();
525}
526
527// Initialization Utilities
528
529bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
530  return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
531                                 getSourceManager(), getFrontendOpts());
532}
533
534bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
535                                               Diagnostic &Diags,
536                                               FileManager &FileMgr,
537                                               SourceManager &SourceMgr,
538                                               const FrontendOptions &Opts) {
539  // Figure out where to get and map in the main file, unless it's already
540  // been created (e.g., by a precompiled preamble).
541  if (!SourceMgr.getMainFileID().isInvalid()) {
542    // Do nothing: the main file has already been set.
543  } else if (InputFile != "-") {
544    const FileEntry *File = FileMgr.getFile(InputFile);
545    if (!File) {
546      Diags.Report(diag::err_fe_error_reading) << InputFile;
547      return false;
548    }
549    SourceMgr.createMainFileID(File);
550  } else {
551    llvm::OwningPtr<llvm::MemoryBuffer> SB;
552    if (llvm::MemoryBuffer::getSTDIN(SB)) {
553      // FIXME: Give ec.message() in this diag.
554      Diags.Report(diag::err_fe_error_reading_stdin);
555      return false;
556    }
557    const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
558                                                   SB->getBufferSize(), 0);
559    SourceMgr.createMainFileID(File);
560    SourceMgr.overrideFileContents(File, SB.take());
561  }
562
563  assert(!SourceMgr.getMainFileID().isInvalid() &&
564         "Couldn't establish MainFileID!");
565  return true;
566}
567
568// High-Level Operations
569
570bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
571  assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
572  assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
573  assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
574
575  // FIXME: Take this as an argument, once all the APIs we used have moved to
576  // taking it as an input instead of hard-coding llvm::errs.
577  raw_ostream &OS = llvm::errs();
578
579  // Create the target instance.
580  setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
581  if (!hasTarget())
582    return false;
583
584  // Inform the target of the language options.
585  //
586  // FIXME: We shouldn't need to do this, the target should be immutable once
587  // created. This complexity should be lifted elsewhere.
588  getTarget().setForcedLangOptions(getLangOpts());
589
590  // Validate/process some options.
591  if (getHeaderSearchOpts().Verbose)
592    OS << "clang -cc1 version " CLANG_VERSION_STRING
593       << " based upon " << PACKAGE_STRING
594       << " hosted on " << llvm::sys::getHostTriple() << "\n";
595
596  if (getFrontendOpts().ShowTimers)
597    createFrontendTimer();
598
599  if (getFrontendOpts().ShowStats)
600    llvm::EnableStatistics();
601
602  for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
603    const std::string &InFile = getFrontendOpts().Inputs[i].second;
604
605    // Reset the ID tables if we are reusing the SourceManager.
606    if (hasSourceManager())
607      getSourceManager().clearIDTables();
608
609    if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
610      Act.Execute();
611      Act.EndSourceFile();
612    }
613  }
614
615  if (getDiagnosticOpts().ShowCarets) {
616    // We can have multiple diagnostics sharing one diagnostic client.
617    // Get the total number of warnings/errors from the client.
618    unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
619    unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
620
621    if (NumWarnings)
622      OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
623    if (NumWarnings && NumErrors)
624      OS << " and ";
625    if (NumErrors)
626      OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
627    if (NumWarnings || NumErrors)
628      OS << " generated.\n";
629  }
630
631  if (getFrontendOpts().ShowStats && hasFileManager()) {
632    getFileManager().PrintStats();
633    OS << "\n";
634  }
635
636  return !getDiagnostics().getClient()->getNumErrors();
637}
638
639/// \brief Determine the appropriate source input kind based on language
640/// options.
641static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
642  if (LangOpts.OpenCL)
643    return IK_OpenCL;
644  if (LangOpts.CUDA)
645    return IK_CUDA;
646  if (LangOpts.ObjC1)
647    return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
648  return LangOpts.CPlusPlus? IK_CXX : IK_C;
649}
650
651/// \brief Compile a module file for the given module name with the given
652/// umbrella header, using the options provided by the importing compiler
653/// instance.
654static void compileModule(CompilerInstance &ImportingInstance,
655                          StringRef ModuleName,
656                          StringRef ModuleFileName,
657                          StringRef UmbrellaHeader) {
658  // Construct a compiler invocation for creating this module.
659  llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
660    (new CompilerInvocation(ImportingInstance.getInvocation()));
661  Invocation->getLangOpts().resetNonModularOptions();
662  Invocation->getPreprocessorOpts().resetNonModularOptions();
663
664  FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
665  FrontendOpts.OutputFile = ModuleFileName.str();
666  FrontendOpts.DisableFree = false;
667  FrontendOpts.Inputs.clear();
668  FrontendOpts.Inputs.push_back(
669    std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()),
670                                                 UmbrellaHeader));
671
672  Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
673
674  assert(ImportingInstance.getInvocation().getModuleHash() ==
675           Invocation->getModuleHash() && "Module hash mismatch!");
676
677  // Construct a compiler instance that will be used to actually create the
678  // module.
679  CompilerInstance Instance;
680  Instance.setInvocation(&*Invocation);
681  Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
682                             &ImportingInstance.getDiagnosticClient(),
683                             /*ShouldOwnClient=*/false);
684
685  // Construct a module-generating action.
686  GeneratePCHAction CreateModuleAction(true);
687
688  // Execute the action to actually build the module in-place.
689  // FIXME: Need to synchronize when multiple processes do this.
690  Instance.ExecuteAction(CreateModuleAction);
691
692  // Tell the diagnostic client that it's (re-)starting to process a source
693  // file.
694  ImportingInstance.getDiagnosticClient()
695    .BeginSourceFile(ImportingInstance.getLangOpts(),
696                     &ImportingInstance.getPreprocessor());
697}
698
699ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
700                                       IdentifierInfo &ModuleName,
701                                       SourceLocation ModuleNameLoc) {
702  // Determine what file we're searching from.
703  SourceManager &SourceMgr = getSourceManager();
704  SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
705  const FileEntry *CurFile
706    = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
707  if (!CurFile)
708    CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
709
710  // Search for a module with the given name.
711  std::string UmbrellaHeader;
712  std::string ModuleFileName;
713  const FileEntry *ModuleFile
714    = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
715                                             &ModuleFileName,
716                                             &UmbrellaHeader);
717
718  bool BuildingModule = false;
719  if (!ModuleFile && !UmbrellaHeader.empty()) {
720    // We didn't find the module, but there is an umbrella header that
721    // can be used to create the module file. Create a separate compilation
722    // module to do so.
723    BuildingModule = true;
724    compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader);
725    ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName());
726  }
727
728  if (!ModuleFile) {
729    getDiagnostics().Report(ModuleNameLoc,
730                            BuildingModule? diag::err_module_not_built
731                                          : diag::err_module_not_found)
732      << ModuleName.getName()
733      << SourceRange(ImportLoc, ModuleNameLoc);
734    return 0;
735  }
736
737  // If we don't already have an ASTReader, create one now.
738  if (!ModuleManager) {
739    std::string Sysroot = getHeaderSearchOpts().Sysroot;
740    const PreprocessorOptions &PPOpts = getPreprocessorOpts();
741    ModuleManager = new ASTReader(getPreprocessor(), *Context,
742                                  Sysroot.empty() ? "" : Sysroot.c_str(),
743                                  PPOpts.DisablePCHValidation,
744                                  PPOpts.DisableStatCache);
745    ModuleManager->setDeserializationListener(
746      getASTConsumer().GetASTDeserializationListener());
747    getASTContext().setASTMutationListener(
748      getASTConsumer().GetASTMutationListener());
749    llvm::OwningPtr<ExternalASTSource> Source;
750    Source.reset(ModuleManager);
751    getASTContext().setExternalSource(Source);
752    ModuleManager->InitializeSema(getSema());
753  }
754
755  // Try to load the module we found.
756  switch (ModuleManager->ReadAST(ModuleFile->getName(),
757                                 serialization::MK_Module)) {
758  case ASTReader::Success:
759    break;
760
761  case ASTReader::IgnorePCH:
762    // FIXME: The ASTReader will already have complained, but can we showhorn
763    // that diagnostic information into a more useful form?
764    return 0;
765
766  case ASTReader::Failure:
767    // Already complained.
768    return 0;
769  }
770
771  // FIXME: The module file's FileEntry makes a poor key indeed!
772  return (ModuleKey)ModuleFile;
773}
774
775