Diagnostic.cpp revision 210299
1238722Skargl//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2251315Skargl//
3238722Skargl//                     The LLVM Compiler Infrastructure
4238722Skargl//
5238722Skargl// This file is distributed under the University of Illinois Open Source
6238722Skargl// License. See LICENSE.TXT for details.
7238722Skargl//
8238722Skargl//===----------------------------------------------------------------------===//
9238722Skargl//
10238722Skargl//  This file implements the Diagnostic-related interfaces.
11238722Skargl//
12238722Skargl//===----------------------------------------------------------------------===//
13238722Skargl
14238722Skargl#include "clang/AST/ASTDiagnostic.h"
15238722Skargl#include "clang/Analysis/AnalysisDiagnostic.h"
16238722Skargl#include "clang/Basic/Diagnostic.h"
17238722Skargl#include "clang/Basic/FileManager.h"
18238722Skargl#include "clang/Basic/IdentifierTable.h"
19238722Skargl#include "clang/Basic/PartialDiagnostic.h"
20238722Skargl#include "clang/Basic/SourceLocation.h"
21238722Skargl#include "clang/Basic/SourceManager.h"
22238722Skargl#include "clang/Driver/DriverDiagnostic.h"
23238722Skargl#include "clang/Frontend/FrontendDiagnostic.h"
24238722Skargl#include "clang/Lex/LexDiagnostic.h"
25238722Skargl#include "clang/Parse/ParseDiagnostic.h"
26238722Skargl#include "clang/Sema/SemaDiagnostic.h"
27238722Skargl#include "llvm/ADT/SmallVector.h"
28238722Skargl#include "llvm/ADT/StringExtras.h"
29238722Skargl#include "llvm/Support/MemoryBuffer.h"
30240864Skargl#include "llvm/Support/raw_ostream.h"
31240864Skargl
32240864Skargl#include <vector>
33240864Skargl#include <map>
34238722Skargl#include <cstring>
35238722Skarglusing namespace clang;
36238783Skargl
37238722Skargl//===----------------------------------------------------------------------===//
38238722Skargl// Builtin Diagnostic information
39238722Skargl//===----------------------------------------------------------------------===//
40240864Skargl
41238722Skargl// Diagnostic classes.
42238722Skarglenum {
43240864Skargl  CLASS_NOTE       = 0x01,
44238722Skargl  CLASS_WARNING    = 0x02,
45238722Skargl  CLASS_EXTENSION  = 0x03,
46240864Skargl  CLASS_ERROR      = 0x04
47240864Skargl};
48240864Skargl
49238722Skarglstruct StaticDiagInfoRec {
50238722Skargl  unsigned short DiagID;
51240864Skargl  unsigned Mapping : 3;
52240864Skargl  unsigned Class : 3;
53238722Skargl  bool SFINAE : 1;
54238722Skargl  unsigned Category : 5;
55251321Skargl
56251321Skargl  const char *Description;
57251321Skargl  const char *OptionGroup;
58251321Skargl
59251321Skargl  bool operator<(const StaticDiagInfoRec &RHS) const {
60251321Skargl    return DiagID < RHS.DiagID;
61251321Skargl  }
62251321Skargl  bool operator>(const StaticDiagInfoRec &RHS) const {
63251321Skargl    return DiagID > RHS.DiagID;
64251321Skargl  }
65238722Skargl};
66238722Skargl
67238722Skarglstatic const StaticDiagInfoRec StaticDiagInfo[] = {
68238722Skargl#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE, CATEGORY)    \
69251321Skargl  { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, CATEGORY, DESC, GROUP },
70238722Skargl#include "clang/Basic/DiagnosticCommonKinds.inc"
71238722Skargl#include "clang/Basic/DiagnosticDriverKinds.inc"
72238722Skargl#include "clang/Basic/DiagnosticFrontendKinds.inc"
73238722Skargl#include "clang/Basic/DiagnosticLexKinds.inc"
74238722Skargl#include "clang/Basic/DiagnosticParseKinds.inc"
75238722Skargl#include "clang/Basic/DiagnosticASTKinds.inc"
76238722Skargl#include "clang/Basic/DiagnosticSemaKinds.inc"
77238722Skargl#include "clang/Basic/DiagnosticAnalysisKinds.inc"
78238722Skargl  { 0, 0, 0, 0, 0, 0, 0}
79238722Skargl};
80238722Skargl#undef DIAG
81238722Skargl
82238722Skargl/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
83238722Skargl/// or null if the ID is invalid.
84238722Skarglstatic const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
85238722Skargl  unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
86238722Skargl
87238722Skargl  // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
88238722Skargl#ifndef NDEBUG
89238722Skargl  static bool IsFirst = true;
90238722Skargl  if (IsFirst) {
91238722Skargl    for (unsigned i = 1; i != NumDiagEntries; ++i) {
92238722Skargl      assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
93238722Skargl             "Diag ID conflict, the enums at the start of clang::diag (in "
94238722Skargl             "Diagnostic.h) probably need to be increased");
95238722Skargl
96238722Skargl      assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
97238722Skargl             "Improperly sorted diag info");
98238722Skargl    }
99238722Skargl    IsFirst = false;
100238722Skargl  }
101238722Skargl#endif
102238722Skargl
103238722Skargl  // Search the diagnostic table with a binary search.
104238722Skargl  StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0, 0 };
105238722Skargl
106238722Skargl  const StaticDiagInfoRec *Found =
107238722Skargl    std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find);
108238722Skargl  if (Found == StaticDiagInfo + NumDiagEntries ||
109238722Skargl      Found->DiagID != DiagID)
110238722Skargl    return 0;
111238722Skargl
112238722Skargl  return Found;
113238722Skargl}
114238722Skargl
115238722Skarglstatic unsigned GetDefaultDiagMapping(unsigned DiagID) {
116238722Skargl  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
117238722Skargl    return Info->Mapping;
118238722Skargl  return diag::MAP_FATAL;
119238722Skargl}
120238722Skargl
121238722Skargl/// getWarningOptionForDiag - Return the lowest-level warning option that
122238722Skargl/// enables the specified diagnostic.  If there is no -Wfoo flag that controls
123238722Skargl/// the diagnostic, this returns null.
124238722Skarglconst char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) {
125238722Skargl  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
126238722Skargl    return Info->OptionGroup;
127238722Skargl  return 0;
128238722Skargl}
129238722Skargl
130238722Skargl/// getWarningOptionForDiag - Return the category number that a specified
131238722Skargl/// DiagID belongs to, or 0 if no category.
132238722Skarglunsigned Diagnostic::getCategoryNumberForDiag(unsigned DiagID) {
133238722Skargl  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
134238722Skargl    return Info->Category;
135238722Skargl  return 0;
136238722Skargl}
137238722Skargl
138238722Skargl/// getCategoryNameFromID - Given a category ID, return the name of the
139238722Skargl/// category, an empty string if CategoryID is zero, or null if CategoryID is
140238722Skargl/// invalid.
141238722Skarglconst char *Diagnostic::getCategoryNameFromID(unsigned CategoryID) {
142238722Skargl  // Second the table of options, sorted by name for fast binary lookup.
143238722Skargl  static const char *CategoryNameTable[] = {
144238722Skargl#define GET_CATEGORY_TABLE
145238722Skargl#define CATEGORY(X) X,
146238722Skargl#include "clang/Basic/DiagnosticGroups.inc"
147238722Skargl#undef GET_CATEGORY_TABLE
148238722Skargl    "<<END>>"
149238722Skargl  };
150238722Skargl  static const size_t CategoryNameTableSize =
151238722Skargl    sizeof(CategoryNameTable) / sizeof(CategoryNameTable[0])-1;
152238722Skargl
153238722Skargl  if (CategoryID >= CategoryNameTableSize) return 0;
154238722Skargl  return CategoryNameTable[CategoryID];
155238722Skargl}
156238722Skargl
157238722Skargl
158238722Skargl
159238722SkarglDiagnostic::SFINAEResponse
160238722SkarglDiagnostic::getDiagnosticSFINAEResponse(unsigned DiagID) {
161238722Skargl  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) {
162238722Skargl    if (!Info->SFINAE)
163238722Skargl      return SFINAE_Report;
164238722Skargl
165238722Skargl    if (Info->Class == CLASS_ERROR)
166238722Skargl      return SFINAE_SubstitutionFailure;
167238722Skargl
168238722Skargl    // Suppress notes, warnings, and extensions;
169238722Skargl    return SFINAE_Suppress;
170238722Skargl  }
171238722Skargl
172238722Skargl  return SFINAE_Report;
173238722Skargl}
174238722Skargl
175238722Skargl/// getDiagClass - Return the class field of the diagnostic.
176238722Skargl///
177238722Skarglstatic unsigned getBuiltinDiagClass(unsigned DiagID) {
178238722Skargl  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
179238722Skargl    return Info->Class;
180238722Skargl  return ~0U;
181238722Skargl}
182238722Skargl
183238722Skargl//===----------------------------------------------------------------------===//
184238722Skargl// Custom Diagnostic information
185238722Skargl//===----------------------------------------------------------------------===//
186238722Skargl
187238722Skarglnamespace clang {
188238722Skargl  namespace diag {
189238722Skargl    class CustomDiagInfo {
190238722Skargl      typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
191238722Skargl      std::vector<DiagDesc> DiagInfo;
192238722Skargl      std::map<DiagDesc, unsigned> DiagIDs;
193238722Skargl    public:
194238722Skargl
195238722Skargl      /// getDescription - Return the description of the specified custom
196238722Skargl      /// diagnostic.
197238722Skargl      const char *getDescription(unsigned DiagID) const {
198238722Skargl        assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
199238722Skargl               "Invalid diagnosic ID");
200238722Skargl        return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
201238722Skargl      }
202238722Skargl
203238722Skargl      /// getLevel - Return the level of the specified custom diagnostic.
204238722Skargl      Diagnostic::Level getLevel(unsigned DiagID) const {
205238722Skargl        assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
206238722Skargl               "Invalid diagnosic ID");
207238722Skargl        return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
208238722Skargl      }
209238722Skargl
210238722Skargl      unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message,
211238923Skargl                                 Diagnostic &Diags) {
212238722Skargl        DiagDesc D(L, Message);
213238722Skargl        // Check to see if it already exists.
214240866Skargl        std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
215240866Skargl        if (I != DiagIDs.end() && I->first == D)
216240866Skargl          return I->second;
217240866Skargl
218238722Skargl        // If not, assign a new ID.
219238722Skargl        unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
220238722Skargl        DiagIDs.insert(std::make_pair(D, ID));
221238722Skargl        DiagInfo.push_back(D);
222238722Skargl        return ID;
223240866Skargl      }
224238722Skargl    };
225238722Skargl
226238722Skargl  } // end diag namespace
227238722Skargl} // end clang namespace
228240864Skargl
229238722Skargl
230238722Skargl//===----------------------------------------------------------------------===//
231240864Skargl// Common Diagnostic implementation
232238784Skargl//===----------------------------------------------------------------------===//
233238722Skargl
234238722Skarglstatic void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
235238722Skargl                               const char *Modifier, unsigned ML,
236238722Skargl                               const char *Argument, unsigned ArgLen,
237238722Skargl                               const Diagnostic::ArgumentValue *PrevArgs,
238238722Skargl                               unsigned NumPrevArgs,
239238722Skargl                               llvm::SmallVectorImpl<char> &Output,
240238722Skargl                               void *Cookie) {
241238722Skargl  const char *Str = "<can't format argument>";
242238722Skargl  Output.append(Str, Str+strlen(Str));
243238722Skargl}
244238722Skargl
245238722Skargl
246238722SkarglDiagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
247238722Skargl  AllExtensionsSilenced = 0;
248251321Skargl  IgnoreAllWarnings = false;
249251321Skargl  WarningsAsErrors = false;
250251321Skargl  ErrorsAsFatal = false;
251251321Skargl  SuppressSystemWarnings = false;
252238722Skargl  SuppressAllDiagnostics = false;
253238722Skargl  ShowOverloads = Ovl_All;
254238722Skargl  ExtBehavior = Ext_Ignore;
255238722Skargl
256238722Skargl  ErrorOccurred = false;
257238722Skargl  FatalErrorOccurred = false;
258238722Skargl  ErrorLimit = 0;
259238722Skargl  TemplateBacktraceLimit = 0;
260238722Skargl
261238722Skargl  NumWarnings = 0;
262  NumErrors = 0;
263  NumErrorsSuppressed = 0;
264  CustomDiagInfo = 0;
265  CurDiagID = ~0U;
266  LastDiagLevel = Ignored;
267
268  ArgToStringFn = DummyArgToStringFn;
269  ArgToStringCookie = 0;
270
271  DelayedDiagID = 0;
272
273  // Set all mappings to 'unset'.
274  DiagMappings BlankDiags(diag::DIAG_UPPER_LIMIT/2, 0);
275  DiagMappingsStack.push_back(BlankDiags);
276}
277
278Diagnostic::~Diagnostic() {
279  delete CustomDiagInfo;
280}
281
282
283void Diagnostic::pushMappings() {
284  // Avoids undefined behavior when the stack has to resize.
285  DiagMappingsStack.reserve(DiagMappingsStack.size() + 1);
286  DiagMappingsStack.push_back(DiagMappingsStack.back());
287}
288
289bool Diagnostic::popMappings() {
290  if (DiagMappingsStack.size() == 1)
291    return false;
292
293  DiagMappingsStack.pop_back();
294  return true;
295}
296
297/// getCustomDiagID - Return an ID for a diagnostic with the specified message
298/// and level.  If this is the first request for this diagnosic, it is
299/// registered and created, otherwise the existing ID is returned.
300unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) {
301  if (CustomDiagInfo == 0)
302    CustomDiagInfo = new diag::CustomDiagInfo();
303  return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
304}
305
306
307/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
308/// level of the specified diagnostic ID is a Warning or Extension.
309/// This only works on builtin diagnostics, not custom ones, and is not legal to
310/// call on NOTEs.
311bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
312  return DiagID < diag::DIAG_UPPER_LIMIT &&
313         getBuiltinDiagClass(DiagID) != CLASS_ERROR;
314}
315
316/// \brief Determine whether the given built-in diagnostic ID is a
317/// Note.
318bool Diagnostic::isBuiltinNote(unsigned DiagID) {
319  return DiagID < diag::DIAG_UPPER_LIMIT &&
320    getBuiltinDiagClass(DiagID) == CLASS_NOTE;
321}
322
323/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
324/// ID is for an extension of some sort.  This also returns EnabledByDefault,
325/// which is set to indicate whether the diagnostic is ignored by default (in
326/// which case -pedantic enables it) or treated as a warning/error by default.
327///
328bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID,
329                                        bool &EnabledByDefault) {
330  if (DiagID >= diag::DIAG_UPPER_LIMIT ||
331      getBuiltinDiagClass(DiagID) != CLASS_EXTENSION)
332    return false;
333
334  EnabledByDefault = StaticDiagInfo[DiagID].Mapping != diag::MAP_IGNORE;
335  return true;
336}
337
338
339/// getDescription - Given a diagnostic ID, return a description of the
340/// issue.
341const char *Diagnostic::getDescription(unsigned DiagID) const {
342  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
343    return Info->Description;
344  return CustomDiagInfo->getDescription(DiagID);
345}
346
347void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1,
348                                      llvm::StringRef Arg2) {
349  if (DelayedDiagID)
350    return;
351
352  DelayedDiagID = DiagID;
353  DelayedDiagArg1 = Arg1.str();
354  DelayedDiagArg2 = Arg2.str();
355}
356
357void Diagnostic::ReportDelayed() {
358  Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
359  DelayedDiagID = 0;
360  DelayedDiagArg1.clear();
361  DelayedDiagArg2.clear();
362}
363
364/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
365/// object, classify the specified diagnostic ID into a Level, consumable by
366/// the DiagnosticClient.
367Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
368  // Handle custom diagnostics, which cannot be mapped.
369  if (DiagID >= diag::DIAG_UPPER_LIMIT)
370    return CustomDiagInfo->getLevel(DiagID);
371
372  unsigned DiagClass = getBuiltinDiagClass(DiagID);
373  assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
374  return getDiagnosticLevel(DiagID, DiagClass);
375}
376
377/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
378/// object, classify the specified diagnostic ID into a Level, consumable by
379/// the DiagnosticClient.
380Diagnostic::Level
381Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
382  // Specific non-error diagnostics may be mapped to various levels from ignored
383  // to error.  Errors can only be mapped to fatal.
384  Diagnostic::Level Result = Diagnostic::Fatal;
385
386  // Get the mapping information, if unset, compute it lazily.
387  unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
388  if (MappingInfo == 0) {
389    MappingInfo = GetDefaultDiagMapping(DiagID);
390    setDiagnosticMappingInternal(DiagID, MappingInfo, false);
391  }
392
393  switch (MappingInfo & 7) {
394  default: assert(0 && "Unknown mapping!");
395  case diag::MAP_IGNORE:
396    // Ignore this, unless this is an extension diagnostic and we're mapping
397    // them onto warnings or errors.
398    if (!isBuiltinExtensionDiag(DiagID) ||  // Not an extension
399        ExtBehavior == Ext_Ignore ||        // Extensions ignored anyway
400        (MappingInfo & 8) != 0)             // User explicitly mapped it.
401      return Diagnostic::Ignored;
402    Result = Diagnostic::Warning;
403    if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
404    if (Result == Diagnostic::Error && ErrorsAsFatal)
405      Result = Diagnostic::Fatal;
406    break;
407  case diag::MAP_ERROR:
408    Result = Diagnostic::Error;
409    if (ErrorsAsFatal)
410      Result = Diagnostic::Fatal;
411    break;
412  case diag::MAP_FATAL:
413    Result = Diagnostic::Fatal;
414    break;
415  case diag::MAP_WARNING:
416    // If warnings are globally mapped to ignore or error, do it.
417    if (IgnoreAllWarnings)
418      return Diagnostic::Ignored;
419
420    Result = Diagnostic::Warning;
421
422    // If this is an extension diagnostic and we're in -pedantic-error mode, and
423    // if the user didn't explicitly map it, upgrade to an error.
424    if (ExtBehavior == Ext_Error &&
425        (MappingInfo & 8) == 0 &&
426        isBuiltinExtensionDiag(DiagID))
427      Result = Diagnostic::Error;
428
429    if (WarningsAsErrors)
430      Result = Diagnostic::Error;
431    if (Result == Diagnostic::Error && ErrorsAsFatal)
432      Result = Diagnostic::Fatal;
433    break;
434
435  case diag::MAP_WARNING_NO_WERROR:
436    // Diagnostics specified with -Wno-error=foo should be set to warnings, but
437    // not be adjusted by -Werror or -pedantic-errors.
438    Result = Diagnostic::Warning;
439
440    // If warnings are globally mapped to ignore or error, do it.
441    if (IgnoreAllWarnings)
442      return Diagnostic::Ignored;
443
444    break;
445
446  case diag::MAP_ERROR_NO_WFATAL:
447    // Diagnostics specified as -Wno-fatal-error=foo should be errors, but
448    // unaffected by -Wfatal-errors.
449    Result = Diagnostic::Error;
450    break;
451  }
452
453  // Okay, we're about to return this as a "diagnostic to emit" one last check:
454  // if this is any sort of extension warning, and if we're in an __extension__
455  // block, silence it.
456  if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
457    return Diagnostic::Ignored;
458
459  return Result;
460}
461
462struct WarningOption {
463  const char  *Name;
464  const short *Members;
465  const short *SubGroups;
466};
467
468#define GET_DIAG_ARRAYS
469#include "clang/Basic/DiagnosticGroups.inc"
470#undef GET_DIAG_ARRAYS
471
472// Second the table of options, sorted by name for fast binary lookup.
473static const WarningOption OptionTable[] = {
474#define GET_DIAG_TABLE
475#include "clang/Basic/DiagnosticGroups.inc"
476#undef GET_DIAG_TABLE
477};
478static const size_t OptionTableSize =
479sizeof(OptionTable) / sizeof(OptionTable[0]);
480
481static bool WarningOptionCompare(const WarningOption &LHS,
482                                 const WarningOption &RHS) {
483  return strcmp(LHS.Name, RHS.Name) < 0;
484}
485
486static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
487                            Diagnostic &Diags) {
488  // Option exists, poke all the members of its diagnostic set.
489  if (const short *Member = Group->Members) {
490    for (; *Member != -1; ++Member)
491      Diags.setDiagnosticMapping(*Member, Mapping);
492  }
493
494  // Enable/disable all subgroups along with this one.
495  if (const short *SubGroups = Group->SubGroups) {
496    for (; *SubGroups != (short)-1; ++SubGroups)
497      MapGroupMembers(&OptionTable[(short)*SubGroups], Mapping, Diags);
498  }
499}
500
501/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
502/// "unknown-pragmas" to have the specified mapping.  This returns true and
503/// ignores the request if "Group" was unknown, false otherwise.
504bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
505                                           diag::Mapping Map) {
506
507  WarningOption Key = { Group, 0, 0 };
508  const WarningOption *Found =
509  std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
510                   WarningOptionCompare);
511  if (Found == OptionTable + OptionTableSize ||
512      strcmp(Found->Name, Group) != 0)
513    return true;  // Option not found.
514
515  MapGroupMembers(Found, Map, *this);
516  return false;
517}
518
519
520/// ProcessDiag - This is the method used to report a diagnostic that is
521/// finally fully formed.
522bool Diagnostic::ProcessDiag() {
523  DiagnosticInfo Info(this);
524
525  if (SuppressAllDiagnostics)
526    return false;
527
528  // Figure out the diagnostic level of this message.
529  Diagnostic::Level DiagLevel;
530  unsigned DiagID = Info.getID();
531
532  // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
533  // in a system header.
534  bool ShouldEmitInSystemHeader;
535
536  if (DiagID >= diag::DIAG_UPPER_LIMIT) {
537    // Handle custom diagnostics, which cannot be mapped.
538    DiagLevel = CustomDiagInfo->getLevel(DiagID);
539
540    // Custom diagnostics always are emitted in system headers.
541    ShouldEmitInSystemHeader = true;
542  } else {
543    // Get the class of the diagnostic.  If this is a NOTE, map it onto whatever
544    // the diagnostic level was for the previous diagnostic so that it is
545    // filtered the same as the previous diagnostic.
546    unsigned DiagClass = getBuiltinDiagClass(DiagID);
547    if (DiagClass == CLASS_NOTE) {
548      DiagLevel = Diagnostic::Note;
549      ShouldEmitInSystemHeader = false;  // extra consideration is needed
550    } else {
551      // If this is not an error and we are in a system header, we ignore it.
552      // Check the original Diag ID here, because we also want to ignore
553      // extensions and warnings in -Werror and -pedantic-errors modes, which
554      // *map* warnings/extensions to errors.
555      ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
556
557      DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
558    }
559  }
560
561  if (DiagLevel != Diagnostic::Note) {
562    // Record that a fatal error occurred only when we see a second
563    // non-note diagnostic. This allows notes to be attached to the
564    // fatal error, but suppresses any diagnostics that follow those
565    // notes.
566    if (LastDiagLevel == Diagnostic::Fatal)
567      FatalErrorOccurred = true;
568
569    LastDiagLevel = DiagLevel;
570  }
571
572  // If a fatal error has already been emitted, silence all subsequent
573  // diagnostics.
574  if (FatalErrorOccurred) {
575    if (DiagLevel >= Diagnostic::Error) {
576      ++NumErrors;
577      ++NumErrorsSuppressed;
578    }
579
580    return false;
581  }
582
583  // If the client doesn't care about this message, don't issue it.  If this is
584  // a note and the last real diagnostic was ignored, ignore it too.
585  if (DiagLevel == Diagnostic::Ignored ||
586      (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
587    return false;
588
589  // If this diagnostic is in a system header and is not a clang error, suppress
590  // it.
591  if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
592      Info.getLocation().isValid() &&
593      Info.getLocation().getInstantiationLoc().isInSystemHeader() &&
594      (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
595    LastDiagLevel = Diagnostic::Ignored;
596    return false;
597  }
598
599  if (DiagLevel >= Diagnostic::Error) {
600    ErrorOccurred = true;
601    ++NumErrors;
602
603    // If we've emitted a lot of errors, emit a fatal error after it to stop a
604    // flood of bogus errors.
605    if (ErrorLimit && NumErrors >= ErrorLimit &&
606        DiagLevel == Diagnostic::Error)
607      SetDelayedDiagnostic(diag::fatal_too_many_errors);
608  }
609
610  // Finally, report it.
611  Client->HandleDiagnostic(DiagLevel, Info);
612  if (Client->IncludeInDiagnosticCounts()) {
613    if (DiagLevel == Diagnostic::Warning)
614      ++NumWarnings;
615  }
616
617  CurDiagID = ~0U;
618
619  return true;
620}
621
622bool DiagnosticBuilder::Emit() {
623  // If DiagObj is null, then its soul was stolen by the copy ctor
624  // or the user called Emit().
625  if (DiagObj == 0) return false;
626
627  // When emitting diagnostics, we set the final argument count into
628  // the Diagnostic object.
629  DiagObj->NumDiagArgs = NumArgs;
630  DiagObj->NumDiagRanges = NumRanges;
631  DiagObj->NumFixItHints = NumFixItHints;
632
633  // Process the diagnostic, sending the accumulated information to the
634  // DiagnosticClient.
635  bool Emitted = DiagObj->ProcessDiag();
636
637  // Clear out the current diagnostic object.
638  unsigned DiagID = DiagObj->CurDiagID;
639  DiagObj->Clear();
640
641  // If there was a delayed diagnostic, emit it now.
642  if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
643    DiagObj->ReportDelayed();
644
645  // This diagnostic is dead.
646  DiagObj = 0;
647
648  return Emitted;
649}
650
651
652DiagnosticClient::~DiagnosticClient() {}
653
654
655/// ModifierIs - Return true if the specified modifier matches specified string.
656template <std::size_t StrLen>
657static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
658                       const char (&Str)[StrLen]) {
659  return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
660}
661
662/// ScanForward - Scans forward, looking for the given character, skipping
663/// nested clauses and escaped characters.
664static const char *ScanFormat(const char *I, const char *E, char Target) {
665  unsigned Depth = 0;
666
667  for ( ; I != E; ++I) {
668    if (Depth == 0 && *I == Target) return I;
669    if (Depth != 0 && *I == '}') Depth--;
670
671    if (*I == '%') {
672      I++;
673      if (I == E) break;
674
675      // Escaped characters get implicitly skipped here.
676
677      // Format specifier.
678      if (!isdigit(*I) && !ispunct(*I)) {
679        for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
680        if (I == E) break;
681        if (*I == '{')
682          Depth++;
683      }
684    }
685  }
686  return E;
687}
688
689/// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
690/// like this:  %select{foo|bar|baz}2.  This means that the integer argument
691/// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
692/// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
693/// This is very useful for certain classes of variant diagnostics.
694static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
695                                 const char *Argument, unsigned ArgumentLen,
696                                 llvm::SmallVectorImpl<char> &OutStr) {
697  const char *ArgumentEnd = Argument+ArgumentLen;
698
699  // Skip over 'ValNo' |'s.
700  while (ValNo) {
701    const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
702    assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
703           " larger than the number of options in the diagnostic string!");
704    Argument = NextVal+1;  // Skip this string.
705    --ValNo;
706  }
707
708  // Get the end of the value.  This is either the } or the |.
709  const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
710
711  // Recursively format the result of the select clause into the output string.
712  DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
713}
714
715/// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
716/// letter 's' to the string if the value is not 1.  This is used in cases like
717/// this:  "you idiot, you have %4 parameter%s4!".
718static void HandleIntegerSModifier(unsigned ValNo,
719                                   llvm::SmallVectorImpl<char> &OutStr) {
720  if (ValNo != 1)
721    OutStr.push_back('s');
722}
723
724/// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
725/// prints the ordinal form of the given integer, with 1 corresponding
726/// to the first ordinal.  Currently this is hard-coded to use the
727/// English form.
728static void HandleOrdinalModifier(unsigned ValNo,
729                                  llvm::SmallVectorImpl<char> &OutStr) {
730  assert(ValNo != 0 && "ValNo must be strictly positive!");
731
732  llvm::raw_svector_ostream Out(OutStr);
733
734  // We could use text forms for the first N ordinals, but the numeric
735  // forms are actually nicer in diagnostics because they stand out.
736  Out << ValNo;
737
738  // It is critically important that we do this perfectly for
739  // user-written sequences with over 100 elements.
740  switch (ValNo % 100) {
741  case 11:
742  case 12:
743  case 13:
744    Out << "th"; return;
745  default:
746    switch (ValNo % 10) {
747    case 1: Out << "st"; return;
748    case 2: Out << "nd"; return;
749    case 3: Out << "rd"; return;
750    default: Out << "th"; return;
751    }
752  }
753}
754
755
756/// PluralNumber - Parse an unsigned integer and advance Start.
757static unsigned PluralNumber(const char *&Start, const char *End) {
758  // Programming 101: Parse a decimal number :-)
759  unsigned Val = 0;
760  while (Start != End && *Start >= '0' && *Start <= '9') {
761    Val *= 10;
762    Val += *Start - '0';
763    ++Start;
764  }
765  return Val;
766}
767
768/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
769static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
770  if (*Start != '[') {
771    unsigned Ref = PluralNumber(Start, End);
772    return Ref == Val;
773  }
774
775  ++Start;
776  unsigned Low = PluralNumber(Start, End);
777  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
778  ++Start;
779  unsigned High = PluralNumber(Start, End);
780  assert(*Start == ']' && "Bad plural expression syntax: expected )");
781  ++Start;
782  return Low <= Val && Val <= High;
783}
784
785/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
786static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
787  // Empty condition?
788  if (*Start == ':')
789    return true;
790
791  while (1) {
792    char C = *Start;
793    if (C == '%') {
794      // Modulo expression
795      ++Start;
796      unsigned Arg = PluralNumber(Start, End);
797      assert(*Start == '=' && "Bad plural expression syntax: expected =");
798      ++Start;
799      unsigned ValMod = ValNo % Arg;
800      if (TestPluralRange(ValMod, Start, End))
801        return true;
802    } else {
803      assert((C == '[' || (C >= '0' && C <= '9')) &&
804             "Bad plural expression syntax: unexpected character");
805      // Range expression
806      if (TestPluralRange(ValNo, Start, End))
807        return true;
808    }
809
810    // Scan for next or-expr part.
811    Start = std::find(Start, End, ',');
812    if (Start == End)
813      break;
814    ++Start;
815  }
816  return false;
817}
818
819/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
820/// for complex plural forms, or in languages where all plurals are complex.
821/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
822/// conditions that are tested in order, the form corresponding to the first
823/// that applies being emitted. The empty condition is always true, making the
824/// last form a default case.
825/// Conditions are simple boolean expressions, where n is the number argument.
826/// Here are the rules.
827/// condition  := expression | empty
828/// empty      :=                             -> always true
829/// expression := numeric [',' expression]    -> logical or
830/// numeric    := range                       -> true if n in range
831///             | '%' number '=' range        -> true if n % number in range
832/// range      := number
833///             | '[' number ',' number ']'   -> ranges are inclusive both ends
834///
835/// Here are some examples from the GNU gettext manual written in this form:
836/// English:
837/// {1:form0|:form1}
838/// Latvian:
839/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
840/// Gaeilge:
841/// {1:form0|2:form1|:form2}
842/// Romanian:
843/// {1:form0|0,%100=[1,19]:form1|:form2}
844/// Lithuanian:
845/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
846/// Russian (requires repeated form):
847/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
848/// Slovak
849/// {1:form0|[2,4]:form1|:form2}
850/// Polish (requires repeated form):
851/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
852static void HandlePluralModifier(unsigned ValNo,
853                                 const char *Argument, unsigned ArgumentLen,
854                                 llvm::SmallVectorImpl<char> &OutStr) {
855  const char *ArgumentEnd = Argument + ArgumentLen;
856  while (1) {
857    assert(Argument < ArgumentEnd && "Plural expression didn't match.");
858    const char *ExprEnd = Argument;
859    while (*ExprEnd != ':') {
860      assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
861      ++ExprEnd;
862    }
863    if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
864      Argument = ExprEnd + 1;
865      ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
866      OutStr.append(Argument, ExprEnd);
867      return;
868    }
869    Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
870  }
871}
872
873
874/// FormatDiagnostic - Format this diagnostic into a string, substituting the
875/// formal arguments into the %0 slots.  The result is appended onto the Str
876/// array.
877void DiagnosticInfo::
878FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
879  const char *DiagStr = getDiags()->getDescription(getID());
880  const char *DiagEnd = DiagStr+strlen(DiagStr);
881
882  FormatDiagnostic(DiagStr, DiagEnd, OutStr);
883}
884
885void DiagnosticInfo::
886FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
887                 llvm::SmallVectorImpl<char> &OutStr) const {
888
889  /// FormattedArgs - Keep track of all of the arguments formatted by
890  /// ConvertArgToString and pass them into subsequent calls to
891  /// ConvertArgToString, allowing the implementation to avoid redundancies in
892  /// obvious cases.
893  llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
894
895  while (DiagStr != DiagEnd) {
896    if (DiagStr[0] != '%') {
897      // Append non-%0 substrings to Str if we have one.
898      const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
899      OutStr.append(DiagStr, StrEnd);
900      DiagStr = StrEnd;
901      continue;
902    } else if (ispunct(DiagStr[1])) {
903      OutStr.push_back(DiagStr[1]);  // %% -> %.
904      DiagStr += 2;
905      continue;
906    }
907
908    // Skip the %.
909    ++DiagStr;
910
911    // This must be a placeholder for a diagnostic argument.  The format for a
912    // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
913    // The digit is a number from 0-9 indicating which argument this comes from.
914    // The modifier is a string of digits from the set [-a-z]+, arguments is a
915    // brace enclosed string.
916    const char *Modifier = 0, *Argument = 0;
917    unsigned ModifierLen = 0, ArgumentLen = 0;
918
919    // Check to see if we have a modifier.  If so eat it.
920    if (!isdigit(DiagStr[0])) {
921      Modifier = DiagStr;
922      while (DiagStr[0] == '-' ||
923             (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
924        ++DiagStr;
925      ModifierLen = DiagStr-Modifier;
926
927      // If we have an argument, get it next.
928      if (DiagStr[0] == '{') {
929        ++DiagStr; // Skip {.
930        Argument = DiagStr;
931
932        DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
933        assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
934        ArgumentLen = DiagStr-Argument;
935        ++DiagStr;  // Skip }.
936      }
937    }
938
939    assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
940    unsigned ArgNo = *DiagStr++ - '0';
941
942    Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
943
944    switch (Kind) {
945    // ---- STRINGS ----
946    case Diagnostic::ak_std_string: {
947      const std::string &S = getArgStdStr(ArgNo);
948      assert(ModifierLen == 0 && "No modifiers for strings yet");
949      OutStr.append(S.begin(), S.end());
950      break;
951    }
952    case Diagnostic::ak_c_string: {
953      const char *S = getArgCStr(ArgNo);
954      assert(ModifierLen == 0 && "No modifiers for strings yet");
955
956      // Don't crash if get passed a null pointer by accident.
957      if (!S)
958        S = "(null)";
959
960      OutStr.append(S, S + strlen(S));
961      break;
962    }
963    // ---- INTEGERS ----
964    case Diagnostic::ak_sint: {
965      int Val = getArgSInt(ArgNo);
966
967      if (ModifierIs(Modifier, ModifierLen, "select")) {
968        HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr);
969      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
970        HandleIntegerSModifier(Val, OutStr);
971      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
972        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
973      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
974        HandleOrdinalModifier((unsigned)Val, OutStr);
975      } else {
976        assert(ModifierLen == 0 && "Unknown integer modifier");
977        llvm::raw_svector_ostream(OutStr) << Val;
978      }
979      break;
980    }
981    case Diagnostic::ak_uint: {
982      unsigned Val = getArgUInt(ArgNo);
983
984      if (ModifierIs(Modifier, ModifierLen, "select")) {
985        HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
986      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
987        HandleIntegerSModifier(Val, OutStr);
988      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
989        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
990      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
991        HandleOrdinalModifier(Val, OutStr);
992      } else {
993        assert(ModifierLen == 0 && "Unknown integer modifier");
994        llvm::raw_svector_ostream(OutStr) << Val;
995      }
996      break;
997    }
998    // ---- NAMES and TYPES ----
999    case Diagnostic::ak_identifierinfo: {
1000      const IdentifierInfo *II = getArgIdentifier(ArgNo);
1001      assert(ModifierLen == 0 && "No modifiers for strings yet");
1002
1003      // Don't crash if get passed a null pointer by accident.
1004      if (!II) {
1005        const char *S = "(null)";
1006        OutStr.append(S, S + strlen(S));
1007        continue;
1008      }
1009
1010      llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
1011      break;
1012    }
1013    case Diagnostic::ak_qualtype:
1014    case Diagnostic::ak_declarationname:
1015    case Diagnostic::ak_nameddecl:
1016    case Diagnostic::ak_nestednamespec:
1017    case Diagnostic::ak_declcontext:
1018      getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
1019                                     Modifier, ModifierLen,
1020                                     Argument, ArgumentLen,
1021                                     FormattedArgs.data(), FormattedArgs.size(),
1022                                     OutStr);
1023      break;
1024    }
1025
1026    // Remember this argument info for subsequent formatting operations.  Turn
1027    // std::strings into a null terminated string to make it be the same case as
1028    // all the other ones.
1029    if (Kind != Diagnostic::ak_std_string)
1030      FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1031    else
1032      FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
1033                                        (intptr_t)getArgStdStr(ArgNo).c_str()));
1034
1035  }
1036}
1037
1038StoredDiagnostic::StoredDiagnostic() { }
1039
1040StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1041                                   llvm::StringRef Message)
1042  : Level(Level), Loc(), Message(Message) { }
1043
1044StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
1045                                   const DiagnosticInfo &Info)
1046  : Level(Level), Loc(Info.getLocation()) {
1047  llvm::SmallString<64> Message;
1048  Info.FormatDiagnostic(Message);
1049  this->Message.assign(Message.begin(), Message.end());
1050
1051  Ranges.reserve(Info.getNumRanges());
1052  for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
1053    Ranges.push_back(Info.getRange(I));
1054
1055  FixIts.reserve(Info.getNumFixItHints());
1056  for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
1057    FixIts.push_back(Info.getFixItHint(I));
1058}
1059
1060StoredDiagnostic::~StoredDiagnostic() { }
1061
1062static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) {
1063  OS.write((const char *)&Value, sizeof(unsigned));
1064}
1065
1066static void WriteString(llvm::raw_ostream &OS, llvm::StringRef String) {
1067  WriteUnsigned(OS, String.size());
1068  OS.write(String.data(), String.size());
1069}
1070
1071static void WriteSourceLocation(llvm::raw_ostream &OS,
1072                                SourceManager *SM,
1073                                SourceLocation Location) {
1074  if (!SM || Location.isInvalid()) {
1075    // If we don't have a source manager or this location is invalid,
1076    // just write an invalid location.
1077    WriteUnsigned(OS, 0);
1078    WriteUnsigned(OS, 0);
1079    WriteUnsigned(OS, 0);
1080    return;
1081  }
1082
1083  Location = SM->getInstantiationLoc(Location);
1084  std::pair<FileID, unsigned> Decomposed = SM->getDecomposedLoc(Location);
1085
1086  const FileEntry *FE = SM->getFileEntryForID(Decomposed.first);
1087  if (FE)
1088    WriteString(OS, FE->getName());
1089  else {
1090    // Fallback to using the buffer name when there is no entry.
1091    WriteString(OS, SM->getBuffer(Decomposed.first)->getBufferIdentifier());
1092  }
1093
1094  WriteUnsigned(OS, SM->getLineNumber(Decomposed.first, Decomposed.second));
1095  WriteUnsigned(OS, SM->getColumnNumber(Decomposed.first, Decomposed.second));
1096}
1097
1098void StoredDiagnostic::Serialize(llvm::raw_ostream &OS) const {
1099  SourceManager *SM = 0;
1100  if (getLocation().isValid())
1101    SM = &const_cast<SourceManager &>(getLocation().getManager());
1102
1103  // Write a short header to help identify diagnostics.
1104  OS << (char)0x06 << (char)0x07;
1105
1106  // Write the diagnostic level and location.
1107  WriteUnsigned(OS, (unsigned)Level);
1108  WriteSourceLocation(OS, SM, getLocation());
1109
1110  // Write the diagnostic message.
1111  llvm::SmallString<64> Message;
1112  WriteString(OS, getMessage());
1113
1114  // Count the number of ranges that don't point into macros, since
1115  // only simple file ranges serialize well.
1116  unsigned NumNonMacroRanges = 0;
1117  for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1118    if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
1119      continue;
1120
1121    ++NumNonMacroRanges;
1122  }
1123
1124  // Write the ranges.
1125  WriteUnsigned(OS, NumNonMacroRanges);
1126  if (NumNonMacroRanges) {
1127    for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) {
1128      if (R->getBegin().isMacroID() || R->getEnd().isMacroID())
1129        continue;
1130
1131      WriteSourceLocation(OS, SM, R->getBegin());
1132      WriteSourceLocation(OS, SM, R->getEnd());
1133      WriteUnsigned(OS, R->isTokenRange());
1134    }
1135  }
1136
1137  // Determine if all of the fix-its involve rewrites with simple file
1138  // locations (not in macro instantiations). If so, we can write
1139  // fix-it information.
1140  unsigned NumFixIts = 0;
1141  for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1142    if (F->RemoveRange.isValid() &&
1143        (F->RemoveRange.getBegin().isMacroID() ||
1144         F->RemoveRange.getEnd().isMacroID())) {
1145      NumFixIts = 0;
1146      break;
1147    }
1148
1149    if (F->InsertionLoc.isValid() && F->InsertionLoc.isMacroID()) {
1150      NumFixIts = 0;
1151      break;
1152    }
1153
1154    ++NumFixIts;
1155  }
1156
1157  // Write the fix-its.
1158  WriteUnsigned(OS, NumFixIts);
1159  for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) {
1160    WriteSourceLocation(OS, SM, F->RemoveRange.getBegin());
1161    WriteSourceLocation(OS, SM, F->RemoveRange.getEnd());
1162    WriteUnsigned(OS, F->RemoveRange.isTokenRange());
1163    WriteSourceLocation(OS, SM, F->InsertionLoc);
1164    WriteString(OS, F->CodeToInsert);
1165  }
1166}
1167
1168static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
1169                         unsigned &Value) {
1170  if (Memory + sizeof(unsigned) > MemoryEnd)
1171    return true;
1172
1173  memmove(&Value, Memory, sizeof(unsigned));
1174  Memory += sizeof(unsigned);
1175  return false;
1176}
1177
1178static bool ReadSourceLocation(FileManager &FM, SourceManager &SM,
1179                               const char *&Memory, const char *MemoryEnd,
1180                               SourceLocation &Location) {
1181  // Read the filename.
1182  unsigned FileNameLen = 0;
1183  if (ReadUnsigned(Memory, MemoryEnd, FileNameLen) ||
1184      Memory + FileNameLen > MemoryEnd)
1185    return true;
1186
1187  llvm::StringRef FileName(Memory, FileNameLen);
1188  Memory += FileNameLen;
1189
1190  // Read the line, column.
1191  unsigned Line = 0, Column = 0;
1192  if (ReadUnsigned(Memory, MemoryEnd, Line) ||
1193      ReadUnsigned(Memory, MemoryEnd, Column))
1194    return true;
1195
1196  if (FileName.empty()) {
1197    Location = SourceLocation();
1198    return false;
1199  }
1200
1201  const FileEntry *File = FM.getFile(FileName);
1202  if (!File)
1203    return true;
1204
1205  // Make sure that this file has an entry in the source manager.
1206  if (!SM.hasFileInfo(File))
1207    SM.createFileID(File, SourceLocation(), SrcMgr::C_User);
1208
1209  Location = SM.getLocation(File, Line, Column);
1210  return false;
1211}
1212
1213StoredDiagnostic
1214StoredDiagnostic::Deserialize(FileManager &FM, SourceManager &SM,
1215                              const char *&Memory, const char *MemoryEnd) {
1216  while (true) {
1217    if (Memory == MemoryEnd)
1218      return StoredDiagnostic();
1219
1220    if (*Memory != 0x06) {
1221      ++Memory;
1222      continue;
1223    }
1224
1225    ++Memory;
1226    if (Memory == MemoryEnd)
1227      return StoredDiagnostic();
1228
1229    if (*Memory != 0x07) {
1230      ++Memory;
1231      continue;
1232    }
1233
1234    // We found the header. We're done.
1235    ++Memory;
1236    break;
1237  }
1238
1239  // Read the severity level.
1240  unsigned Level = 0;
1241  if (ReadUnsigned(Memory, MemoryEnd, Level) || Level > Diagnostic::Fatal)
1242    return StoredDiagnostic();
1243
1244  // Read the source location.
1245  SourceLocation Location;
1246  if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Location))
1247    return StoredDiagnostic();
1248
1249  // Read the diagnostic text.
1250  if (Memory == MemoryEnd)
1251    return StoredDiagnostic();
1252
1253  unsigned MessageLen = 0;
1254  if (ReadUnsigned(Memory, MemoryEnd, MessageLen) ||
1255      Memory + MessageLen > MemoryEnd)
1256    return StoredDiagnostic();
1257
1258  llvm::StringRef Message(Memory, MessageLen);
1259  Memory += MessageLen;
1260
1261
1262  // At this point, we have enough information to form a diagnostic. Do so.
1263  StoredDiagnostic Diag;
1264  Diag.Level = (Diagnostic::Level)Level;
1265  Diag.Loc = FullSourceLoc(Location, SM);
1266  Diag.Message = Message;
1267  if (Memory == MemoryEnd)
1268    return Diag;
1269
1270  // Read the source ranges.
1271  unsigned NumSourceRanges = 0;
1272  if (ReadUnsigned(Memory, MemoryEnd, NumSourceRanges))
1273    return Diag;
1274  for (unsigned I = 0; I != NumSourceRanges; ++I) {
1275    SourceLocation Begin, End;
1276    unsigned IsTokenRange;
1277    if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Begin) ||
1278        ReadSourceLocation(FM, SM, Memory, MemoryEnd, End) ||
1279        ReadUnsigned(Memory, MemoryEnd, IsTokenRange))
1280      return Diag;
1281
1282    Diag.Ranges.push_back(CharSourceRange(SourceRange(Begin, End),
1283                                          IsTokenRange));
1284  }
1285
1286  // Read the fix-it hints.
1287  unsigned NumFixIts = 0;
1288  if (ReadUnsigned(Memory, MemoryEnd, NumFixIts))
1289    return Diag;
1290  for (unsigned I = 0; I != NumFixIts; ++I) {
1291    SourceLocation RemoveBegin, RemoveEnd, InsertionLoc;
1292    unsigned InsertLen = 0, RemoveIsTokenRange;
1293    if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveBegin) ||
1294        ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveEnd) ||
1295        ReadUnsigned(Memory, MemoryEnd, RemoveIsTokenRange) ||
1296        ReadSourceLocation(FM, SM, Memory, MemoryEnd, InsertionLoc) ||
1297        ReadUnsigned(Memory, MemoryEnd, InsertLen) ||
1298        Memory + InsertLen > MemoryEnd) {
1299      Diag.FixIts.clear();
1300      return Diag;
1301    }
1302
1303    FixItHint Hint;
1304    Hint.RemoveRange = CharSourceRange(SourceRange(RemoveBegin, RemoveEnd),
1305                                       RemoveIsTokenRange);
1306    Hint.InsertionLoc = InsertionLoc;
1307    Hint.CodeToInsert.assign(Memory, Memory + InsertLen);
1308    Memory += InsertLen;
1309    Diag.FixIts.push_back(Hint);
1310  }
1311
1312  return Diag;
1313}
1314
1315/// IncludeInDiagnosticCounts - This method (whose default implementation
1316///  returns true) indicates whether the diagnostics handled by this
1317///  DiagnosticClient should be included in the number of diagnostics
1318///  reported by Diagnostic.
1319bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
1320
1321PartialDiagnostic::StorageAllocator::StorageAllocator() {
1322  for (unsigned I = 0; I != NumCached; ++I)
1323    FreeList[I] = Cached + I;
1324  NumFreeListEntries = NumCached;
1325}
1326
1327PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1328  assert(NumFreeListEntries == NumCached && "A partial is on the lamb");
1329}
1330