Coverage Report

Created: 2022-07-16 07:03

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