Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Basic/Diagnostic.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Diagnostic.cpp - C Language Family Diagnostic 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-related interfaces.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Basic/Diagnostic.h"
14
#include "clang/Basic/CharInfo.h"
15
#include "clang/Basic/DiagnosticError.h"
16
#include "clang/Basic/DiagnosticIDs.h"
17
#include "clang/Basic/DiagnosticOptions.h"
18
#include "clang/Basic/IdentifierTable.h"
19
#include "clang/Basic/PartialDiagnostic.h"
20
#include "clang/Basic/SourceLocation.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "clang/Basic/Specifiers.h"
23
#include "clang/Basic/TokenKinds.h"
24
#include "llvm/ADT/SmallString.h"
25
#include "llvm/ADT/SmallVector.h"
26
#include "llvm/ADT/StringExtras.h"
27
#include "llvm/ADT/StringRef.h"
28
#include "llvm/Support/CrashRecoveryContext.h"
29
#include "llvm/Support/Locale.h"
30
#include "llvm/Support/raw_ostream.h"
31
#include <algorithm>
32
#include <cassert>
33
#include <cstddef>
34
#include <cstdint>
35
#include <cstring>
36
#include <limits>
37
#include <string>
38
#include <utility>
39
#include <vector>
40
41
using namespace clang;
42
43
const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
44
132
                                           DiagNullabilityKind nullability) {
45
132
  StringRef string;
46
132
  switch (nullability.first) {
47
85
  case NullabilityKind::NonNull:
48
85
    string = nullability.second ? 
"'nonnull'"11
:
"'_Nonnull'"74
;
49
85
    break;
50
0
51
40
  case NullabilityKind::Nullable:
52
40
    string = nullability.second ? 
"'nullable'"19
:
"'_Nullable'"21
;
53
40
    break;
54
0
55
7
  case NullabilityKind::Unspecified:
56
7
    string = nullability.second ? 
"'null_unspecified'"4
:
"'_Null_unspecified'"3
;
57
7
    break;
58
132
  }
59
132
60
132
  DB.AddString(string);
61
132
  return DB;
62
132
}
63
64
static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
65
                            StringRef Modifier, StringRef Argument,
66
                            ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
67
                            SmallVectorImpl<char> &Output,
68
                            void *Cookie,
69
0
                            ArrayRef<intptr_t> QualTypeVals) {
70
0
  StringRef Str = "<can't format argument>";
71
0
  Output.append(Str.begin(), Str.end());
72
0
}
73
74
DiagnosticsEngine::DiagnosticsEngine(
75
    IntrusiveRefCntPtr<DiagnosticIDs> diags,
76
    IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, DiagnosticConsumer *client,
77
    bool ShouldOwnClient)
78
201k
    : Diags(std::move(diags)), DiagOpts(std::move(DiagOpts)) {
79
201k
  setClient(client, ShouldOwnClient);
80
201k
  ArgToStringFn = DummyArgToStringFn;
81
201k
82
201k
  Reset();
83
201k
}
84
85
193k
DiagnosticsEngine::~DiagnosticsEngine() {
86
193k
  // If we own the diagnostic client, destroy it first so that it can access the
87
193k
  // engine from its destructor.
88
193k
  setClient(nullptr);
89
193k
}
90
91
0
void DiagnosticsEngine::dump() const {
92
0
  DiagStatesByLoc.dump(*SourceMgr);
93
0
}
94
95
0
void DiagnosticsEngine::dump(StringRef DiagName) const {
96
0
  DiagStatesByLoc.dump(*SourceMgr, DiagName);
97
0
}
98
99
void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
100
546k
                                  bool ShouldOwnClient) {
101
546k
  Owner.reset(ShouldOwnClient ? 
client484k
:
nullptr62.7k
);
102
546k
  Client = client;
103
546k
}
104
105
13.3k
void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
106
13.3k
  DiagStateOnPushStack.push_back(GetCurDiagState());
107
13.3k
}
108
109
13.3k
bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
110
13.3k
  if (DiagStateOnPushStack.empty())
111
2
    return false;
112
13.3k
113
13.3k
  if (DiagStateOnPushStack.back() != GetCurDiagState()) {
114
13.3k
    // State changed at some point between push/pop.
115
13.3k
    PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
116
13.3k
  }
117
13.3k
  DiagStateOnPushStack.pop_back();
118
13.3k
  return true;
119
13.3k
}
120
121
208k
void DiagnosticsEngine::Reset() {
122
208k
  ErrorOccurred = false;
123
208k
  UncompilableErrorOccurred = false;
124
208k
  FatalErrorOccurred = false;
125
208k
  UnrecoverableErrorOccurred = false;
126
208k
127
208k
  NumWarnings = 0;
128
208k
  NumErrors = 0;
129
208k
  TrapNumErrorsOccurred = 0;
130
208k
  TrapNumUnrecoverableErrorsOccurred = 0;
131
208k
132
208k
  CurDiagID = std::numeric_limits<unsigned>::max();
133
208k
  LastDiagLevel = DiagnosticIDs::Ignored;
134
208k
  DelayedDiagID = 0;
135
208k
136
208k
  // Clear state related to #pragma diagnostic.
137
208k
  DiagStates.clear();
138
208k
  DiagStatesByLoc.clear();
139
208k
  DiagStateOnPushStack.clear();
140
208k
141
208k
  // Create a DiagState and DiagStatePoint representing diagnostic changes
142
208k
  // through command-line.
143
208k
  DiagStates.emplace_back();
144
208k
  DiagStatesByLoc.appendFirst(&DiagStates.back());
145
208k
}
146
147
void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
148
7
                                             StringRef Arg2, StringRef Arg3) {
149
7
  if (DelayedDiagID)
150
0
    return;
151
7
152
7
  DelayedDiagID = DiagID;
153
7
  DelayedDiagArg1 = Arg1.str();
154
7
  DelayedDiagArg2 = Arg2.str();
155
7
  DelayedDiagArg3 = Arg3.str();
156
7
}
157
158
7
void DiagnosticsEngine::ReportDelayed() {
159
7
  unsigned ID = DelayedDiagID;
160
7
  DelayedDiagID = 0;
161
7
  Report(ID) << DelayedDiagArg1 << DelayedDiagArg2 << DelayedDiagArg3;
162
7
}
163
164
208k
void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {
165
208k
  assert(Files.empty() && "not first");
166
208k
  FirstDiagState = CurDiagState = State;
167
208k
  CurDiagStateLoc = SourceLocation();
168
208k
}
169
170
void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
171
                                             SourceLocation Loc,
