]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Basic/DiagnosticIDs.cpp
Merge clang 3.5.0 release from ^/vendor/clang/dist, resolve conflicts,
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Basic / DiagnosticIDs.cpp
1 //===--- DiagnosticIDs.cpp - Diagnostic IDs Handling ----------------------===//
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 //  This file implements the Diagnostic IDs-related interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Basic/DiagnosticIDs.h"
15 #include "clang/Basic/AllDiagnostics.h"
16 #include "clang/Basic/DiagnosticCategories.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include <map>
22 using namespace clang;
23
24 //===----------------------------------------------------------------------===//
25 // Builtin Diagnostic information
26 //===----------------------------------------------------------------------===//
27
28 namespace {
29
30 // Diagnostic classes.
31 enum {
32   CLASS_NOTE       = 0x01,
33   CLASS_REMARK     = 0x02,
34   CLASS_WARNING    = 0x03,
35   CLASS_EXTENSION  = 0x04,
36   CLASS_ERROR      = 0x05
37 };
38
39 struct StaticDiagInfoRec {
40   uint16_t DiagID;
41   unsigned DefaultSeverity : 3;
42   unsigned Class : 3;
43   unsigned SFINAE : 2;
44   unsigned WarnNoWerror : 1;
45   unsigned WarnShowInSystemHeader : 1;
46   unsigned Category : 5;
47
48   uint16_t OptionGroupIndex;
49
50   uint16_t DescriptionLen;
51   const char *DescriptionStr;
52
53   unsigned getOptionGroupIndex() const {
54     return OptionGroupIndex;
55   }
56
57   StringRef getDescription() const {
58     return StringRef(DescriptionStr, DescriptionLen);
59   }
60
61   diag::Flavor getFlavor() const {
62     return Class == CLASS_REMARK ? diag::Flavor::Remark
63                                  : diag::Flavor::WarningOrError;
64   }
65
66   bool operator<(const StaticDiagInfoRec &RHS) const {
67     return DiagID < RHS.DiagID;
68   }
69 };
70
71 } // namespace anonymous
72
73 static const StaticDiagInfoRec StaticDiagInfo[] = {
74 #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR,     \
75              SHOWINSYSHEADER, CATEGORY)                                        \
76   {                                                                            \
77     diag::ENUM, DEFAULT_SEVERITY, CLASS, DiagnosticIDs::SFINAE, NOWERROR,      \
78         SHOWINSYSHEADER, CATEGORY, GROUP, STR_SIZE(DESC, uint16_t), DESC       \
79   }                                                                            \
80   ,
81 #include "clang/Basic/DiagnosticCommonKinds.inc"
82 #include "clang/Basic/DiagnosticDriverKinds.inc"
83 #include "clang/Basic/DiagnosticFrontendKinds.inc"
84 #include "clang/Basic/DiagnosticSerializationKinds.inc"
85 #include "clang/Basic/DiagnosticLexKinds.inc"
86 #include "clang/Basic/DiagnosticParseKinds.inc"
87 #include "clang/Basic/DiagnosticASTKinds.inc"
88 #include "clang/Basic/DiagnosticCommentKinds.inc"
89 #include "clang/Basic/DiagnosticSemaKinds.inc"
90 #include "clang/Basic/DiagnosticAnalysisKinds.inc"
91 #undef DIAG
92 };
93
94 static const unsigned StaticDiagInfoSize = llvm::array_lengthof(StaticDiagInfo);
95
96 /// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
97 /// or null if the ID is invalid.
98 static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
99   // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
100 #ifndef NDEBUG
101   static bool IsFirst = true; // So the check is only performed on first call.
102   if (IsFirst) {
103     for (unsigned i = 1; i != StaticDiagInfoSize; ++i) {
104       assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
105              "Diag ID conflict, the enums at the start of clang::diag (in "
106              "DiagnosticIDs.h) probably need to be increased");
107
108       assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
109              "Improperly sorted diag info");
110     }
111     IsFirst = false;
112   }
113 #endif
114
115   // Out of bounds diag. Can't be in the table.
116   using namespace diag;
117   if (DiagID >= DIAG_UPPER_LIMIT || DiagID <= DIAG_START_COMMON)
118     return nullptr;
119
120   // Compute the index of the requested diagnostic in the static table.
121   // 1. Add the number of diagnostics in each category preceding the
122   //    diagnostic and of the category the diagnostic is in. This gives us
123   //    the offset of the category in the table.
124   // 2. Subtract the number of IDs in each category from our ID. This gives us
125   //    the offset of the diagnostic in the category.
126   // This is cheaper than a binary search on the table as it doesn't touch
127   // memory at all.
128   unsigned Offset = 0;
129   unsigned ID = DiagID - DIAG_START_COMMON - 1;
130 #define CATEGORY(NAME, PREV) \
131   if (DiagID > DIAG_START_##NAME) { \
132     Offset += NUM_BUILTIN_##PREV##_DIAGNOSTICS - DIAG_START_##PREV - 1; \
133     ID -= DIAG_START_##NAME - DIAG_START_##PREV; \
134   }
135 CATEGORY(DRIVER, COMMON)
136 CATEGORY(FRONTEND, DRIVER)
137 CATEGORY(SERIALIZATION, FRONTEND)
138 CATEGORY(LEX, SERIALIZATION)
139 CATEGORY(PARSE, LEX)
140 CATEGORY(AST, PARSE)
141 CATEGORY(COMMENT, AST)
142 CATEGORY(SEMA, COMMENT)
143 CATEGORY(ANALYSIS, SEMA)
144 #undef CATEGORY
145
146   // Avoid out of bounds reads.
147   if (ID + Offset >= StaticDiagInfoSize)
148     return nullptr;
149
150   assert(ID < StaticDiagInfoSize && Offset < StaticDiagInfoSize);
151
152   const StaticDiagInfoRec *Found = &StaticDiagInfo[ID + Offset];
153   // If the diag id doesn't match we found a different diag, abort. This can
154   // happen when this function is called with an ID that points into a hole in
155   // the diagID space.
156   if (Found->DiagID != DiagID)
157     return nullptr;
158   return Found;
159 }
160
161 static DiagnosticMapping GetDefaultDiagMapping(unsigned DiagID) {
162   DiagnosticMapping Info = DiagnosticMapping::Make(
163       diag::Severity::Fatal, /*IsUser=*/false, /*IsPragma=*/false);
164
165   if (const StaticDiagInfoRec *StaticInfo = GetDiagInfo(DiagID)) {
166     Info.setSeverity((diag::Severity)StaticInfo->DefaultSeverity);
167
168     if (StaticInfo->WarnNoWerror) {
169       assert(Info.getSeverity() == diag::Severity::Warning &&
170              "Unexpected mapping with no-Werror bit!");
171       Info.setNoWarningAsError(true);
172     }
173   }
174
175   return Info;
176 }
177
178 /// getCategoryNumberForDiag - Return the category number that a specified
179 /// DiagID belongs to, or 0 if no category.
180 unsigned DiagnosticIDs::getCategoryNumberForDiag(unsigned DiagID) {
181   if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
182     return Info->Category;
183   return 0;
184 }
185
186 namespace {
187   // The diagnostic category names.
188   struct StaticDiagCategoryRec {
189     const char *NameStr;
190     uint8_t NameLen;
191
192     StringRef getName() const {
193       return StringRef(NameStr, NameLen);
194     }
195   };
196 }
197
198 // Unfortunately, the split between DiagnosticIDs and Diagnostic is not
199 // particularly clean, but for now we just implement this method here so we can
200 // access GetDefaultDiagMapping.
201 DiagnosticMapping &
202 DiagnosticsEngine::DiagState::getOrAddMapping(diag::kind Diag) {
203   std::pair<iterator, bool> Result =
204       DiagMap.insert(std::make_pair(Diag, DiagnosticMapping()));
205
206   // Initialize the entry if we added it.
207   if (Result.second)
208     Result.first->second = GetDefaultDiagMapping(Diag);
209
210   return Result.first->second;
211 }
212
213 static const StaticDiagCategoryRec CategoryNameTable[] = {
214 #define GET_CATEGORY_TABLE
215 #define CATEGORY(X, ENUM) { X, STR_SIZE(X, uint8_t) },
216 #include "clang/Basic/DiagnosticGroups.inc"
217 #undef GET_CATEGORY_TABLE
218   { nullptr, 0 }
219 };
220
221 /// getNumberOfCategories - Return the number of categories
222 unsigned DiagnosticIDs::getNumberOfCategories() {
223   return llvm::array_lengthof(CategoryNameTable) - 1;
224 }
225
226 /// getCategoryNameFromID - Given a category ID, return the name of the
227 /// category, an empty string if CategoryID is zero, or null if CategoryID is
228 /// invalid.
229 StringRef DiagnosticIDs::getCategoryNameFromID(unsigned CategoryID) {
230   if (CategoryID >= getNumberOfCategories())
231    return StringRef();
232   return CategoryNameTable[CategoryID].getName();
233 }
234
235
236
237 DiagnosticIDs::SFINAEResponse
238 DiagnosticIDs::getDiagnosticSFINAEResponse(unsigned DiagID) {
239   if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
240     return static_cast<DiagnosticIDs::SFINAEResponse>(Info->SFINAE);
241   return SFINAE_Report;
242 }
243
244 /// getBuiltinDiagClass - Return the class field of the diagnostic.
245 ///
246 static unsigned getBuiltinDiagClass(unsigned DiagID) {
247   if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
248     return Info->Class;
249   return ~0U;
250 }
251
252 //===----------------------------------------------------------------------===//
253 // Custom Diagnostic information
254 //===----------------------------------------------------------------------===//
255
256 namespace clang {
257   namespace diag {
258     class CustomDiagInfo {
259       typedef std::pair<DiagnosticIDs::Level, std::string> DiagDesc;
260       std::vector<DiagDesc> DiagInfo;
261       std::map<DiagDesc, unsigned> DiagIDs;
262     public:
263
264       /// getDescription - Return the description of the specified custom
265       /// diagnostic.
266       StringRef getDescription(unsigned DiagID) const {
267         assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() &&
268                "Invalid diagnostic ID");
269         return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second;
270       }
271
272       /// getLevel - Return the level of the specified custom diagnostic.
273       DiagnosticIDs::Level getLevel(unsigned DiagID) const {
274         assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() &&
275                "Invalid diagnostic ID");
276         return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
277       }
278
279       unsigned getOrCreateDiagID(DiagnosticIDs::Level L, StringRef Message,
280                                  DiagnosticIDs &Diags) {
281         DiagDesc D(L, Message);
282         // Check to see if it already exists.
283         std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
284         if (I != DiagIDs.end() && I->first == D)
285           return I->second;
286
287         // If not, assign a new ID.
288         unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
289         DiagIDs.insert(std::make_pair(D, ID));
290         DiagInfo.push_back(D);
291         return ID;
292       }
293     };
294
295   } // end diag namespace
296 } // end clang namespace
297
298
299 //===----------------------------------------------------------------------===//
300 // Common Diagnostic implementation
301 //===----------------------------------------------------------------------===//
302
303 DiagnosticIDs::DiagnosticIDs() { CustomDiagInfo = nullptr; }
304
305 DiagnosticIDs::~DiagnosticIDs() {
306   delete CustomDiagInfo;
307 }
308
309 /// getCustomDiagID - Return an ID for a diagnostic with the specified message
310 /// and level.  If this is the first request for this diagnostic, it is
311 /// registered and created, otherwise the existing ID is returned.
312 ///
313 /// \param FormatString A fixed diagnostic format string that will be hashed and
314 /// mapped to a unique DiagID.
315 unsigned DiagnosticIDs::getCustomDiagID(Level L, StringRef FormatString) {
316   if (!CustomDiagInfo)
317     CustomDiagInfo = new diag::CustomDiagInfo();
318   return CustomDiagInfo->getOrCreateDiagID(L, FormatString, *this);
319 }
320
321
322 /// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
323 /// level of the specified diagnostic ID is a Warning or Extension.
324 /// This only works on builtin diagnostics, not custom ones, and is not legal to
325 /// call on NOTEs.
326 bool DiagnosticIDs::isBuiltinWarningOrExtension(unsigned DiagID) {
327   return DiagID < diag::DIAG_UPPER_LIMIT &&
328          getBuiltinDiagClass(DiagID) != CLASS_ERROR;
329 }
330
331 /// \brief Determine whether the given built-in diagnostic ID is a
332 /// Note.
333 bool DiagnosticIDs::isBuiltinNote(unsigned DiagID) {
334   return DiagID < diag::DIAG_UPPER_LIMIT &&
335     getBuiltinDiagClass(DiagID) == CLASS_NOTE;
336 }
337
338 /// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
339 /// ID is for an extension of some sort.  This also returns EnabledByDefault,
340 /// which is set to indicate whether the diagnostic is ignored by default (in
341 /// which case -pedantic enables it) or treated as a warning/error by default.
342 ///
343 bool DiagnosticIDs::isBuiltinExtensionDiag(unsigned DiagID,
344                                         bool &EnabledByDefault) {
345   if (DiagID >= diag::DIAG_UPPER_LIMIT ||
346       getBuiltinDiagClass(DiagID) != CLASS_EXTENSION)
347     return false;
348
349   EnabledByDefault =
350       GetDefaultDiagMapping(DiagID).getSeverity() != diag::Severity::Ignored;
351   return true;
352 }
353
354 bool DiagnosticIDs::isDefaultMappingAsError(unsigned DiagID) {
355   if (DiagID >= diag::DIAG_UPPER_LIMIT)
356     return false;
357
358   return GetDefaultDiagMapping(DiagID).getSeverity() == diag::Severity::Error;
359 }
360
361 /// getDescription - Given a diagnostic ID, return a description of the
362 /// issue.
363 StringRef DiagnosticIDs::getDescription(unsigned DiagID) const {
364   if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
365     return Info->getDescription();
366   assert(CustomDiagInfo && "Invalid CustomDiagInfo");
367   return CustomDiagInfo->getDescription(DiagID);
368 }
369
370 static DiagnosticIDs::Level toLevel(diag::Severity SV) {
371   switch (SV) {
372   case diag::Severity::Ignored:
373     return DiagnosticIDs::Ignored;
374   case diag::Severity::Remark:
375     return DiagnosticIDs::Remark;
376   case diag::Severity::Warning:
377     return DiagnosticIDs::Warning;
378   case diag::Severity::Error:
379     return DiagnosticIDs::Error;
380   case diag::Severity::Fatal:
381     return DiagnosticIDs::Fatal;
382   }
383   llvm_unreachable("unexpected severity");
384 }
385
386 /// getDiagnosticLevel - Based on the way the client configured the
387 /// DiagnosticsEngine object, classify the specified diagnostic ID into a Level,
388 /// by consumable the DiagnosticClient.
389 DiagnosticIDs::Level
390 DiagnosticIDs::getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
391                                   const DiagnosticsEngine &Diag) const {
392   // Handle custom diagnostics, which cannot be mapped.
393   if (DiagID >= diag::DIAG_UPPER_LIMIT) {
394     assert(CustomDiagInfo && "Invalid CustomDiagInfo");
395     return CustomDiagInfo->getLevel(DiagID);
396   }
397
398   unsigned DiagClass = getBuiltinDiagClass(DiagID);
399   if (DiagClass == CLASS_NOTE) return DiagnosticIDs::Note;
400   return toLevel(getDiagnosticSeverity(DiagID, Loc, Diag));
401 }
402
403 /// \brief Based on the way the client configured the Diagnostic
404 /// object, classify the specified diagnostic ID into a Level, consumable by
405 /// the DiagnosticClient.
406 ///
407 /// \param Loc The source location we are interested in finding out the
408 /// diagnostic state. Can be null in order to query the latest state.
409 diag::Severity
410 DiagnosticIDs::getDiagnosticSeverity(unsigned DiagID, SourceLocation Loc,
411                                      const DiagnosticsEngine &Diag) const {
412   assert(getBuiltinDiagClass(DiagID) != CLASS_NOTE);
413
414   // Specific non-error diagnostics may be mapped to various levels from ignored
415   // to error.  Errors can only be mapped to fatal.
416   diag::Severity Result = diag::Severity::Fatal;
417
418   DiagnosticsEngine::DiagStatePointsTy::iterator
419     Pos = Diag.GetDiagStatePointForLoc(Loc);
420   DiagnosticsEngine::DiagState *State = Pos->State;
421
422   // Get the mapping information, or compute it lazily.
423   DiagnosticMapping &Mapping = State->getOrAddMapping((diag::kind)DiagID);
424
425   // TODO: Can a null severity really get here?
426   if (Mapping.getSeverity() != diag::Severity())
427     Result = Mapping.getSeverity();
428
429   // Upgrade ignored diagnostics if -Weverything is enabled.
430   if (Diag.EnableAllWarnings && Result == diag::Severity::Ignored &&
431       !Mapping.isUser())
432     Result = diag::Severity::Warning;
433
434   // Diagnostics of class REMARK are either printed as remarks or in case they
435   // have been added to -Werror they are printed as errors.
436   // FIXME: Disregarding user-requested remark mappings like this is bogus.
437   if (Result == diag::Severity::Warning &&
438       getBuiltinDiagClass(DiagID) == CLASS_REMARK)
439     Result = diag::Severity::Remark;
440
441   // Ignore -pedantic diagnostics inside __extension__ blocks.
442   // (The diagnostics controlled by -pedantic are the extension diagnostics
443   // that are not enabled by default.)
444   bool EnabledByDefault = false;
445   bool IsExtensionDiag = isBuiltinExtensionDiag(DiagID, EnabledByDefault);
446   if (Diag.AllExtensionsSilenced && IsExtensionDiag && !EnabledByDefault)
447     return diag::Severity::Ignored;
448
449   // For extension diagnostics that haven't been explicitly mapped, check if we
450   // should upgrade the diagnostic.
451   if (IsExtensionDiag && !Mapping.isUser())
452     Result = std::max(Result, Diag.ExtBehavior);
453
454   // At this point, ignored errors can no longer be upgraded.
455   if (Result == diag::Severity::Ignored)
456     return Result;
457
458   // Honor -w, which is lower in priority than pedantic-errors, but higher than
459   // -Werror.
460   if (Result == diag::Severity::Warning && Diag.IgnoreAllWarnings)
461     return diag::Severity::Ignored;
462
463   // If -Werror is enabled, map warnings to errors unless explicitly disabled.
464   if (Result == diag::Severity::Warning) {
465     if (Diag.WarningsAsErrors && !Mapping.hasNoWarningAsError())
466       Result = diag::Severity::Error;
467   }
468
469   // If -Wfatal-errors is enabled, map errors to fatal unless explicity
470   // disabled.
471   if (Result == diag::Severity::Error) {
472     if (Diag.ErrorsAsFatal && !Mapping.hasNoErrorAsFatal())
473       Result = diag::Severity::Fatal;
474   }
475
476   // Custom diagnostics always are emitted in system headers.
477   bool ShowInSystemHeader =
478       !GetDiagInfo(DiagID) || GetDiagInfo(DiagID)->WarnShowInSystemHeader;
479
480   // If we are in a system header, we ignore it. We look at the diagnostic class
481   // because we also want to ignore extensions and warnings in -Werror and
482   // -pedantic-errors modes, which *map* warnings/extensions to errors.
483   if (Diag.SuppressSystemWarnings && !ShowInSystemHeader && Loc.isValid() &&
484       Diag.getSourceManager().isInSystemHeader(
485           Diag.getSourceManager().getExpansionLoc(Loc)))
486     return diag::Severity::Ignored;
487
488   return Result;
489 }
490
491 #define GET_DIAG_ARRAYS
492 #include "clang/Basic/DiagnosticGroups.inc"
493 #undef GET_DIAG_ARRAYS
494
495 namespace {
496   struct WarningOption {
497     uint16_t NameOffset;
498     uint16_t Members;
499     uint16_t SubGroups;
500
501     // String is stored with a pascal-style length byte.
502     StringRef getName() const {
503       return StringRef(DiagGroupNames + NameOffset + 1,
504                        DiagGroupNames[NameOffset]);
505     }
506   };
507 }
508
509 // Second the table of options, sorted by name for fast binary lookup.
510 static const WarningOption OptionTable[] = {
511 #define GET_DIAG_TABLE
512 #include "clang/Basic/DiagnosticGroups.inc"
513 #undef GET_DIAG_TABLE
514 };
515 static const size_t OptionTableSize = llvm::array_lengthof(OptionTable);
516
517 static bool WarningOptionCompare(const WarningOption &LHS, StringRef RHS) {
518   return LHS.getName() < RHS;
519 }
520
521 /// getWarningOptionForDiag - Return the lowest-level warning option that
522 /// enables the specified diagnostic.  If there is no -Wfoo flag that controls
523 /// the diagnostic, this returns null.
524 StringRef DiagnosticIDs::getWarningOptionForDiag(unsigned DiagID) {
525   if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
526     return OptionTable[Info->getOptionGroupIndex()].getName();
527   return StringRef();
528 }
529
530 /// Return \c true if any diagnostics were found in this group, even if they
531 /// were filtered out due to having the wrong flavor.
532 static bool getDiagnosticsInGroup(diag::Flavor Flavor,
533                                   const WarningOption *Group,
534                                   SmallVectorImpl<diag::kind> &Diags) {
535   // An empty group is considered to be a warning group: we have empty groups
536   // for GCC compatibility, and GCC does not have remarks.
537   if (!Group->Members && !Group->SubGroups)
538     return Flavor == diag::Flavor::Remark ? true : false;
539
540   bool NotFound = true;
541
542   // Add the members of the option diagnostic set.
543   const int16_t *Member = DiagArrays + Group->Members;
544   for (; *Member != -1; ++Member) {
545     if (GetDiagInfo(*Member)->getFlavor() == Flavor) {
546       NotFound = false;
547       Diags.push_back(*Member);
548     }
549   }
550
551   // Add the members of the subgroups.
552   const int16_t *SubGroups = DiagSubGroups + Group->SubGroups;
553   for (; *SubGroups != (int16_t)-1; ++SubGroups)
554     NotFound &= getDiagnosticsInGroup(Flavor, &OptionTable[(short)*SubGroups],
555                                       Diags);
556
557   return NotFound;
558 }
559
560 bool
561 DiagnosticIDs::getDiagnosticsInGroup(diag::Flavor Flavor, StringRef Group,
562                                      SmallVectorImpl<diag::kind> &Diags) const {
563   const WarningOption *Found = std::lower_bound(
564       OptionTable, OptionTable + OptionTableSize, Group, WarningOptionCompare);
565   if (Found == OptionTable + OptionTableSize ||
566       Found->getName() != Group)
567     return true; // Option not found.
568
569   return ::getDiagnosticsInGroup(Flavor, Found, Diags);
570 }
571
572 void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
573                                      SmallVectorImpl<diag::kind> &Diags) const {
574   for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
575     if (StaticDiagInfo[i].getFlavor() == Flavor)
576       Diags.push_back(StaticDiagInfo[i].DiagID);
577 }
578
579 StringRef DiagnosticIDs::getNearestOption(diag::Flavor Flavor,
580                                           StringRef Group) {
581   StringRef Best;
582   unsigned BestDistance = Group.size() + 1; // Sanity threshold.
583   for (const WarningOption *i = OptionTable, *e = OptionTable + OptionTableSize;
584        i != e; ++i) {
585     // Don't suggest ignored warning flags.
586     if (!i->Members && !i->SubGroups)
587       continue;
588
589     unsigned Distance = i->getName().edit_distance(Group, true, BestDistance);
590     if (Distance > BestDistance)
591       continue;
592
593     // Don't suggest groups that are not of this kind.
594     llvm::SmallVector<diag::kind, 8> Diags;
595     if (::getDiagnosticsInGroup(Flavor, i, Diags) || Diags.empty())
596       continue;
597
598     if (Distance == BestDistance) {
599       // Two matches with the same distance, don't prefer one over the other.
600       Best = "";
601     } else if (Distance < BestDistance) {
602       // This is a better match.
603       Best = i->getName();
604       BestDistance = Distance;
605     }
606   }
607
608   return Best;
609 }
610
611 /// ProcessDiag - This is the method used to report a diagnostic that is
612 /// finally fully formed.
613 bool DiagnosticIDs::ProcessDiag(DiagnosticsEngine &Diag) const {
614   Diagnostic Info(&Diag);
615
616   if (Diag.SuppressAllDiagnostics)
617     return false;
618
619   assert(Diag.getClient() && "DiagnosticClient not set!");
620
621   // Figure out the diagnostic level of this message.
622   unsigned DiagID = Info.getID();
623   DiagnosticIDs::Level DiagLevel
624     = getDiagnosticLevel(DiagID, Info.getLocation(), Diag);
625
626   if (DiagLevel != DiagnosticIDs::Note) {
627     // Record that a fatal error occurred only when we see a second
628     // non-note diagnostic. This allows notes to be attached to the
629     // fatal error, but suppresses any diagnostics that follow those
630     // notes.
631     if (Diag.LastDiagLevel == DiagnosticIDs::Fatal)
632       Diag.FatalErrorOccurred = true;
633
634     Diag.LastDiagLevel = DiagLevel;
635   }
636
637   // Update counts for DiagnosticErrorTrap even if a fatal error occurred.
638   if (DiagLevel >= DiagnosticIDs::Error) {
639     ++Diag.TrapNumErrorsOccurred;
640     if (isUnrecoverable(DiagID))
641       ++Diag.TrapNumUnrecoverableErrorsOccurred;
642   }
643
644   // If a fatal error has already been emitted, silence all subsequent
645   // diagnostics.
646   if (Diag.FatalErrorOccurred) {
647     if (DiagLevel >= DiagnosticIDs::Error &&
648         Diag.Client->IncludeInDiagnosticCounts()) {
649       ++Diag.NumErrors;
650       ++Diag.NumErrorsSuppressed;
651     }
652
653     return false;
654   }
655
656   // If the client doesn't care about this message, don't issue it.  If this is
657   // a note and the last real diagnostic was ignored, ignore it too.
658   if (DiagLevel == DiagnosticIDs::Ignored ||
659       (DiagLevel == DiagnosticIDs::Note &&
660        Diag.LastDiagLevel == DiagnosticIDs::Ignored))
661     return false;
662
663   if (DiagLevel >= DiagnosticIDs::Error) {
664     if (isUnrecoverable(DiagID))
665       Diag.UnrecoverableErrorOccurred = true;
666
667     // Warnings which have been upgraded to errors do not prevent compilation.
668     if (isDefaultMappingAsError(DiagID))
669       Diag.UncompilableErrorOccurred = true;
670
671     Diag.ErrorOccurred = true;
672     if (Diag.Client->IncludeInDiagnosticCounts()) {
673       ++Diag.NumErrors;
674     }
675
676     // If we've emitted a lot of errors, emit a fatal error instead of it to 
677     // stop a flood of bogus errors.
678     if (Diag.ErrorLimit && Diag.NumErrors > Diag.ErrorLimit &&
679         DiagLevel == DiagnosticIDs::Error) {
680       Diag.SetDelayedDiagnostic(diag::fatal_too_many_errors);
681       return false;
682     }
683   }
684
685   // Finally, report it.
686   EmitDiag(Diag, DiagLevel);
687   return true;
688 }
689
690 void DiagnosticIDs::EmitDiag(DiagnosticsEngine &Diag, Level DiagLevel) const {
691   Diagnostic Info(&Diag);
692   assert(DiagLevel != DiagnosticIDs::Ignored && "Cannot emit ignored diagnostics!");
693
694   Diag.Client->HandleDiagnostic((DiagnosticsEngine::Level)DiagLevel, Info);
695   if (Diag.Client->IncludeInDiagnosticCounts()) {
696     if (DiagLevel == DiagnosticIDs::Warning)
697       ++Diag.NumWarnings;
698   }
699
700   Diag.CurDiagID = ~0U;
701 }
702
703 bool DiagnosticIDs::isUnrecoverable(unsigned DiagID) const {
704   if (DiagID >= diag::DIAG_UPPER_LIMIT) {
705     assert(CustomDiagInfo && "Invalid CustomDiagInfo");
706     // Custom diagnostics.
707     return CustomDiagInfo->getLevel(DiagID) >= DiagnosticIDs::Error;
708   }
709
710   // Only errors may be unrecoverable.
711   if (getBuiltinDiagClass(DiagID) < CLASS_ERROR)
712     return false;
713
714   if (DiagID == diag::err_unavailable ||
715       DiagID == diag::err_unavailable_message)
716     return false;
717
718   // Currently we consider all ARC errors as recoverable.
719   if (isARCDiagnostic(DiagID))
720     return false;
721
722   return true;
723 }
724
725 bool DiagnosticIDs::isARCDiagnostic(unsigned DiagID) {
726   unsigned cat = getCategoryNumberForDiag(DiagID);
727   return DiagnosticIDs::getCategoryNameFromID(cat).startswith("ARC ");
728 }