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