172
28.7k
                                             DiagState *State) {
173
28.7k
  CurDiagState = State;
174
28.7k
  CurDiagStateLoc = Loc;
175
28.7k
176
28.7k
  std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
177
28.7k
  unsigned Offset = Decomp.second;
178
263k
  for (File *F = getFile(SrcMgr, Decomp.first); F;
179
234k
       Offset = F->ParentOffset, F = F->Parent) {
180
234k
    F->HasLocalTransitions = true;
181
234k
    auto &Last = F->StateTransitions.back();
182
234k
    assert(Last.Offset <= Offset && "state transitions added out of order");
183
234k
184
234k
    if (Last.Offset == Offset) {
185
173k
      if (Last.State == State)
186
0
        break;
187
173k
      Last.State = State;
188
173k
      continue;
189
173k
    }
190
60.4k
191
60.4k
    F->StateTransitions.push_back({State, Offset});
192
60.4k
  }
193
28.7k
}
194
195
DiagnosticsEngine::DiagState *
196
DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
197
117M
                                        SourceLocation Loc) const {
198
117M
  // Common case: we have not seen any diagnostic pragmas.
199
117M
  if (Files.empty())
200
66.6M
    return FirstDiagState;
201
50.4M
202
50.4M
  std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
203
50.4M
  const File *F = getFile(SrcMgr, Decomp.first);
204
50.4M
  return F->lookup(Decomp.second);
205
50.4M
}
206
207
DiagnosticsEngine::DiagState *
208
53.0M
DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
209
53.0M
  auto OnePastIt =
210
55.2M
      llvm::partition_point(StateTransitions, [=](const DiagStatePoint &P) {
211
55.2M
        return P.Offset <= Offset;
212
55.2M
      });
213
53.0M
  assert(OnePastIt != StateTransitions.begin() && "missing initial state");
214
53.0M
  return OnePastIt[-1].State;
