Debian Codegraph @

clang/lib/Basic/DiagnosticIDs.cpp

raw
1 //===--- DiagnosticIDs.cpp - Diagnostic IDs Handling ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Diagnostic IDs-related interfaces.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/Basic/DiagnosticIDs.h"
14 #include "clang/Basic/AllDiagnostics.h"
15 #include "clang/Basic/DiagnosticCategories.h"
16 #include "clang/Basic/LangOptions.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringTable.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include <map>
24 #include <optional>
25 using namespace clang;
26
27 //===----------------------------------------------------------------------===//
28 // Builtin Diagnostic information
29 //===----------------------------------------------------------------------===//
30
31 namespace {
32
33 struct StaticDiagInfoRec;
34
35 // Store the descriptions in a separate table to avoid pointers that need to
36 // be relocated, and also decrease the amount of data needed on 64-bit
37 // platforms. See "How To Write Shared Libraries" by Ulrich Drepper.
38 struct StaticDiagInfoDescriptionStringTable {
39 #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
40 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
41 char ENUM##_desc[sizeof(DESC)];
42 #include "clang/Basic/AllDiagnosticKinds.inc"
43 #undef DIAG
44 };
45
46 const StaticDiagInfoDescriptionStringTable StaticDiagInfoDescriptions = {
47 #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
48 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
49 DESC,
50 #include "clang/Basic/AllDiagnosticKinds.inc"
51 #undef DIAG
52 };
53
54 extern const StaticDiagInfoRec StaticDiagInfo[];
55
56 // Stored separately from StaticDiagInfoRec to pack better. Otherwise,
57 // StaticDiagInfoRec would have extra padding on 64-bit platforms.
58 const uint32_t StaticDiagInfoDescriptionOffsets[] = {
59 #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
60 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
61 offsetof(StaticDiagInfoDescriptionStringTable, ENUM##_desc),
62 #include "clang/Basic/AllDiagnosticKinds.inc"
63 #undef DIAG
64 };
65
66 enum DiagnosticClass {
67 CLASS_NOTE = DiagnosticIDs::CLASS_NOTE,
68 CLASS_REMARK = DiagnosticIDs::CLASS_REMARK,
69 CLASS_WARNING = DiagnosticIDs::CLASS_WARNING,
70 CLASS_EXTENSION = DiagnosticIDs::CLASS_EXTENSION,
71 CLASS_ERROR = DiagnosticIDs::CLASS_ERROR,
72 CLASS_TRAP = DiagnosticIDs::CLASS_TRAP,
73 };
74
75 struct StaticDiagInfoRec {
76 uint16_t DiagID;
77 LLVM_PREFERRED_TYPE(diag::Severity)
78 uint16_t DefaultSeverity : 3;
79 LLVM_PREFERRED_TYPE(DiagnosticClass)
80 uint16_t Class : 3;
81 LLVM_PREFERRED_TYPE(DiagnosticIDs::SFINAEResponse)
82 uint16_t SFINAE : 2;
83 LLVM_PREFERRED_TYPE(diag::DiagCategory)
84 uint16_t Category : 6;
85 LLVM_PREFERRED_TYPE(bool)
86 uint16_t WarnNoWerror : 1;
87 LLVM_PREFERRED_TYPE(bool)
88 uint16_t WarnShowInSystemHeader : 1;
89 LLVM_PREFERRED_TYPE(bool)
90 uint16_t WarnShowInSystemMacro : 1;
91
92 LLVM_PREFERRED_TYPE(diag::Group)
93 uint16_t OptionGroupIndex : 15;
94 LLVM_PREFERRED_TYPE(bool)
95 uint16_t Deferrable : 1;
96
97 uint16_t DescriptionLen;
98
99 unsigned getOptionGroupIndex() const {
100 return OptionGroupIndex;
101 }
102
103 StringRef getDescription() const {
104 size_t MyIndex = this - &StaticDiagInfo[0];
105 uint32_t StringOffset = StaticDiagInfoDescriptionOffsets[MyIndex];
106 const char* Table = reinterpret_cast<const char*>(&StaticDiagInfoDescriptions);
107 return StringRef(&Table[StringOffset], DescriptionLen);
108 }
109
110 diag::Flavor getFlavor() const {
111 return Class == CLASS_REMARK ? diag::Flavor::Remark
112 : diag::Flavor::WarningOrError;
113 }
114
115 bool operator<(const StaticDiagInfoRec &RHS) const {
116 return DiagID < RHS.DiagID;
117 }
118 };
119
120 #define STRINGIFY_NAME(NAME) #NAME
121 #define VALIDATE_DIAG_SIZE(NAME) \
122 static_assert( \
123 static_cast<unsigned>(diag::NUM_BUILTIN_##NAME##_DIAGNOSTICS) < \
124 static_cast<unsigned>(diag::DIAG_START_##NAME) + \
125 static_cast<unsigned>(diag::DIAG_SIZE_##NAME), \
126 STRINGIFY_NAME( \
127 DIAG_SIZE_##NAME) " is insufficient to contain all " \
128 "diagnostics, it may need to be made larger in " \
129 "DiagnosticIDs.h.");
130 VALIDATE_DIAG_SIZE(COMMON)
131 VALIDATE_DIAG_SIZE(DRIVER)
132 VALIDATE_DIAG_SIZE(FRONTEND)
133 VALIDATE_DIAG_SIZE(SERIALIZATION)
134 VALIDATE_DIAG_SIZE(LEX)
135 VALIDATE_DIAG_SIZE(PARSE)
136 VALIDATE_DIAG_SIZE(AST)
137 VALIDATE_DIAG_SIZE(COMMENT)
138 VALIDATE_DIAG_SIZE(CROSSTU)
139 VALIDATE_DIAG_SIZE(SEMA)
140 VALIDATE_DIAG_SIZE(ANALYSIS)
141 VALIDATE_DIAG_SIZE(REFACTORING)
142 VALIDATE_DIAG_SIZE(INSTALLAPI)
143 VALIDATE_DIAG_SIZE(TRAP)
144 #undef VALIDATE_DIAG_SIZE
145 #undef STRINGIFY_NAME
146
147 const StaticDiagInfoRec StaticDiagInfo[] = {
148 // clang-format off
149 #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \
150 SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY) \
151 { \
152 diag::ENUM, \
153 DEFAULT_SEVERITY, \
154 CLASS, \
155 DiagnosticIDs::SFINAE, \
156 CATEGORY, \
157 NOWERROR, \
158 SHOWINSYSHEADER, \
159 SHOWINSYSMACRO, \
160 GROUP, \
161 DEFERRABLE, \
162 STR_SIZE(DESC, uint16_t)},
163 #include "clang/Basic/DiagnosticCommonKinds.inc"
164 #include "clang/Basic/DiagnosticDriverKinds.inc"
165 #include "clang/Basic/DiagnosticFrontendKinds.inc"
166 #include "clang/Basic/DiagnosticSerializationKinds.inc"
167 #include "clang/Basic/DiagnosticLexKinds.inc"
168 #include "clang/Basic/DiagnosticParseKinds.inc"
169 #include "clang/Basic/DiagnosticASTKinds.inc"
170 #include "clang/Basic/DiagnosticCommentKinds.inc"
171 #include "clang/Basic/DiagnosticCrossTUKinds.inc"
172 #include "clang/Basic/DiagnosticSemaKinds.inc"
173 #include "clang/Basic/DiagnosticAnalysisKinds.inc"
174 #include "clang/Basic/DiagnosticRefactoringKinds.inc"
175 #include "clang/Basic/DiagnosticInstallAPIKinds.inc"
176 #include "clang/Basic/DiagnosticTrapKinds.inc"
177 // clang-format on
178 #undef DIAG
179 };
180
181 } // namespace
182
183 static const unsigned StaticDiagInfoSize = std::size(StaticDiagInfo);
184
185 /// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
186 /// or null if the ID is invalid.
187 static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
188 // Out of bounds diag. Can't be in the table.
189 using namespace diag;
190 if (DiagID >= DIAG_UPPER_LIMIT || DiagID <= DIAG_START_COMMON)
191 return nullptr;
192
193 // Compute the index of the requested diagnostic in the static table.
194 // 1. Add the number of diagnostics in each category preceding the
195 // diagnostic and of the category the diagnostic is in. This gives us
196 // the offset of the category in the table.
197 // 2. Subtract the number of IDs in each category from our ID. This gives us
198 // the offset of the diagnostic in the category.
199 // This is cheaper than a binary search on the table as it doesn't touch
200 // memory at all.
201 unsigned Offset = 0;
202 unsigned ID = DiagID - DIAG_START_COMMON - 1;
203 #define CATEGORY(NAME, PREV) \
204 if (DiagID > DIAG_START_##NAME) { \
205 Offset += NUM_BUILTIN_##PREV##_DIAGNOSTICS - DIAG_START_##PREV - 1; \
206 ID -= DIAG_START_##NAME - DIAG_START_##PREV; \
207 }
208 CATEGORY(DRIVER, COMMON)
209 CATEGORY(FRONTEND, DRIVER)
210 CATEGORY(SERIALIZATION, FRONTEND)
211 CATEGORY(LEX, SERIALIZATION)
212 CATEGORY(PARSE, LEX)
213 CATEGORY(AST, PARSE)
214 CATEGORY(COMMENT, AST)
215 CATEGORY(CROSSTU, COMMENT)
216 CATEGORY(SEMA, CROSSTU)
217 CATEGORY(ANALYSIS, SEMA)
218 CATEGORY(REFACTORING, ANALYSIS)
219 CATEGORY(INSTALLAPI, REFACTORING)
220 CATEGORY(TRAP, INSTALLAPI)
221 #undef CATEGORY
222
223 // Avoid out of bounds reads.
224 if (ID + Offset >= StaticDiagInfoSize)
225 return nullptr;
226
227 assert(ID < StaticDiagInfoSize && Offset < StaticDiagInfoSize);
228
229 const StaticDiagInfoRec *Found = &StaticDiagInfo[ID + Offset];
230 // If the diag id doesn't match we found a different diag, abort. This can
231 // happen when this function is called with an ID that points into a hole in
232 // the diagID space.
233 if (Found->DiagID != DiagID)
234 return nullptr;
235 return Found;
236 }
237
238 //===----------------------------------------------------------------------===//
239 // Custom Diagnostic information
240 //===----------------------------------------------------------------------===//
241
242 namespace clang {
243 namespace diag {
244 using CustomDiagDesc = DiagnosticIDs::CustomDiagDesc;
245 class CustomDiagInfo {
246 std::vector<CustomDiagDesc> DiagInfo;
247 std::map<CustomDiagDesc, unsigned> DiagIDs;
248 std::map<diag::Group, std::vector<unsigned>> GroupToDiags;
249
250 public:
251 /// getDescription - Return the description of the specified custom
252 /// diagnostic.
253 const CustomDiagDesc &getDescription(unsigned DiagID) const {
254 assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() &&
255 "Invalid diagnostic ID");
256 return DiagInfo[DiagID - DIAG_UPPER_LIMIT];
257 }
258
259 unsigned getOrCreateDiagID(DiagnosticIDs::CustomDiagDesc D) {
260 // Check to see if it already exists.
261 std::map<CustomDiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
262 if (I != DiagIDs.end() && I->first == D)
263 return I->second;
264
265 // If not, assign a new ID.
266 unsigned ID = DiagInfo.size() + DIAG_UPPER_LIMIT;
267 DiagIDs.insert(std::make_pair(D, ID));
268 DiagInfo.push_back(D);
269 if (auto Group = D.GetGroup())
270 GroupToDiags[*Group].emplace_back(ID);
271 return ID;
272 }
273
274 ArrayRef<unsigned> getDiagsInGroup(diag::Group G) const {
275 if (auto Diags = GroupToDiags.find(G); Diags != GroupToDiags.end())
276 return Diags->second;
277 return {};
278 }
279 };
280
281 } // namespace diag
282 } // namespace clang
283
284 DiagnosticMapping DiagnosticIDs::getDefaultMapping(unsigned DiagID) const {
285 DiagnosticMapping Info = DiagnosticMapping::Make(
286 diag::Severity::Fatal, /*IsUser=*/false, /*IsPragma=*/false);
287
288 if (IsCustomDiag(DiagID)) {
289 Info.setSeverity(
290 CustomDiagInfo->getDescription(DiagID).GetDefaultSeverity());
291 } else if (const StaticDiagInfoRec *StaticInfo = GetDiagInfo(DiagID)) {
292 Info.setSeverity((diag::Severity)StaticInfo->DefaultSeverity);
293
294 if (StaticInfo->WarnNoWerror) {
295 assert(Info.getSeverity() == diag::Severity::Warning &&
296 "Unexpected mapping with no-Werror bit!");
297 Info.setNoWarningAsError(true);
298 }
299 }
300
301 return Info;
302 }
303
304 void DiagnosticIDs::initCustomDiagMapping(DiagnosticMapping &Mapping,
305 unsigned DiagID) {
306 assert(IsCustomDiag(DiagID));
307 const auto &Diag = CustomDiagInfo->getDescription(DiagID);
308 if (auto Group = Diag.GetGroup()) {
309 GroupInfo GroupInfo = GroupInfos[static_cast<size_t>(*Group)];
310 if (static_cast<diag::Severity>(GroupInfo.Severity) != diag::Severity())
311 Mapping.setSeverity(static_cast<diag::Severity>(GroupInfo.Severity));
312 Mapping.setNoWarningAsError(GroupInfo.HasNoWarningAsError);
313 } else {
314 Mapping.setSeverity(Diag.GetDefaultSeverity());
315 Mapping.setNoWarningAsError(true);
316 Mapping.setNoErrorAsFatal(true);
317 }
318 }
319
320 /// getCategoryNumberForDiag - Return the category number that a specified
321 /// DiagID belongs to, or 0 if no category.
322 unsigned DiagnosticIDs::getCategoryNumberForDiag(unsigned DiagID) {
323 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
324 return Info->Category;
325 return 0;
326 }
327
328 namespace {
329 // The diagnostic category names.
330 struct StaticDiagCategoryRec {
331 const char *NameStr;
332 uint8_t NameLen;
333
334 StringRef getName() const {
335 return StringRef(NameStr, NameLen);
336 }
337 };
338 }
339
340 static const StaticDiagCategoryRec CategoryNameTable[] = {
341 #define GET_CATEGORY_TABLE
342 #define CATEGORY(X, ENUM) { X, STR_SIZE(X, uint8_t) },
343 #include "clang/Basic/DiagnosticGroups.inc"
344 #undef GET_CATEGORY_TABLE
345 { nullptr, 0 }
346 };
347
348 /// getNumberOfCategories - Return the number of categories
349 unsigned DiagnosticIDs::getNumberOfCategories() {
350 return std::size(CategoryNameTable) - 1;
351 }
352
353 /// getCategoryNameFromID - Given a category ID, return the name of the
354 /// category, an empty string if CategoryID is zero, or null if CategoryID is
355 /// invalid.
356 StringRef DiagnosticIDs::getCategoryNameFromID(unsigned CategoryID) {
357 if (CategoryID >= getNumberOfCategories())
358 return StringRef();
359 return CategoryNameTable[CategoryID].getName();
360 }
361
362
363
364 DiagnosticIDs::SFINAEResponse
365 DiagnosticIDs::getDiagnosticSFINAEResponse(unsigned DiagID) {
366 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
367 return static_cast<DiagnosticIDs::SFINAEResponse>(Info->SFINAE);
368 return SFINAE_Report;
369 }
370
371 bool DiagnosticIDs::isDeferrable(unsigned DiagID) {
372 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
373 return Info->Deferrable;
374 return false;
375 }
376
377 //===----------------------------------------------------------------------===//
378 // Common Diagnostic implementation
379 //===----------------------------------------------------------------------===//
380
381 DiagnosticIDs::DiagnosticIDs() {}
382
383 DiagnosticIDs::~DiagnosticIDs() {}
384
385 /// getCustomDiagID - Return an ID for a diagnostic with the specified message
386 /// and level. If this is the first request for this diagnostic, it is
387 /// registered and created, otherwise the existing ID is returned.
388 ///
389 /// \param FormatString A fixed diagnostic format string that will be hashed and
390 /// mapped to a unique DiagID.
391 unsigned DiagnosticIDs::getCustomDiagID(CustomDiagDesc Diag) {
392 if (!CustomDiagInfo)
393 CustomDiagInfo.reset(new diag::CustomDiagInfo());
394 return CustomDiagInfo->getOrCreateDiagID(Diag);
395 }
396
397 bool DiagnosticIDs::isWarningOrExtension(unsigned DiagID) const {
398 return DiagID < diag::DIAG_UPPER_LIMIT
399 ? getDiagClass(DiagID) != CLASS_ERROR
400 : CustomDiagInfo->getDescription(DiagID).GetClass() != CLASS_ERROR;
401 }
402
403 /// Determine whether the given built-in diagnostic ID is a
404 /// Note.
405 bool DiagnosticIDs::isNote(unsigned DiagID) const {
406 return DiagID < diag::DIAG_UPPER_LIMIT && getDiagClass(DiagID) == CLASS_NOTE;
407 }
408
409 /// isExtensionDiag - Determine whether the given built-in diagnostic
410 /// ID is for an extension of some sort. This also returns EnabledByDefault,
411 /// which is set to indicate whether the diagnostic is ignored by default (in
412 /// which case -pedantic enables it) or treated as a warning/error by default.
413 ///
414 bool DiagnosticIDs::isExtensionDiag(unsigned DiagID,
415 bool &EnabledByDefault) const {
416 if (IsCustomDiag(DiagID) || getDiagClass(DiagID) != CLASS_EXTENSION)
417 return false;
418
419 EnabledByDefault =
420 getDefaultMapping(DiagID).getSeverity() != diag::Severity::Ignored;
421 return true;
422 }
423
424 bool DiagnosticIDs::isDefaultMappingAsError(unsigned DiagID) const {
425 return getDefaultMapping(DiagID).getSeverity() >= diag::Severity::Error;
426 }
427
428 /// getDescription - Given a diagnostic ID, return a description of the
429 /// issue.
430 StringRef DiagnosticIDs::getDescription(unsigned DiagID) const {
431 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
432 return Info->getDescription();
433 assert(CustomDiagInfo && "Invalid CustomDiagInfo");
434 return CustomDiagInfo->getDescription(DiagID).GetDescription();
435 }
436
437 static DiagnosticIDs::Level toLevel(diag::Severity SV) {
438 switch (SV) {
439 case diag::Severity::Ignored:
440 return DiagnosticIDs::Ignored;
441 case diag::Severity::Remark:
442 return DiagnosticIDs::Remark;
443 case diag::Severity::Warning:
444 return DiagnosticIDs::Warning;
445 case diag::Severity::Error:
446 return DiagnosticIDs::Error;
447 case diag::Severity::Fatal:
448 return DiagnosticIDs::Fatal;
449 }
450 llvm_unreachable("unexpected severity");
451 }
452
453 /// getDiagnosticLevel - Based on the way the client configured the
454 /// DiagnosticsEngine object, classify the specified diagnostic ID into a Level,
455 /// by consumable the DiagnosticClient.
456 DiagnosticIDs::Level
457 DiagnosticIDs::getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
458 const DiagnosticsEngine &Diag) const {
459 unsigned DiagClass = getDiagClass(DiagID);
460 if (DiagClass == CLASS_NOTE) return DiagnosticIDs::Note;
461 return toLevel(getDiagnosticSeverity(DiagID, Loc, Diag));
462 }
463
464 /// Based on the way the client configured the Diagnostic
465 /// object, classify the specified diagnostic ID into a Level, consumable by
466 /// the DiagnosticClient.
467 ///
468 /// \param Loc The source location we are interested in finding out the
469 /// diagnostic state. Can be null in order to query the latest state.
470 diag::Severity
471 DiagnosticIDs::getDiagnosticSeverity(unsigned DiagID, SourceLocation Loc,
472 const DiagnosticsEngine &Diag) const {
473 bool IsCustomDiag = DiagnosticIDs::IsCustomDiag(DiagID);
474 assert(getDiagClass(DiagID) != CLASS_NOTE);
475
476 // Specific non-error diagnostics may be mapped to various levels from ignored
477 // to error. Errors can only be mapped to fatal.
478 diag::Severity Result = diag::Severity::Fatal;
479
480 // Get the mapping information, or compute it lazily.
481 DiagnosticsEngine::DiagState *State = Diag.GetDiagStateForLoc(Loc);
482 DiagnosticMapping Mapping = State->getOrAddMapping((diag::kind)DiagID);
483
484 // TODO: Can a null severity really get here?
485 if (Mapping.getSeverity() != diag::Severity())
486 Result = Mapping.getSeverity();
487
488 // Upgrade ignored diagnostics if -Weverything is enabled.
489 if (State->EnableAllWarnings && Result == diag::Severity::Ignored &&
490 !Mapping.isUser() &&
491 (IsCustomDiag || getDiagClass(DiagID) != CLASS_REMARK))
492 Result = diag::Severity::Warning;
493
494 // Ignore -pedantic diagnostics inside __extension__ blocks.
495 // (The diagnostics controlled by -pedantic are the extension diagnostics
496 // that are not enabled by default.)
497 bool EnabledByDefault = false;
498 bool IsExtensionDiag = isExtensionDiag(DiagID, EnabledByDefault);
499 if (Diag.AllExtensionsSilenced && IsExtensionDiag && !EnabledByDefault)
500 return diag::Severity::Ignored;
501
502 // For extension diagnostics that haven't been explicitly mapped, check if we
503 // should upgrade the diagnostic.
504 if (IsExtensionDiag && !Mapping.isUser()) {
505 if (Mapping.hasNoWarningAsError())
506 Result = std::max(Result,
507 std::min(State->ExtBehavior, diag::Severity::Warning));
508 else
509 Result = std::max(Result, State->ExtBehavior);
510 }
511
512 // At this point, ignored errors can no longer be upgraded.
513 if (Result == diag::Severity::Ignored)
514 return Result;
515
516 // Honor -w: this disables all messages which are not Error/Fatal by
517 // default (disregarding attempts to upgrade severity from Warning to Error),
518 // as well as disabling all messages which are currently mapped to Warning
519 // (whether by default or downgraded from Error via e.g. -Wno-error or #pragma
520 // diagnostic.)
521 // FIXME: Should -w be ignored for custom warnings without a group?
522 if (State->IgnoreAllWarnings) {
523 if ((!IsCustomDiag || CustomDiagInfo->getDescription(DiagID).GetGroup()) &&
524 (Result == diag::Severity::Warning ||
525 (Result >= diag::Severity::Error &&
526 !isDefaultMappingAsError((diag::kind)DiagID))))
527 return diag::Severity::Ignored;
528 }
529
530 // If -Werror is enabled, map warnings to errors unless explicitly disabled.
531 if (Result == diag::Severity::Warning) {
532 if (State->WarningsAsErrors && !Mapping.hasNoWarningAsError())
533 Result = diag::Severity::Error;
534 }
535
536 // If -Wfatal-errors is enabled, map errors to fatal unless explicitly
537 // disabled.
538 if (Result == diag::Severity::Error) {
539 if (State->ErrorsAsFatal && !Mapping.hasNoErrorAsFatal())
540 Result = diag::Severity::Fatal;
541 }
542
543 // If explicitly requested, map fatal errors to errors.
544 if (Result == diag::Severity::Fatal &&
545 DiagID != diag::fatal_too_many_errors && Diag.FatalsAsError)
546 Result = diag::Severity::Error;
547
548 // Rest of the mappings are only applicable for diagnostics associated with a
549 // SourceLocation, bail out early for others.
550 if (!Diag.hasSourceManager())
551 return Result;
552
553 const auto &SM = Diag.getSourceManager();
554 // If we are in a system header, we ignore it. We look at the diagnostic class
555 // because we also want to ignore extensions and warnings in -Werror and
556 // -pedantic-errors modes, which *map* warnings/extensions to errors.
557 if (State->SuppressSystemWarnings && Loc.isValid() &&
558 SM.isInSystemHeader(SM.getExpansionLoc(Loc))) {
559 bool ShowInSystemHeader = true;
560 if (IsCustomDiag)
561 ShowInSystemHeader =
562 CustomDiagInfo->getDescription(DiagID).ShouldShowInSystemHeader();
563 else if (const StaticDiagInfoRec *Rec = GetDiagInfo(DiagID))
564 ShowInSystemHeader = Rec->WarnShowInSystemHeader;
565
566 if (!ShowInSystemHeader)
567 return diag::Severity::Ignored;
568 }
569 // We also ignore warnings due to system macros
570 if (State->SuppressSystemWarnings && Loc.isValid()) {
571
572 bool ShowInSystemMacro = true;
573 if (const StaticDiagInfoRec *Rec = GetDiagInfo(DiagID))
574 ShowInSystemMacro = Rec->WarnShowInSystemMacro;
575
576 if (!ShowInSystemMacro && SM.isInSystemMacro(Loc))
577 return diag::Severity::Ignored;
578 }
579 // Clang-diagnostics pragmas always take precedence over suppression mapping.
580 if (!Mapping.isPragma() && Diag.isSuppressedViaMapping(DiagID, Loc))
581 return diag::Severity::Ignored;
582
583 return Result;
584 }
585
586 DiagnosticIDs::Class DiagnosticIDs::getDiagClass(unsigned DiagID) const {
587 if (IsCustomDiag(DiagID))
588 return Class(CustomDiagInfo->getDescription(DiagID).GetClass());
589
590 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
591 return Class(Info->Class);
592 return CLASS_INVALID;
593 }
594
595 #define GET_DIAG_ARRAYS
596 #include "clang/Basic/DiagnosticGroups.inc"
597 #undef GET_DIAG_ARRAYS
598
599 namespace {
600 struct WarningOption {
601 uint16_t NameOffset;
602 uint16_t Members;
603 uint16_t SubGroups;
604 StringRef Documentation;
605
606 StringRef getName() const { return DiagGroupNames[NameOffset]; }
607 };
608 }
609
610 // Second the table of options, sorted by name for fast binary lookup.
611 static const WarningOption OptionTable[] = {
612 #define DIAG_ENTRY(GroupName, FlagNameOffset, Members, SubGroups, Docs) \
613 {FlagNameOffset, Members, SubGroups, Docs},
614 #include "clang/Basic/DiagnosticGroups.inc"
615 #undef DIAG_ENTRY
616 };
617
618 /// Given a diagnostic group ID, return its documentation.
619 StringRef DiagnosticIDs::getWarningOptionDocumentation(diag::Group Group) {
620 return OptionTable[static_cast<int>(Group)].Documentation;
621 }
622
623 StringRef DiagnosticIDs::getWarningOptionForGroup(diag::Group Group) {
624 return OptionTable[static_cast<int>(Group)].getName();
625 }
626
627 std::optional<diag::Group>
628 DiagnosticIDs::getGroupForWarningOption(StringRef Name) {
629 const auto *Found = llvm::partition_point(
630 OptionTable, [=](const WarningOption &O) { return O.getName() < Name; });
631 if (Found == std::end(OptionTable) || Found->getName() != Name)
632 return std::nullopt;
633 return static_cast<diag::Group>(Found - OptionTable);
634 }
635
636 std::optional<diag::Group>
637 DiagnosticIDs::getGroupForDiag(unsigned DiagID) const {
638 if (IsCustomDiag(DiagID)) {
639 assert(CustomDiagInfo);
640 return CustomDiagInfo->getDescription(DiagID).GetGroup();
641 }
642 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
643 return static_cast<diag::Group>(Info->getOptionGroupIndex());
644 return std::nullopt;
645 }
646
647 /// getWarningOptionForDiag - Return the lowest-level warning option that
648 /// enables the specified diagnostic. If there is no -Wfoo flag that controls
649 /// the diagnostic, this returns null.
650 StringRef DiagnosticIDs::getWarningOptionForDiag(unsigned DiagID) {
651 if (auto G = getGroupForDiag(DiagID))
652 return getWarningOptionForGroup(*G);
653 return StringRef();
654 }
655
656 std::vector<std::string> DiagnosticIDs::getDiagnosticFlags() {
657 std::vector<std::string> Res{"-W", "-Wno-"};
658 for (StringRef Name : DiagGroupNames) {
659 if (Name.empty())
660 continue;
661
662 Res.push_back((Twine("-W") + Name).str());
663 Res.push_back((Twine("-Wno-") + Name).str());
664 }
665
666 return Res;
667 }
668
669 /// Return \c true if any diagnostics were found in this group, even if they
670 /// were filtered out due to having the wrong flavor.
671 static bool getDiagnosticsInGroup(diag::Flavor Flavor,
672 const WarningOption *Group,
673 SmallVectorImpl<diag::kind> &Diags,
674 diag::CustomDiagInfo *CustomDiagInfo) {
675 // An empty group is considered to be a warning group: we have empty groups
676 // for GCC compatibility, and GCC does not have remarks.
677 if (!Group->Members && !Group->SubGroups)
678 return Flavor == diag::Flavor::Remark;
679
680 bool NotFound = true;
681
682 // Add the members of the option diagnostic set.
683 const int16_t *Member = DiagArrays + Group->Members;
684 for (; *Member != -1; ++Member) {
685 if (GetDiagInfo(*Member)->getFlavor() == Flavor) {
686 NotFound = false;
687 Diags.push_back(*Member);
688 }
689 }
690
691 // Add the members of the subgroups.
692 const int16_t *SubGroups = DiagSubGroups + Group->SubGroups;
693 for (; *SubGroups != (int16_t)-1; ++SubGroups) {
694 if (CustomDiagInfo)
695 llvm::copy(
696 CustomDiagInfo->getDiagsInGroup(static_cast<diag::Group>(*SubGroups)),
697 std::back_inserter(Diags));
698 NotFound &= getDiagnosticsInGroup(Flavor, &OptionTable[(short)*SubGroups],
699 Diags, CustomDiagInfo);
700 }
701
702 return NotFound;
703 }
704
705 bool
706 DiagnosticIDs::getDiagnosticsInGroup(diag::Flavor Flavor, StringRef Group,
707 SmallVectorImpl<diag::kind> &Diags) const {
708 if (std::optional<diag::Group> G = getGroupForWarningOption(Group)) {
709 if (CustomDiagInfo)
710 llvm::copy(CustomDiagInfo->getDiagsInGroup(*G),
711 std::back_inserter(Diags));
712 return ::getDiagnosticsInGroup(Flavor,
713 &OptionTable[static_cast<unsigned>(*G)],
714 Diags, CustomDiagInfo.get());
715 }
716 return true;
717 }
718
719 template <class Func>
720 static void forEachSubGroupImpl(const WarningOption *Group, Func func) {
721 for (const int16_t *SubGroups = DiagSubGroups + Group->SubGroups;
722 *SubGroups != -1; ++SubGroups) {
723 func(static_cast<size_t>(*SubGroups));
724 forEachSubGroupImpl(&OptionTable[*SubGroups], func);
725 }
726 }
727
728 template <class Func>
729 static void forEachSubGroup(diag::Group Group, Func func) {
730 const WarningOption *WarningOpt = &OptionTable[static_cast<size_t>(Group)];
731 func(static_cast<size_t>(Group));
732 ::forEachSubGroupImpl(WarningOpt, std::move(func));
733 }
734
735 void DiagnosticIDs::setGroupSeverity(StringRef Group, diag::Severity Sev) {
736 if (std::optional<diag::Group> G = getGroupForWarningOption(Group)) {
737 ::forEachSubGroup(*G, [&](size_t SubGroup) {
738 GroupInfos[SubGroup].Severity = static_cast<unsigned>(Sev);
739 });
740 }
741 }
742
743 void DiagnosticIDs::setGroupNoWarningsAsError(StringRef Group, bool Val) {
744 if (std::optional<diag::Group> G = getGroupForWarningOption(Group)) {
745 ::forEachSubGroup(*G, [&](size_t SubGroup) {
746 GroupInfos[static_cast<size_t>(*G)].HasNoWarningAsError = Val;
747 });
748 }
749 }
750
751 void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
752 std::vector<diag::kind> &Diags) {
753 for (unsigned i = 0; i != StaticDiagInfoSize; ++i)
754 if (StaticDiagInfo[i].getFlavor() == Flavor)
755 Diags.push_back(StaticDiagInfo[i].DiagID);
756 }
757
758 StringRef DiagnosticIDs::getNearestOption(diag::Flavor Flavor,
759 StringRef Group) {
760 StringRef Best;
761 unsigned BestDistance = Group.size() + 1; // Maximum threshold.
762 for (const WarningOption &O : OptionTable) {
763 // Don't suggest ignored warning flags.
764 if (!O.Members && !O.SubGroups)
765 continue;
766
767 unsigned Distance = O.getName().edit_distance(Group, true, BestDistance);
768 if (Distance > BestDistance)
769 continue;
770
771 // Don't suggest groups that are not of this kind.
772 llvm::SmallVector<diag::kind, 8> Diags;
773 if (::getDiagnosticsInGroup(Flavor, &O, Diags, nullptr) || Diags.empty())
774 continue;
775
776 if (Distance == BestDistance) {
777 // Two matches with the same distance, don't prefer one over the other.
778 Best = "";
779 } else if (Distance < BestDistance) {
780 // This is a better match.
781 Best = O.getName();
782 BestDistance = Distance;
783 }
784 }
785
786 return Best;
787 }
788
789 unsigned DiagnosticIDs::getCXXCompatDiagId(const LangOptions &LangOpts,
790 unsigned CompatDiagId) {
791 struct CompatDiag {
792 unsigned StdVer;
793 unsigned DiagId;
794 unsigned PreDiagId;
795 };
796
797 // We encode the standard version such that C++98 < C++11 < C++14 etc. The
798 // actual numbers don't really matter for this, but the definitions of the
799 // compat diags in the Tablegen file use the standard version number (i.e.
800 // 98, 11, 14, etc.), so we base the encoding here on that.
801 #define DIAG_COMPAT_IDS_BEGIN()
802 #define DIAG_COMPAT_IDS_END()
803 #define DIAG_COMPAT_ID(Value, Name, Std, Diag, DiagPre) \
804 {Std == 98 ? 1998 : 2000 + Std, diag::Diag, diag::DiagPre},
805 static constexpr CompatDiag Diags[]{
806 #include "clang/Basic/DiagnosticAllCompatIDs.inc"
807 };
808 #undef DIAG_COMPAT_ID
809 #undef DIAG_COMPAT_IDS_BEGIN
810 #undef DIAG_COMPAT_IDS_END
811
812 assert(CompatDiagId < std::size(Diags) && "Invalid compat diag id");
813
814 unsigned StdVer = [&] {
815 if (LangOpts.CPlusPlus26)
816 return 2026;
817 if (LangOpts.CPlusPlus23)
818 return 2023;
819 if (LangOpts.CPlusPlus20)
820 return 2020;
821 if (LangOpts.CPlusPlus17)
822 return 2017;
823 if (LangOpts.CPlusPlus14)
824 return 2014;
825 if (LangOpts.CPlusPlus11)
826 return 2011;
827 return 1998;
828 }();
829
830 const CompatDiag &D = Diags[CompatDiagId];
831 return StdVer >= D.StdVer ? D.DiagId : D.PreDiagId;
832 }
833
834 bool DiagnosticIDs::isUnrecoverable(unsigned DiagID) const {
835 // Only errors may be unrecoverable.
836 if (getDiagClass(DiagID) < CLASS_ERROR)
837 return false;
838
839 if (DiagID == diag::err_unavailable ||
840 DiagID == diag::err_unavailable_message)
841 return false;
842
843 // All ARC errors are currently considered recoverable, with the exception of
844 // err_arc_may_not_respond. This specific error is treated as unrecoverable
845 // because sending a message with an unknown selector could lead to crashes
846 // within CodeGen if the resulting expression is used to initialize a C++
847 // auto variable, where type deduction is required.
848 if (isARCDiagnostic(DiagID) && DiagID != diag::err_arc_may_not_respond)
849 return false;
850
851 if (isCodegenABICheckDiagnostic(DiagID))
852 return false;
853
854 return true;
855 }
856
857 bool DiagnosticIDs::isARCDiagnostic(unsigned DiagID) {
858 unsigned cat = getCategoryNumberForDiag(DiagID);
859 return DiagnosticIDs::getCategoryNameFromID(cat).starts_with("ARC ");
860 }
861
862 bool DiagnosticIDs::isCodegenABICheckDiagnostic(unsigned DiagID) {
863 unsigned cat = getCategoryNumberForDiag(DiagID);
864 return DiagnosticIDs::getCategoryNameFromID(cat) == "Codegen ABI Check";
865 }