Coverage Report

Created: 2021-09-21 08:58

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