215
53.0M
}
216
217
DiagnosticsEngine::DiagStateMap::File *
218
DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
219
53.0M
                                         FileID ID) const {
220
53.0M
  // Get or insert the File for this ID.
221
53.0M
  auto Range = Files.equal_range(ID);
222
53.0M
  if (Range.first != Range.second)
223
50.4M
    return &Range.first->second;
224
2.61M
  auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
225
2.61M
226
2.61M
  // We created a new File; look up the diagnostic state at the start of it and
227
2.61M
  // initialize it.
228
2.61M
  if (ID.isValid()) {
229
2.60M
    std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
230
2.60M
    F.Parent = getFile(SrcMgr, Decomp.first);
231
2.60M
    F.ParentOffset = Decomp.second;
232
2.60M
    F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
233
2.60M
  } else {
234
3.38k
    // This is the (imaginary) root file into which we pretend all top-level
235
3.38k
    // files are included; it descends from the initial state.
236
3.38k
    //
237
3.38k
    // FIXME: This doesn't guarantee that we use the same ordering as
238
3.38k
    // isBeforeInTranslationUnit in the cases where someone invented another
239
3.38k
    // top-level file and added diagnostic pragmas to it. See the code at the
240
3.38k
    // end of isBeforeInTranslationUnit for the quirks it deals with.
241
3.38k
    F.StateTransitions.push_back({FirstDiagState, 0});
242
3.38k
  }
243
2.61M
  return &F;
244
2.61M
}
245
246
void DiagnosticsEngine::DiagStateMap::dump(SourceManager &SrcMgr,
247
0
                                           StringRef DiagName) const {
248
0
  llvm::errs() << "diagnostic state at ";
249
0
  CurDiagStateLoc.print(llvm::errs(), SrcMgr);
250
0
  llvm::errs() << ": " << CurDiagState << "\n";
251
0
252
0
  for (auto &F : Files) {
253
0
    FileID ID = F.first;
254
0
    File &File = F.second;
255
0
256
0
    bool PrintedOuterHeading = false;
257
0
    auto PrintOuterHeading = [&] {
258
0
      if (PrintedOuterHeading) return;
259
0
      PrintedOuterHeading = true;
260
0
261
0
      llvm::errs() << "File " << &File << " <FileID " << ID.getHashValue()
262
0
                   << ">: " << SrcMgr.getBuffer(ID)->getBufferIdentifier();
263
0
      if (F.second.Parent) {
264
0
        std::pair<FileID, unsigned> Decomp =
265
0
            SrcMgr.getDecomposedIncludedLoc(ID);
266
0
        assert(File.ParentOffset == Decomp.second);
267
0
        llvm::errs() << " parent " << File.Parent << " <FileID "
268
0
                     << Decomp.first.getHashValue() << "> ";
269
0
        SrcMgr.getLocForStartOfFile(Decomp.first)
270
0
              .getLocWithOffset(Decomp.second)
271
0
              .print(llvm::errs(), SrcMgr);
272
0
      }
273
0
      if (File.HasLocalTransitions)
274
0
        llvm::errs() << " has_local_transitions";
275
0
      llvm::errs() << "\n";
276
0
    };
277
0
278
0
    if (DiagName.empty())
279
0
      PrintOuterHeading();
280
0
281
0
    for (DiagStatePoint &Transition : File.StateTransitions) {
282
0
      bool PrintedInnerHeading = false;
283
0
      auto PrintInnerHeading = [&] {
284
0
        if (PrintedInnerHeading) return;
285
0
        PrintedInnerHeading = true;
286
0
287
0
        PrintOuterHeading();
288
0
        llvm::errs() << "  ";
289
0
        SrcMgr.getLocForStartOfFile(ID)
290
0
              .getLocWithOffset(Transition.Offset)
291
0
              .print(llvm::errs(), SrcMgr);
292
0
        llvm::errs() << ": state " << Transition.State << ":\n";
293
0
      };
294
0
295
0
      if (DiagName.empty())
296
0
        PrintInnerHeading();
297
0
298
0
      for (auto &Mapping : *Transition.State) {
299
0
        StringRef Option =
300
0
            DiagnosticIDs::getWarningOptionForDiag(Mapping.first);
301
0
        if (!DiagName.empty() && DiagName != Option)
302
0
          continue;
303
0
304
0
        PrintInnerHeading();
305
0
        llvm::errs() << "    ";
306
0
        if (Option.empty())
307
0
          llvm::errs() << "<unknown " << Mapping.first << ">";
308
0
        else
309
0
          llvm::errs() << Option;
310
0
        llvm::errs() << ": ";
311
0
312
0
        switch (Mapping.second.getSeverity()) {
313
0
        case diag::Severity::Ignored: llvm::errs() << "ignored"; break;
314
0
        case diag::Severity::Remark: llvm::errs() << "remark"; break;
315
0
        case diag::Severity::Warning: llvm::errs() << "warning"; break;
316
0
        case diag::Severity::Error: llvm::errs() << "error"; break;
317
0
        case diag::Severity::Fatal: llvm::errs() << "fatal"; break;
318
0
        }
319
0
320
0
        if (!Mapping.second.isUser())
321
0
          llvm::errs() << " default";
322
0
        if (Mapping.second.isPragma())
323
0
          llvm::errs() << " pragma";
324
0
        if (Mapping.second.hasNoWarningAsError())
325
0
          llvm::errs() << " no-error";
326
0
        if (Mapping.second.hasNoErrorAsFatal())
327
0
          llvm::errs() << " no-fatal";
328
0
        if (Mapping.second.wasUpgradedFromWarning())
329
0
          llvm::errs() << " overruled";
330
0
        llvm::errs() << "\n";
331
0
      }
332
0
    }
333
0
  }
334
0
}
335
336
void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
337
28.7k
                                           SourceLocation Loc) {
338
28.7k
  assert(Loc.isValid() && "Adding invalid loc point");
339
28.7k
  DiagStatesByLoc.append(*SourceMgr, Loc, State);
340
28.7k
}
341
342
void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
343
783k
                                    SourceLocation L) {
344
783k
  assert(Diag < diag::DIAG_UPPER_LIMIT &&
345
783k
         "Can only map builtin diagnostics");
346
783k
  assert((Diags->isBuiltinWarningOrExtension(Diag) ||
347
783k
          (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
348
783k
         "Cannot map errors into warnings!");
349
783k
  assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
350
783k
351
783k
  // Don't allow a mapping to a warning override an error/fatal mapping.
352
783k
  bool WasUpgradedFromWarning = false;
353
783k
  if (Map == diag::Severity::Warning) {
354
166k
    DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
355
166k
    if (Info.getSeverity() == diag::Severity::Error ||
356
166k
        
Info.getSeverity() == diag::Severity::Fatal159k
) {
357
10.3k
      Map = Info.getSeverity();
358
10.3k
      WasUpgradedFromWarning = true;
359
10.3k
    }
360
166k
  }
361
783k
  DiagnosticMapping Mapping = makeUserMapping(Map, L);
362
783k
  Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
363
783k
364
783k
  // Common case; setting all the diagnostics of a group in one place.
365
783k
  if ((L.isInvalid() || 
L == DiagStatesByLoc.getCurDiagStateLoc()207k
) &&
366
783k
      
DiagStatesByLoc.getCurDiagState()768k
) {
367
768k
    // FIXME: This is theoretically wrong: if the current state is shared with
368
768k
    // some other location (via push/pop) we will change the state for that
369
768k
    // other location as well. This cannot currently happen, as we can't update
370
768k
    // the diagnostic state at the same location at which we pop.
371
768k
    DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
372
768k
    return;
373
768k
  }
374
15.3k
375
15.3k
  // A diagnostic pragma occurred, create a new DiagState initialized with
376
15.3k
  // the current one and a new DiagStatePoint to record at which location
377
15.3k
  // the new state became active.
378
15.3k
  DiagStates.push_back(*GetCurDiagState());
379
15.3k
  DiagStates.back().setMapping(Diag, Mapping);
380
15.3k
  PushDiagStatePoint(&DiagStates.back(), L);
381
15.3k
}
382
383
bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
384
                                            StringRef Group, diag::Severity Map,
385
93.2k
                                            SourceLocation Loc) {
386
93.2k
  // Get the diagnostics in this group.
387
93.2k
  SmallVector<diag::kind, 256> GroupDiags;
388
93.2k
  if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
389
42
    return true;
390
93.2k
391
93.2k
  // Set the mapping.
392
93.2k
  for (diag::kind Diag : GroupDiags)
393
697k
    setSeverity(Diag, Map, Loc);
394
93.2k
395
93.2k
  return false;
396
93.2k
}
397
398
bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
399
24.5k
                                                         bool Enabled) {
400
24.5k
  // If we are enabling this feature, just set the diagnostic mappings to map to
401
24.5k
  // errors.
402
24.5k
  if (Enabled)
403
24.5k
    return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
404
24.5k
                               diag::Severity::Error);
405
58
406
58
  // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
407
58
  // potentially downgrade anything already mapped to be a warning.
408
58
409
58
  // Get the diagnostics in this group.
410
58
  SmallVector<diag::kind, 8> GroupDiags;
411
58
  if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
412
58
                                   GroupDiags))
413
0
    return true;
414
58
415
58
  // Perform the mapping change.
416
249
  
for (diag::kind Diag : GroupDiags)58
{
417
249
    DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
418
249
419
249
    if (Info.getSeverity() == diag::Severity::Error ||
420
249
        
Info.getSeverity() == diag::Severity::Fatal131
)
421
118
      Info.setSeverity(diag::Severity::Warning);
422
249
423
249
    Info.setNoWarningAsError(true);
424
249
  }
425
58
426
58
  return false;
427
58
}
428
429
bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
430
1
                                                       bool Enabled) {
431
1
  // If we are enabling this feature, just set the diagnostic mappings to map to
432
1
  // fatal errors.
433
1
  if (Enabled)
434
1
    return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
435
1
                               diag::Severity::Fatal);
436
0
437
0
  // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
438
0
  // and potentially downgrade anything already mapped to be a fatal error.
439
0
440
0
  // Get the diagnostics in this group.
441
0
  SmallVector<diag::kind, 8> GroupDiags;
442
0
  if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
443
0
                                   GroupDiags))
444
0
    return true;
445
0
446
0
  // Perform the mapping change.
447
0
  for (diag::kind Diag : GroupDiags) {
448
0
    DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
449
0
450
0
    if (Info.getSeverity() == diag::Severity::Fatal)
451
0
      Info.setSeverity(diag::Severity::Error);
452
0
453
0
    Info.setNoErrorAsFatal(true);
454
0
  }
