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