xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision 7b83306d20ccfd25c8d039ed265bd911dbfecad7)
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 using namespace clang;
42 
43 CompilerInstance::CompilerInstance()
44   : Invocation(new CompilerInvocation()) {
45 }
46 
47 CompilerInstance::~CompilerInstance() {
48 }
49 
50 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
51   Invocation = Value;
52 }
53 
54 void CompilerInstance::setDiagnostics(Diagnostic *Value) {
55   Diagnostics = Value;
56 }
57 
58 void CompilerInstance::setTarget(TargetInfo *Value) {
59   Target = Value;
60 }
61 
62 void CompilerInstance::setFileManager(FileManager *Value) {
63   FileMgr = Value;
64 }
65 
66 void CompilerInstance::setSourceManager(SourceManager *Value) {
67   SourceMgr = Value;
68 }
69 
70 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
71 
72 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
73 
74 void CompilerInstance::setSema(Sema *S) {
75   TheSema.reset(S);
76 }
77 
78 void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
79   Consumer.reset(Value);
80 }
81 
82 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
83   CompletionConsumer.reset(Value);
84 }
85 
86 // Diagnostics
87 static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
88                               unsigned argc, const char* const *argv,
89                               Diagnostic &Diags) {
90   std::string ErrorInfo;
91   llvm::OwningPtr<llvm::raw_ostream> OS(
92     new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
93   if (!ErrorInfo.empty()) {
94     Diags.Report(diag::err_fe_unable_to_open_logfile)
95                  << DiagOpts.DumpBuildInformation << ErrorInfo;
96     return;
97   }
98 
99   (*OS) << "clang -cc1 command line arguments: ";
100   for (unsigned i = 0; i != argc; ++i)
101     (*OS) << argv[i] << ' ';
102   (*OS) << '\n';
103 
104   // Chain in a diagnostic client which will log the diagnostics.
105   DiagnosticClient *Logger =
106     new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
107   Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
108 }
109 
110 static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
111                                const CodeGenOptions *CodeGenOpts,
112                                Diagnostic &Diags) {
113   std::string ErrorInfo;
114   bool OwnsStream = false;
115   llvm::raw_ostream *OS = &llvm::errs();
116   if (DiagOpts.DiagnosticLogFile != "-") {
117     // Create the output stream.
118     llvm::raw_fd_ostream *FileOS(
119       new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
120                                ErrorInfo));
121     if (!ErrorInfo.empty()) {
122       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
123         << DiagOpts.DumpBuildInformation << ErrorInfo;
124     } else {
125       FileOS->SetUnbuffered();
126       FileOS->SetUseAtomicWrites(true);
127       OS = FileOS;
128       OwnsStream = true;
129     }
130   }
131 
132   // Chain in the diagnostic client which will log the diagnostics.
133   LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
134                                                           OwnsStream);
135   if (CodeGenOpts)
136     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
137   Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
138 }
139 
140 void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
141                                          DiagnosticClient *Client) {
142   Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
143                                   &getCodeGenOpts());
144 }
145 
146 llvm::IntrusiveRefCntPtr<Diagnostic>
147 CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
148                                     int Argc, const char* const *Argv,
149                                     DiagnosticClient *Client,
150                                     const CodeGenOptions *CodeGenOpts) {
151   llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
152   llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
153 
154   // Create the diagnostic client for reporting errors or for
155   // implementing -verify.
156   if (Client)
157     Diags->setClient(Client);
158   else
159     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
160 
161   // Chain in -verify checker, if requested.
162   if (Opts.VerifyDiagnostics)
163     Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
164 
165   // Chain in -diagnostic-log-file dumper, if requested.
166   if (!Opts.DiagnosticLogFile.empty())
167     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
168 
169   if (!Opts.DumpBuildInformation.empty())
170     SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
171 
172   // Configure our handling of diagnostics.
173   ProcessWarningOptions(*Diags, Opts);
174 
175   return Diags;
176 }
177 
178 // File Manager
179 
180 void CompilerInstance::createFileManager() {
181   FileMgr = new FileManager(getFileSystemOpts());
182 }
183 
184 // Source Manager
185 
186 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
187   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
188 }
189 
190 // Preprocessor
191 
192 void CompilerInstance::createPreprocessor() {
193   PP = createPreprocessor(getDiagnostics(), getLangOpts(),
194                           getPreprocessorOpts(), getHeaderSearchOpts(),
195                           getDependencyOutputOpts(), getTarget(),
196                           getFrontendOpts(), getSourceManager(),
197                           getFileManager());
198 }
199 
200 Preprocessor *
201 CompilerInstance::createPreprocessor(Diagnostic &Diags,
202                                      const LangOptions &LangInfo,
203                                      const PreprocessorOptions &PPOpts,
204                                      const HeaderSearchOptions &HSOpts,
205                                      const DependencyOutputOptions &DepOpts,
206                                      const TargetInfo &Target,
207                                      const FrontendOptions &FEOpts,
208                                      SourceManager &SourceMgr,
209                                      FileManager &FileMgr) {
210   // Create a PTH manager if we are using some form of a token cache.
211   PTHManager *PTHMgr = 0;
212   if (!PPOpts.TokenCache.empty())
213     PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
214 
215   // Create the Preprocessor.
216   HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
217   Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
218                                       SourceMgr, *HeaderInfo, PTHMgr,
219                                       /*OwnsHeaderSearch=*/true);
220 
221   // Note that this is different then passing PTHMgr to Preprocessor's ctor.
222   // That argument is used as the IdentifierInfoLookup argument to
223   // IdentifierTable's ctor.
224   if (PTHMgr) {
225     PTHMgr->setPreprocessor(PP);
226     PP->setPTHManager(PTHMgr);
227   }
228 
229   if (PPOpts.DetailedRecord)
230     PP->createPreprocessingRecord();
231 
232   InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
233 
234   // Handle generating dependencies, if requested.
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     llvm::StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
243     if (OutputPath == "-")
244       OutputPath = "";
245     AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
246                            /*ShowDepth=*/false);
247   }
248 
249   return PP;
250 }
251 
252 // ASTContext
253 
254 void CompilerInstance::createASTContext() {
255   Preprocessor &PP = getPreprocessor();
256   Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
257                            getTarget(), PP.getIdentifierTable(),
258                            PP.getSelectorTable(), PP.getBuiltinInfo(),
259                            /*size_reserve=*/ 0);
260 }
261 
262 // ExternalASTSource
263 
264 void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
265                                                   bool DisablePCHValidation,
266                                                   bool DisableStatCache,
267                                                  void *DeserializationListener){
268   llvm::OwningPtr<ExternalASTSource> Source;
269   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
270   Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
271                                           DisablePCHValidation,
272                                           DisableStatCache,
273                                           getPreprocessor(), getASTContext(),
274                                           DeserializationListener,
275                                           Preamble));
276   getASTContext().setExternalSource(Source);
277 }
278 
279 ExternalASTSource *
280 CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
281                                              const std::string &Sysroot,
282                                              bool DisablePCHValidation,
283                                              bool DisableStatCache,
284                                              Preprocessor &PP,
285                                              ASTContext &Context,
286                                              void *DeserializationListener,
287                                              bool Preamble) {
288   llvm::OwningPtr<ASTReader> Reader;
289   Reader.reset(new ASTReader(PP, &Context,
290                              Sysroot.empty() ? 0 : Sysroot.c_str(),
291                              DisablePCHValidation, DisableStatCache));
292 
293   Reader->setDeserializationListener(
294             static_cast<ASTDeserializationListener *>(DeserializationListener));
295   switch (Reader->ReadAST(Path,
296                           Preamble ? ASTReader::Preamble : ASTReader::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 
317 static 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 
335 void 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 
360 void CompilerInstance::createFrontendTimer() {
361   FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
362 }
363 
364 CodeCompleteConsumer *
365 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
366                                                const std::string &Filename,
367                                                unsigned Line,
368                                                unsigned Column,
369                                                bool ShowMacros,
370                                                bool ShowCodePatterns,
371                                                bool ShowGlobals,
372                                                llvm::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 
381 void CompilerInstance::createSema(bool CompleteTranslationUnit,
382                                   CodeCompleteConsumer *CompletionConsumer) {
383   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
384                          CompleteTranslationUnit, CompletionConsumer));
385 }
386 
387 // Output Files
388 
389 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
390   assert(OutFile.OS && "Attempt to add empty stream to output list!");
391   OutputFiles.push_back(OutFile);
392 }
393 
394 void 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 
424 llvm::raw_fd_ostream *
425 CompilerInstance::createDefaultOutputFile(bool Binary,
426                                           llvm::StringRef InFile,
427                                           llvm::StringRef Extension) {
428   return createOutputFile(getFrontendOpts().OutputFile, Binary,
429                           /*RemoveFileOnSignal=*/true, InFile, Extension);
430 }
431 
432 llvm::raw_fd_ostream *
433 CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
434                                    bool Binary, bool RemoveFileOnSignal,
435                                    llvm::StringRef InFile,
436                                    llvm::StringRef Extension) {
437   std::string Error, OutputPathName, TempPathName;
438   llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
439                                               RemoveFileOnSignal,
440                                               InFile, Extension,
441                                               &OutputPathName,
442                                               &TempPathName);
443   if (!OS) {
444     getDiagnostics().Report(diag::err_fe_unable_to_open_output)
445       << OutputPath << Error;
446     return 0;
447   }
448 
449   // Add the output file -- but don't try to remove "-", since this means we are
450   // using stdin.
451   addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
452                 TempPathName, OS));
453 
454   return OS;
455 }
456 
457 llvm::raw_fd_ostream *
458 CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
459                                    std::string &Error,
460                                    bool Binary,
461                                    bool RemoveFileOnSignal,
462                                    llvm::StringRef InFile,
463                                    llvm::StringRef Extension,
464                                    std::string *ResultPathName,
465                                    std::string *TempPathName) {
466   std::string OutFile, TempFile;
467   if (!OutputPath.empty()) {
468     OutFile = OutputPath;
469   } else if (InFile == "-") {
470     OutFile = "-";
471   } else if (!Extension.empty()) {
472     llvm::sys::Path Path(InFile);
473     Path.eraseSuffix();
474     Path.appendSuffix(Extension);
475     OutFile = Path.str();
476   } else {
477     OutFile = "-";
478   }
479 
480   if (OutFile != "-") {
481     llvm::sys::Path OutPath(OutFile);
482     // Only create the temporary if we can actually write to OutPath, otherwise
483     // we want to fail early.
484     bool Exists;
485     if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
486         (OutPath.isRegularFile() && OutPath.canWrite())) {
487       // Create a temporary file.
488       llvm::sys::Path TempPath(OutFile);
489       if (!TempPath.createTemporaryFileOnDisk())
490         TempFile = TempPath.str();
491     }
492   }
493 
494   std::string OSFile = OutFile;
495   if (!TempFile.empty())
496     OSFile = TempFile;
497 
498   llvm::OwningPtr<llvm::raw_fd_ostream> OS(
499     new llvm::raw_fd_ostream(OSFile.c_str(), Error,
500                              (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
501   if (!Error.empty())
502     return 0;
503 
504   // Make sure the out stream file gets removed if we crash.
505   if (RemoveFileOnSignal)
506     llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
507 
508   if (ResultPathName)
509     *ResultPathName = OutFile;
510   if (TempPathName)
511     *TempPathName = TempFile;
512 
513   return OS.take();
514 }
515 
516 // Initialization Utilities
517 
518 bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
519   return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
520                                  getSourceManager(), getFrontendOpts());
521 }
522 
523 bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
524                                                Diagnostic &Diags,
525                                                FileManager &FileMgr,
526                                                SourceManager &SourceMgr,
527                                                const FrontendOptions &Opts) {
528   // Figure out where to get and map in the main file, unless it's already
529   // been created (e.g., by a precompiled preamble).
530   if (!SourceMgr.getMainFileID().isInvalid()) {
531     // Do nothing: the main file has already been set.
532   } else if (InputFile != "-") {
533     const FileEntry *File = FileMgr.getFile(InputFile);
534     if (!File) {
535       Diags.Report(diag::err_fe_error_reading) << InputFile;
536       return false;
537     }
538     SourceMgr.createMainFileID(File);
539   } else {
540     llvm::OwningPtr<llvm::MemoryBuffer> SB;
541     if (llvm::MemoryBuffer::getSTDIN(SB)) {
542       // FIXME: Give ec.message() in this diag.
543       Diags.Report(diag::err_fe_error_reading_stdin);
544       return false;
545     }
546     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
547                                                    SB->getBufferSize(), 0);
548     SourceMgr.createMainFileID(File);
549     SourceMgr.overrideFileContents(File, SB.take());
550   }
551 
552   assert(!SourceMgr.getMainFileID().isInvalid() &&
553          "Couldn't establish MainFileID!");
554   return true;
555 }
556 
557 // High-Level Operations
558 
559 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
560   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
561   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
562   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
563 
564   // FIXME: Take this as an argument, once all the APIs we used have moved to
565   // taking it as an input instead of hard-coding llvm::errs.
566   llvm::raw_ostream &OS = llvm::errs();
567 
568   // Create the target instance.
569   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
570   if (!hasTarget())
571     return false;
572 
573   // Inform the target of the language options.
574   //
575   // FIXME: We shouldn't need to do this, the target should be immutable once
576   // created. This complexity should be lifted elsewhere.
577   getTarget().setForcedLangOptions(getLangOpts());
578 
579   // Validate/process some options.
580   if (getHeaderSearchOpts().Verbose)
581     OS << "clang -cc1 version " CLANG_VERSION_STRING
582        << " based upon " << PACKAGE_STRING
583        << " hosted on " << llvm::sys::getHostTriple() << "\n";
584 
585   if (getFrontendOpts().ShowTimers)
586     createFrontendTimer();
587 
588   if (getFrontendOpts().ShowStats)
589     llvm::EnableStatistics();
590 
591   for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
592     const std::string &InFile = getFrontendOpts().Inputs[i].second;
593 
594     // Reset the ID tables if we are reusing the SourceManager.
595     if (hasSourceManager())
596       getSourceManager().clearIDTables();
597 
598     if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
599       Act.Execute();
600       Act.EndSourceFile();
601     }
602   }
603 
604   if (getDiagnosticOpts().ShowCarets) {
605     // We can have multiple diagnostics sharing one diagnostic client.
606     // Get the total number of warnings/errors from the client.
607     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
608     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
609 
610     if (NumWarnings)
611       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
612     if (NumWarnings && NumErrors)
613       OS << " and ";
614     if (NumErrors)
615       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
616     if (NumWarnings || NumErrors)
617       OS << " generated.\n";
618   }
619 
620   if (getFrontendOpts().ShowStats && hasFileManager()) {
621     getFileManager().PrintStats();
622     OS << "\n";
623   }
624 
625   return !getDiagnostics().getClient()->getNumErrors();
626 }
627 
628 
629