455
0
456
0
  return false;
457
0
}
458
459
void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
460
                                          diag::Severity Map,
461
44
                                          SourceLocation Loc) {
462
44
  // Get all the diagnostics.
463
44
  std::vector<diag::kind> AllDiags;
464
44
  DiagnosticIDs::getAllDiagnostics(Flavor, AllDiags);
465
44
466
44
  // Set the mapping.
467
44
  for (diag::kind Diag : AllDiags)
468
187k
    if (Diags->isBuiltinWarningOrExtension(Diag))
469
86.3k
      setSeverity(Diag, Map, Loc);
470
44
}
471
472
150
void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
473
150
  assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
474
150
         "Multiple diagnostics in flight at once!");
475
150
476
150
  CurDiagLoc = storedDiag.getLocation();
477
150
  CurDiagID = storedDiag.getID();
478
150
  NumDiagArgs = 0;
479
150
480
150
  DiagRanges.clear();
481
150
  DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
482
150
483
150
  DiagFixItHints.clear();
484
150
  DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
485
150
486
150
  assert(Client && "DiagnosticConsumer not set!");
487
150
  Level DiagLevel = storedDiag.getLevel();
488
150
  Diagnostic Info(this, storedDiag.getMessage());
489
150
  Client->HandleDiagnostic(DiagLevel, Info);
490
150
  if (Client->IncludeInDiagnosticCounts()) {
491
150
    if (DiagLevel == DiagnosticsEngine::Warning)
492
1
      ++NumWarnings;
493
150
  }
494
150
495
150
  CurDiagID = std::numeric_limits<unsigned>::max();
496
150
}
497
498
6.13M
bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
499
6.13M
  assert(getClient() && "DiagnosticClient not set!");
500
6.13M
501
6.13M
  bool Emitted;
502
6.13M
  if (Force) {
503
231
    Diagnostic Info(this);
504
231
505
231
    // Figure out the diagnostic level of this message.
506
231
    DiagnosticIDs::Level DiagLevel
507
231
      = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
508
231
509
231
    Emitted = (DiagLevel != DiagnosticIDs::Ignored);
510
231
    if (Emitted) {
511
231
      // Emit the diagnostic regardless of suppression level.
512
231
      Diags->EmitDiag(*this, DiagLevel);
513
231
    }
514
6.13M
  } else {
515
6.13M
    // Process the diagnostic, sending the accumulated information to the
516
6.13M
    // DiagnosticConsumer.
517
6.13M
    Emitted = ProcessDiag();
518
6.13M
  }
519
6.13M
520
6.13M
  // Clear out the current diagnostic object.
521
6.13M
  Clear();
522
6.13M
523
6.13M
  // If there was a delayed diagnostic, emit it now.
524
6.13M
  if (!Force && 
DelayedDiagID6.13M
)
525
7
    ReportDelayed();
526
6.13M
527
6.13M
  return Emitted;
528
6.13M
}
529
530
200k
DiagnosticConsumer::~DiagnosticConsumer() = default;
531
532
void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
533
312k
                                        const Diagnostic &Info) {
534
312k
  if (!IncludeInDiagnosticCounts())
535
4
    return;
536
312k
537
312k
  if (DiagLevel == DiagnosticsEngine::Warning)
538
60.7k
    ++NumWarnings;
539
251k
  else if (DiagLevel >= DiagnosticsEngine::Error)
540
150k
    ++NumErrors;
541
312k
}
542
543
/// ModifierIs - Return true if the specified modifier matches specified string.
544
template <std::size_t StrLen>
545
static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
546
640k
                       const char (&Str)[StrLen]) {
547
640k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 0173k
;
548
640k
}
Diagnostic.cpp:bool ModifierIs<5ul>(char const*, unsigned int, char const (&) [5ul])
Line
Count
Source
546
421k
                       const char (&Str)[StrLen]) {
547
421k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 011.0k
;
548
421k
}
Diagnostic.cpp:bool ModifierIs<7ul>(char const*, unsigned int, char const (&) [7ul])
Line
Count
Source
546
185k
                       const char (&Str)[StrLen]) {
547
185k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 0154k
;
548
185k
}
Diagnostic.cpp:bool ModifierIs<2ul>(char const*, unsigned int, char const (&) [2ul])
Line
Count
Source
546
18.9k
                       const char (&Str)[StrLen]) {
547
18.9k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 01.37k
;
548
18.9k
}
Diagnostic.cpp:bool ModifierIs<8ul>(char const*, unsigned int, char const (&) [8ul])
Line
Count
Source
546
15.1k
                       const char (&Str)[StrLen]) {
547
15.1k
  return StrLen-1 == ModifierLen && 
memcmp(Modifier, Str, StrLen-1) == 06.64k
;
548
15.1k
}
549
550
/// ScanForward - Scans forward, looking for the given character, skipping
551
/// nested clauses and escaped characters.
552
452k
static const char *ScanFormat(const char *I, const char *E, char Target) {
553
452k
  unsigned Depth = 0;
554
452k
555
20.8M
  for ( ; I != E; 
++I20.4M
) {
556
20.8M
    if (Depth == 0 && 
*I == Target18.2M
)
return I412k
;
557
20.4M
    if (Depth != 0 && 
*I == '}'2.57M
)
Depth--64.6k
;
558
20.4M
559
20.4M
    if (*I == '%') {
560
219k
      I++;
561
219k
      if (I == E) 
break0
;
562
219k
563
219k
      // Escaped characters get implicitly skipped here.
564
219k
565
219k
      // Format specifier.
566
219k
      if (!isDigit(*I) && 
!isPunctuation(*I)87.9k
) {
567
466k
        for (I++; I != E && !isDigit(*I) && 
*I != '{'443k
;
I++379k
)
;379k
568
87.0k
        if (I == E) 
break0
;
569
87.0k
        if (*I == '{')
570
64.6k
          Depth++;
571
87.0k
      }
572
219k
    }
573
20.4M
  }
574
452k
  
return E39.8k
;
575
452k
}
576
577
/// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
578
/// like this:  %select{foo|bar|baz}2.  This means that the integer argument
579
/// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
580
/// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
581
/// This is very useful for certain classes of variant diagnostics.
582
static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
583
                                 const char *Argument, unsigned ArgumentLen,
584
149k
                                 SmallVectorImpl<char> &OutStr) {
585
149k
  const char *ArgumentEnd = Argument+ArgumentLen;
586
149k
587
149k
  // Skip over 'ValNo' |'s.
588
253k
  while (ValNo) {
589
103k
    const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
590
103k
    assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
591
103k
           " larger than the number of options in the diagnostic string!");
592
103k
    Argument = NextVal+1;  // Skip this string.
593
103k
    --ValNo;
594
103k
  }
595
149k
596
149k
  // Get the end of the value.  This is either the } or the |.
597
149k
  const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
598
149k
599
149k
  // Recursively format the result of the select clause into the output string.
600
149k
  DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
601
149k
}
602
603
/// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
604
/// letter 's' to the string if the value is not 1.  This is used in cases like
605
/// this:  "you idiot, you have %4 parameter%s4!".
606
static void HandleIntegerSModifier(unsigned ValNo,
607
1.37k
                                   SmallVectorImpl<char> &OutStr) {
608
1.37k
  if (ValNo != 1)
609
764
    OutStr.push_back('s');
610
1.37k
}
611
612
/// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
613
/// prints the ordinal form of the given integer, with 1 corresponding
614
/// to the first ordinal.  Currently this is hard-coded to use the
615
/// English form.
616
static void HandleOrdinalModifier(unsigned ValNo,
617
6.64k
                                  SmallVectorImpl<char> &OutStr) {
618
6.64k
  assert(ValNo != 0 && "ValNo must be strictly positive!");
619
6.64k
620
6.64k
  llvm::raw_svector_ostream Out(OutStr);
621
6.64k
622
6.64k
  // We could use text forms for the first N ordinals, but the numeric
623
6.64k
  // forms are actually nicer in diagnostics because they stand out.
624
6.64k
  Out << ValNo << llvm::getOrdinalSuffix(ValNo);
625
6.64k
}
626
627
/// PluralNumber - Parse an unsigned integer and advance Start.
628
2.94k
static unsigned PluralNumber(const char *&Start, const char *End) {
629
2.94k
  // Programming 101: Parse a decimal number :-)
630
2.94k
  unsigned Val = 0;
631
5.88k
  while (Start != End && 
*Start >= '0'2.95k
&&
*Start <= '9'2.94k
) {
632
2.94k
    Val *= 10;
633
2.94k
    Val += *Start - '0';
634
2.94k
    ++Start;
635
2.94k
  }
636
2.94k
  return Val;
637
2.94k
}
638
639
/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
640
2.93k
static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
641
2.93k
  if (*Start != '[') {
642
2.92k
    unsigned Ref = PluralNumber(Start, End);
643
2.92k
    return Ref == Val;
644
2.92k
  }
645
7
646
7
  ++Start;
647
7
  unsigned Low = PluralNumber(Start, End);
648
7
  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
649
7
  ++Start;
650
7
  unsigned High = PluralNumber(Start, End);
651
7
  assert(*Start == ']' && "Bad plural expression syntax: expected )");
652
7
  ++Start;
653
7
  return Low <= Val && Val <= High;
654
7
}
655
656
/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
657
4.26k
static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
658
4.26k
  // Empty condition?
659
4.26k
  if (*Start == ':')
660
1.32k
    return true;
661
2.93k
662
2.93k
  while (true) {
663
2.93k
    char C = *Start;
664
2.93k
    if (C == '%') {
665
0
      // Modulo expression
666
0
      ++Start;
667
0
      unsigned Arg = PluralNumber(Start, End);
668
0
      assert(*Start == '=' && "Bad plural expression syntax: expected =");
669
0
      ++Start;
670
0
      unsigned ValMod = ValNo % Arg;
671
0
      if (TestPluralRange(ValMod, Start, End))
672
0
        return true;
673
2.93k
    } else {
674
2.93k
      assert((C == '[' || (C >= '0' && C <= '9')) &&
675
2.93k
             "Bad plural expression syntax: unexpected character");
676
2.93k
      // Range expression
677
2.93k
      if (TestPluralRange(ValNo, Start, End))
678
1.10k
        return true;
679
1.82k
    }
680
1.82k
681
1.82k
    // Scan for next or-expr part.
682
1.82k
    Start = std::find(Start, End, ',');
683
1.82k
    if (Start == End)
684
1.82k
      break;
685
0
    ++Start;
686
0
  }
687
2.93k
  
return false1.82k
;
688
2.93k
}
689
690
/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
691
/// for complex plural forms, or in languages where all plurals are complex.
692
/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
693
/// conditions that are tested in order, the form corresponding to the first
694
/// that applies being emitted. The empty condition is always true, making the
695
/// last form a default case.
696
/// Conditions are simple boolean expressions, where n is the number argument.
697
/// Here are the rules.
698
/// condition  := expression | empty
699
/// empty      :=                             -> always true
700
/// expression := numeric [',' expression]    -> logical or
701
/// numeric    := range                       -> true if n in range
702
///             | '%' number '=' range        -> true if n % number in range
703
/// range      := number
704
///             | '[' number ',' number ']'   -> ranges are inclusive both ends
705
///
706
/// Here are some examples from the GNU gettext manual written in this form:
707
/// English:
708
/// {1:form0|:form1}
709
/// Latvian:
710
/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
711
/// Gaeilge:
712
/// {1:form0|2:form1|:form2}
713
/// Romanian:
714
/// {1:form0|0,%100=[1,19]:form1|:form2}
715
/// Lithuanian:
716
/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
717
/// Russian (requires repeated form):
718
/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
719
/// Slovak
720
/// {1:form0|[2,4]:form1|:form2}
721
/// Polish (requires repeated form):
722
/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
723
static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
724
                                 const char *Argument, unsigned ArgumentLen,
725
2.43k
                                 SmallVectorImpl<char> &OutStr) {
726
2.43k
  const char *ArgumentEnd = Argument + ArgumentLen;
727
4.26k
  while (true) {
728
4.26k
    assert(Argument < ArgumentEnd && "Plural expression didn't match.");
729
4.26k
    const char *ExprEnd = Argument;
730
7.22k
    while (*ExprEnd != ':') {
731
2.96k
      assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
732
2.96k
      ++ExprEnd;
733
2.96k
    }
734
4.26k
    if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
735
2.43k
      Argument = ExprEnd + 1;
736
2.43k
      ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
737
2.43k
738
2.43k
      // Recursively format the result of the plural clause into the
739
2.43k
      // output string.
740
2.43k
      DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
741
2.43k
      return;
742
2.43k
    }
743
1.82k
    Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
744
1.82k
  }
745
2.43k
}
746
747
/// Returns the friendly description for a token kind that will appear
748
/// without quotes in diagnostic messages. These strings may be translatable in
749
/// future.
750
294
static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
751
294
  switch (Kind) {
752
292
  case tok::identifier:
753
292
    return "identifier";
754
2
  default:
755
2
    return nullptr;
756
294
  }
757
294
}
758
759
/// FormatDiagnostic - Format this diagnostic into a string, substituting the
760
/// formal arguments into the %0 slots.  The result is appended onto the Str
761
/// array.
762
void Diagnostic::
763
314k
FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
764
314k
  if (!StoredDiagMessage.empty()) {
765
153
    OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
766
153
    return;
767
153
  }
768
314k
769
314k
  StringRef Diag =
770
314k
    getDiags()->getDiagnosticIDs()->getDescription(getID());
771
314k
772
314k
  FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
773
314k
}
774
775
void Diagnostic::
776
FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
777
498k
                 SmallVectorImpl<char> &OutStr) const {
778
498k
  // When the diagnostic string is only "%0", the entire string is being given
779
498k
  // by an outside source.  Remove unprintable characters from this string
780
498k
  // and skip all the other string processing.
781
498k
  if (DiagEnd - DiagStr == 2 &&
782
498k
      
StringRef(DiagStr, DiagEnd - DiagStr).equals("%0")20.1k
&&
783
498k
      
getArgKind(0) == DiagnosticsEngine::ak_std_string17.5k
) {
784
17.4k
    const std::string &S = getArgStdStr(0);
785
637k
    for (char c : S) {
786
637k
      if (llvm::sys::locale::isPrint(c) || 
c == '\t'350
) {
787
637k
        OutStr.push_back(c);
788
637k
      }
789
637k
    }
790
17.4k
    return;
791
17.4k
  }
792
481k
793
481k
  /// FormattedArgs - Keep track of all of the arguments formatted by
794
481k
  /// ConvertArgToString and pass them into subsequent calls to
795
481k
  /// ConvertArgToString, allowing the implementation to avoid redundancies in
796
481k
  /// obvious cases.
797
481k
  SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
798
481k
799
481k
  /// QualTypeVals - Pass a vector of arrays so that QualType names can be
800
481k
  /// compared to see if more information is needed to be printed.
801
481k
  SmallVector<intptr_t, 2> QualTypeVals;
802
481k
  SmallVector<char, 64> Tree;
803
481k
804
1.73M
  for (unsigned i = 0, e = getNumArgs(); i < e; 
++i1.25M
)
805
1.25M
    if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
806
218k
      QualTypeVals.push_back(getRawArg(i));
807
481k
808
1.52M
  while (DiagStr != DiagEnd) {
809
1.04M
    if (DiagStr[0] != '%') {
810
621k
      // Append non-%0 substrings to Str if we have one.
811
621k
      const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
812
621k
      OutStr.append(DiagStr, StrEnd);
813
621k
      DiagStr = StrEnd;
814
621k
      continue;
815
621k
    } else 
if (421k
isPunctuation(DiagStr[1])421k
) {
816
113
      OutStr.push_back(DiagStr[1]);  // %% -> %.
817
113
      DiagStr += 2;
818
113
      continue;
819
113
    }
820
421k
821
421k
    // Skip the %.
822
421k
    ++DiagStr;
823
421k
824
421k
    // This must be a placeholder for a diagnostic argument.  The format for a
825
421k
    // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
826
421k
    // The digit is a number from 0-9 indicating which argument this comes from.
827
421k
    // The modifier is a string of digits from the set [-a-z]+, arguments is a
828
421k
    // brace enclosed string.
829
421k
    const char *Modifier = nullptr, *Argument = nullptr;
830
421k
    unsigned ModifierLen = 0, ArgumentLen = 0;
831
421k
832
421k
    // Check to see if we have a modifier.  If so eat it.
833
421k
    if (!isDigit(DiagStr[0])) {
834
179k
      Modifier = DiagStr;
835
1.19M
      while (DiagStr[0] == '-' ||
836
1.19M
             (DiagStr[0] >= 'a' && 
DiagStr[0] <= 'z'1.18M
))
837
1.01M
        ++DiagStr;
838
179k
      ModifierLen = DiagStr-Modifier;
839
179k
840
179k
      // If we have an argument, get it next.
841
179k
      if (DiagStr[0] == '{') {
842
162k
        ++DiagStr; // Skip {.
843
162k
        Argument = DiagStr;
844
162k
845
162k
        DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
846
162k
        assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
847
162k
        ArgumentLen = DiagStr-Argument;
848
162k
        ++DiagStr;  // Skip }.
849
162k
      }
850
179k
    }
851
421k
852
421k
    assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
853
421k
    unsigned ArgNo = *DiagStr++ - '0';
854
421k
855
421k
    // Only used for type diffing.
856
421k
    unsigned ArgNo2 = ArgNo;
857
421k
858
421k
    DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
859
421k
    if (ModifierIs(Modifier, ModifierLen, "diff")) {
860
11.0k
      assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
861
11.0k
             "Invalid format for diff modifier");
862
11.0k
      ++DiagStr;  // Comma.
863
11.0k
      ArgNo2 = *DiagStr++ - '0';
864
11.0k
      DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
865
11.0k
      if (Kind == DiagnosticsEngine::ak_qualtype &&
866
11.0k
          
Kind2 == DiagnosticsEngine::ak_qualtype11.0k
)
867
10.9k
        Kind = DiagnosticsEngine::ak_qualtype_pair;
868
78
      else {
869
78
        // %diff only supports QualTypes.  For other kinds of arguments,
870
78
        // use the default printing.  For example, if the modifier is:
871
78
        //   "%diff{compare $ to $|other text}1,2"
872
78
        // treat it as:
873
78
        //   "compare %1 to %2"
874
78
        const char *ArgumentEnd = Argument + ArgumentLen;
875
78
        const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
876
78
        assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
877
78
               "Found too many '|'s in a %diff modifier!");
878
78
        const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
879
78
        const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
880
78
        const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
881
78
        const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
882
78
        FormatDiagnostic(Argument, FirstDollar, OutStr);
883
78
        FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
884
78
        FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
885
78
        FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
886
78
        FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
887
78
        continue;
888
78
      }
889
421k
    }
890
421k
891
421k
    switch (Kind) {
892
0
    // ---- STRINGS ----
893
57.1k
    case DiagnosticsEngine::ak_std_string: {
894
57.1k
      const std::string &S = getArgStdStr(ArgNo);
895
57.1k
      assert(ModifierLen == 0 && "No modifiers for strings yet");
896
57.1k
      OutStr.append(S.begin(), S.end());
897
57.1k
      break;
898
0
    }
899
41.8k
    case DiagnosticsEngine::ak_c_string: {
900
41.8k
      const char *S = getArgCStr(ArgNo);
901
41.8k
      assert(ModifierLen == 0 && "No modifiers for strings yet");
902
41.8k
903
41.8k
      // Don't crash if get passed a null pointer by accident.
904
41.8k
      if (!S)
905
0
        S = "(null)";
906
41.8k
907
41.8k
      OutStr.append(S, S + strlen(S));
908
41.8k
      break;
909
0
    }
910
0
    // ---- INTEGERS ----
911
96.2k
    case DiagnosticsEngine::ak_sint: {
912
96.2k
      int Val = getArgSInt(ArgNo);
913
96.2k
914
96.2k
      if (ModifierIs(Modifier, ModifierLen, "select")) {
915
93.8k
        HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
916
93.8k
                             OutStr);
917
93.8k
      } else 
if (2.44k
ModifierIs(Modifier, ModifierLen, "s")2.44k
) {
918
37
        HandleIntegerSModifier(Val, OutStr);
919
2.40k
      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
920
579
        HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
921
579
                             OutStr);
922
1.83k
      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
923
38
        HandleOrdinalModifier((unsigned)Val, OutStr);
924
1.79k
      } else {
925
1.79k
        assert(ModifierLen == 0 && "Unknown integer modifier");
926
1.79k
        llvm::raw_svector_ostream(OutStr) << Val;
927
1.79k
      }
928
96.2k
      break;
929
0
    }
930
71.9k
    case DiagnosticsEngine::ak_uint: {
931
71.9k
      unsigned Val = getArgUInt(ArgNo);
932
71.9k
933
71.9k
      if (ModifierIs(Modifier, ModifierLen, "select")) {
934
55.4k
        HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
935
55.4k
      } else 
if (16.4k
ModifierIs(Modifier, ModifierLen, "s")16.4k
) {
936
1.33k
        HandleIntegerSModifier(Val, OutStr);
937
15.1k
      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
938
1.85k
        HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
939
1.85k
                             OutStr);
940
13.2k
      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
941
6.61k
        HandleOrdinalModifier(Val, OutStr);
942
6.66k
      } else {
943
6.66k
        assert(ModifierLen == 0 && "Unknown integer modifier");
944
6.66k
        llvm::raw_svector_ostream(OutStr) << Val;
945
6.66k
      }
946
71.9k
      break;
947
0
    }
948
0
    // ---- TOKEN SPELLINGS ----
949
30.6k
    case DiagnosticsEngine::ak_tokenkind: {
950
30.6k
      tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
951
30.6k
      assert(ModifierLen == 0 && "No modifiers for token kinds yet");
952
30.6k
953
30.6k
      llvm::raw_svector_ostream Out(OutStr);
954
30.6k
      if (const char *S = tok::getPunctuatorSpelling(Kind))
955
30.2k
        // Quoted token spelling for punctuators.
956
30.2k
        Out << '\'' << S << '\'';
957
314
      else if (const char *S = tok::getKeywordSpelling(Kind))
958
20
        // Unquoted token spelling for keywords.
959
20
        Out << S;
960
294
      else if (const char *S = getTokenDescForDiagnostic(Kind))
961
292
        // Unquoted translatable token name.
962
292
        Out << S;
963
2
      else if (const char *S = tok::getTokenName(Kind))
964
2
        // Debug name, shouldn't appear in user-facing diagnostics.
965
2
        Out << '<' << S << '>';
966
0
      else
967
0
        Out << "(null)";
968
30.6k
      break;
969
0
    }
970
0
    // ---- NAMES and TYPES ----
971
9.29k
    case DiagnosticsEngine::ak_identifierinfo: {
972
9.29k
      const IdentifierInfo *II = getArgIdentifier(ArgNo);
973
9.29k
      assert(ModifierLen == 0 && "No modifiers for strings yet");
974
9.29k
975
9.29k
      // Don't crash if get passed a null pointer by accident.
976
9.29k
      if (!II) {
977
8
        const char *S = "(null)";
978
8
        OutStr.append(S, S + strlen(S));
979
8
        continue;
980
8
      }
981
9.29k
982
9.29k
      llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
983
9.29k
      break;
984
9.29k
    }
985
102k
    case DiagnosticsEngine::ak_addrspace:
986
102k
    case DiagnosticsEngine::ak_qual:
987
102k
    case DiagnosticsEngine::ak_qualtype:
988
102k
    case DiagnosticsEngine::ak_declarationname:
989
102k
    case DiagnosticsEngine::ak_nameddecl:
990
102k
    case DiagnosticsEngine::ak_nestednamespec:
991
102k
    case DiagnosticsEngine::ak_declcontext:
992
102k
    case DiagnosticsEngine::ak_attr:
993
102k
      getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
994
102k
                                     StringRef(Modifier, ModifierLen),
995
102k
                                     StringRef(Argument, ArgumentLen),
996
102k
                                     FormattedArgs,
997
102k
                                     OutStr, QualTypeVals);
998
102k
      break;
999
102k
    case DiagnosticsEngine::ak_qualtype_pair: {
1000
10.9k
      // Create a struct with all the info needed for printing.
1001
10.9k
      TemplateDiffTypes TDT;
1002
10.9k
      TDT.FromType = getRawArg(ArgNo);
1003
10.9k
      TDT.ToType = getRawArg(ArgNo2);
1004
10.9k
      TDT.ElideType = getDiags()->ElideType;
1005
10.9k
      TDT.ShowColors = getDiags()->ShowColors;
1006
10.9k
      TDT.TemplateDiffUsed = false;
1007
10.9k
      intptr_t val = reinterpret_cast<intptr_t>(&TDT);
1008
10.9k
1009
10.9k
      const char *ArgumentEnd = Argument + ArgumentLen;
1010
10.9k
      const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
1011
10.9k
1012
10.9k
      // Print the tree.  If this diagnostic already has a tree, skip the
1013
10.9k
      // second tree.
1014
10.9k
      if (getDiags()->PrintTemplateTree && 
Tree.empty()577
) {
1015
577
        TDT.PrintFromType = true;
1016
577
        TDT.PrintTree = true;
1017
577
        getDiags()->ConvertArgToString(Kind, val,
1018
577
                                       StringRef(Modifier, ModifierLen),
1019
577
                                       StringRef(Argument, ArgumentLen),
1020
577
                                       FormattedArgs,
1021
577
                                       Tree, QualTypeVals);
1022
577
        // If there is no tree information, fall back to regular printing.
1023
577
        if (!Tree.empty()) {
1024
347
          FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
1025
347
          break;
1026
347
        }
1027
10.6k
      }
1028
10.6k
1029
10.6k
      // Non-tree printing, also the fall-back when tree printing fails.
1030
10.6k
      // The fall-back is triggered when the types compared are not templates.
1031
10.6k
      const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
1032
10.6k
      const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
1033
10.6k
1034
10.6k
      // Append before text
1035
10.6k
      FormatDiagnostic(Argument, FirstDollar, OutStr);
1036
10.6k
1037
10.6k
      // Append first type
1038
10.6k
      TDT.PrintTree = false;
1039
10.6k
      TDT.PrintFromType = true;
1040
10.6k
      getDiags()->ConvertArgToString(Kind, val,
1041
10.6k
                                     StringRef(Modifier, ModifierLen),
1042
10.6k
                                     StringRef(Argument, ArgumentLen),
1043
10.6k
                                     FormattedArgs,
1044
10.6k
                                     OutStr, QualTypeVals);
1045
10.6k
      if (!TDT.TemplateDiffUsed)
1046
10.2k
        FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1047
10.2k
                                               TDT.FromType));
1048
10.6k
1049
10.6k
      // Append middle text
1050
10.6k
      FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
1051
10.6k
1052
10.6k
      // Append second type
1053
10.6k
      TDT.PrintFromType = false;
1054
10.6k
      getDiags()->ConvertArgToString(Kind, val,
1055
10.6k
                                     StringRef(Modifier, ModifierLen),
1056
10.6k
                                     StringRef(Argument, ArgumentLen),
1057
10.6k
                                     FormattedArgs,
1058
10.6k
                                     OutStr, QualTypeVals);
1059
10.6k
      if (!TDT.TemplateDiffUsed)
1060
10.2k
        FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
1061
10.2k
                                               TDT.ToType));
1062
10.6k
1063
10.6k
      // Append end text
1064
10.6k
      FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
1065
10.6k
      break;
1066
10.6k
    }
1067
421k
    }
1068
421k
1069
421k
    // Remember this argument info for subsequent formatting operations.  Turn
1070
421k
    // std::strings into a null terminated string to make it be the same case as
1071
421k
    // all the other ones.
1072
421k
    if (Kind == DiagnosticsEngine::ak_qualtype_pair)
1073
10.9k
      continue;
1074
410k
    else if (Kind != DiagnosticsEngine::ak_std_string)
1075
352k
      FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
1076
57.1k
    else
1077
57.1k
      FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
1078
57.1k
                                        (intptr_t)getArgStdStr(ArgNo).c_str()));
1079
421k
  }
1080
481k
1081
481k
  // Append the type tree to the end of the diagnostics.
1082
481k
  OutStr.append(Tree.begin(), Tree.end());
1083
481k
}
1084
1085
StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1086
                                   StringRef Message)
1087
0
    : ID(ID), Level(Level), Message(Message) {}
1088
1089
StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
1090
                                   const Diagnostic &Info)
1091
10.4k
    : ID(Info.getID()), Level(Level) {
1092
10.4k
  assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
1093
10.4k
       "Valid source location without setting a source manager for diagnostic");
1094
10.4k
  if (Info.getLocation().isValid())
1095
10.4k
    Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1096
10.4k
  SmallString<64> Message;
1097
10.4k
  Info.FormatDiagnostic(Message);
1098
10.4k
  this->Message.assign(Message.begin(), Message.end());
1099
10.4k
  this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1100
10.4k
  this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
1101
10.4k
}
1102
1103
StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1104
                                   StringRef Message, FullSourceLoc Loc,
1105
                                   ArrayRef<CharSourceRange> Ranges,
1106
                                   ArrayRef<FixItHint> FixIts)
1107
    : ID(ID), Level(Level), Loc(Loc), Message(Message),
1108
      Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
1109
65
{
1110
65
}
1111
1112
/// IncludeInDiagnosticCounts - This method (whose default implementation
1113
///  returns true) indicates whether the diagnostics handled by this
1114
///  DiagnosticConsumer should be included in the number of diagnostics
1115
///  reported by DiagnosticsEngine.
1116
777k
bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
1117
1118
0
void IgnoringDiagConsumer::anchor() {}
1119
1120
1.70k
ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() = default;
1121
1122
void ForwardingDiagnosticConsumer::HandleDiagnostic(
1123
       DiagnosticsEngine::Level DiagLevel,
1124
503
       const Diagnostic &Info) {
1125
503
  Target.HandleDiagnostic(DiagLevel, Info);
1126
503
}
1127
1128
0
void ForwardingDiagnosticConsumer::clear() {
1129
0
  DiagnosticConsumer::clear();
1130
0
  Target.clear();
1131
0
}
1132
1133
550
bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1134
550
  return Target.IncludeInDiagnosticCounts();
1135
550
}
1136
1137
62.1k
PartialDiagnostic::StorageAllocator::StorageAllocator() {
1138
1.05M
  for (unsigned I = 0; I != NumCached; 
++I994k
)
1139
994k
    FreeList[I] = Cached + I;
1140
62.1k
  NumFreeListEntries = NumCached;
1141
62.1k
}
1142
1143
57.3k
PartialDiagnostic::StorageAllocator::~StorageAllocator() {
1144
57.3k
  // Don't assert if we are in a CrashRecovery context, as this invariant may
1145
57.3k
  // be invalidated during a crash.
1146
57.3k
  assert((NumFreeListEntries == NumCached ||
1147
57.3k
          llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1148
57.3k
         "A partial is on the lam");
1149
57.3k
}
1150
1151
char DiagnosticError::ID;