Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SerializedDiagnosticPrinter.cpp - Serializer for diagnostics -----===//
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
#include "clang/Frontend/SerializedDiagnosticPrinter.h"
10
#include "clang/Basic/Diagnostic.h"
11
#include "clang/Basic/DiagnosticOptions.h"
12
#include "clang/Basic/SourceManager.h"
13
#include "clang/Frontend/DiagnosticRenderer.h"
14
#include "clang/Frontend/FrontendDiagnostic.h"
15
#include "clang/Frontend/SerializedDiagnosticReader.h"
16
#include "clang/Frontend/SerializedDiagnostics.h"
17
#include "clang/Frontend/TextDiagnosticPrinter.h"
18
#include "clang/Lex/Lexer.h"
19
#include "llvm/ADT/DenseSet.h"
20
#include "llvm/ADT/STLExtras.h"
21
#include "llvm/ADT/SmallString.h"
22
#include "llvm/ADT/StringRef.h"
23
#include "llvm/Bitstream/BitCodes.h"
24
#include "llvm/Bitstream/BitstreamReader.h"
25
#include "llvm/Support/FileSystem.h"
26
#include "llvm/Support/raw_ostream.h"
27
#include <utility>
28
29
using namespace clang;
30
using namespace clang::serialized_diags;
31
32
namespace {
33
34
class AbbreviationMap {
35
  llvm::DenseMap<unsigned, unsigned> Abbrevs;
36
public:
37
0
  AbbreviationMap() {}
38
39
0
  void set(unsigned recordID, unsigned abbrevID) {
40
0
    assert(!Abbrevs.contains(recordID) && "Abbreviation already set.");
41
0
    Abbrevs[recordID] = abbrevID;
42
0
  }
43
44
0
  unsigned get(unsigned recordID) {
45
0
    assert(Abbrevs.contains(recordID) && "Abbreviation not set.");
46
0
    return Abbrevs[recordID];
47
0
  }
48
};
49
50
typedef SmallVector<uint64_t, 64> RecordData;
51
typedef SmallVectorImpl<uint64_t> RecordDataImpl;
52
typedef ArrayRef<uint64_t> RecordDataRef;
53
54
class SDiagsWriter;
55
56
class SDiagsRenderer : public DiagnosticNoteRenderer {
57
  SDiagsWriter &Writer;
58
public:
59
  SDiagsRenderer(SDiagsWriter &Writer, const LangOptions &LangOpts,
60
                 DiagnosticOptions *DiagOpts)
61
0
    : DiagnosticNoteRenderer(LangOpts, DiagOpts), Writer(Writer) {}
62
63
0
  ~SDiagsRenderer() override {}
64
65
protected:
66
  void emitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc,
67
                             DiagnosticsEngine::Level Level, StringRef Message,
68
                             ArrayRef<CharSourceRange> Ranges,
69
                             DiagOrStoredDiag D) override;
70
71
  void emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc,
72
                         DiagnosticsEngine::Level Level,
73
0
                         ArrayRef<CharSourceRange> Ranges) override {}
74
75
  void emitNote(FullSourceLoc Loc, StringRef Message) override;
76
77
  void emitCodeContext(FullSourceLoc Loc, DiagnosticsEngine::Level Level,
78
                       SmallVectorImpl<CharSourceRange> &Ranges,
79
                       ArrayRef<FixItHint> Hints) override;
80
81
  void beginDiagnostic(DiagOrStoredDiag D,
82
                       DiagnosticsEngine::Level Level) override;
83
  void endDiagnostic(DiagOrStoredDiag D,
84
                     DiagnosticsEngine::Level Level) override;
85
};
86
87
typedef llvm::DenseMap<unsigned, unsigned> AbbrevLookup;
88
89
class SDiagsMerger : SerializedDiagnosticReader {
90
  SDiagsWriter &Writer;
91
  AbbrevLookup FileLookup;
92
  AbbrevLookup CategoryLookup;
93
  AbbrevLookup DiagFlagLookup;
94
95
public:
96
0
  SDiagsMerger(SDiagsWriter &Writer) : Writer(Writer) {}
97
98
0
  std::error_code mergeRecordsFromFile(const char *File) {
99
0
    return readDiagnostics(File);
100
0
  }
101
102
protected:
103
  std::error_code visitStartOfDiagnostic() override;
104
  std::error_code visitEndOfDiagnostic() override;
105
  std::error_code visitCategoryRecord(unsigned ID, StringRef Name) override;
106
  std::error_code visitDiagFlagRecord(unsigned ID, StringRef Name) override;
107
  std::error_code visitDiagnosticRecord(
108
      unsigned Severity, const serialized_diags::Location &Location,
109
      unsigned Category, unsigned Flag, StringRef Message) override;
110
  std::error_code visitFilenameRecord(unsigned ID, unsigned Size,
111
                                      unsigned Timestamp,
112
                                      StringRef Name) override;
113
  std::error_code visitFixitRecord(const serialized_diags::Location &Start,
114
                                   const serialized_diags::Location &End,
115
                                   StringRef CodeToInsert) override;
116
  std::error_code
117
  visitSourceRangeRecord(const serialized_diags::Location &Start,
118
                         const serialized_diags::Location &End) override;
119
120
private:
121
  std::error_code adjustSourceLocFilename(RecordData &Record,
122
                                          unsigned int offset);
123
124
  void adjustAbbrevID(RecordData &Record, AbbrevLookup &Lookup,
125
                      unsigned NewAbbrev);
126
127
  void writeRecordWithAbbrev(unsigned ID, RecordData &Record);
128
129
  void writeRecordWithBlob(unsigned ID, RecordData &Record, StringRef Blob);
130
};
131
132
class SDiagsWriter : public DiagnosticConsumer {
133
  friend class SDiagsRenderer;
134
  friend class SDiagsMerger;
135
136
  struct SharedState;
137
138
  explicit SDiagsWriter(std::shared_ptr<SharedState> State)
139
      : LangOpts(nullptr), OriginalInstance(false), MergeChildRecords(false),
140
0
        State(std::move(State)) {}
141
142
public:
143
  SDiagsWriter(StringRef File, DiagnosticOptions *Diags, bool MergeChildRecords)
144
      : LangOpts(nullptr), OriginalInstance(true),
145
        MergeChildRecords(MergeChildRecords),
146
0
        State(std::make_shared<SharedState>(File, Diags)) {
147
0
    if (MergeChildRecords)
148
0
      RemoveOldDiagnostics();
149
0
    EmitPreamble();
150
0
  }
151
152
0
  ~SDiagsWriter() override {}
153
154
  void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
155
                        const Diagnostic &Info) override;
156
157
0
  void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {
158
0
    LangOpts = &LO;
159
0
  }
160
161
  void finish() override;
162
163
private:
164
  /// Build a DiagnosticsEngine to emit diagnostics about the diagnostics
165
  DiagnosticsEngine *getMetaDiags();
166
167
  /// Remove old copies of the serialized diagnostics. This is necessary
168
  /// so that we can detect when subprocesses write diagnostics that we should
169
  /// merge into our own.
170
  void RemoveOldDiagnostics();
171
172
  /// Emit the preamble for the serialized diagnostics.
173
  void EmitPreamble();
174
175
  /// Emit the BLOCKINFO block.
176
  void EmitBlockInfoBlock();
177
178
  /// Emit the META data block.
179
  void EmitMetaBlock();
180
181
  /// Start a DIAG block.
182
  void EnterDiagBlock();
183
184
  /// End a DIAG block.
185
  void ExitDiagBlock();
186
187
  /// Emit a DIAG record.
188
  void EmitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc,
189
                             DiagnosticsEngine::Level Level, StringRef Message,
190
                             DiagOrStoredDiag D);
191
192
  /// Emit FIXIT and SOURCE_RANGE records for a diagnostic.
193
  void EmitCodeContext(SmallVectorImpl<CharSourceRange> &Ranges,
194
                       ArrayRef<FixItHint> Hints,
195
                       const SourceManager &SM);
196
197
  /// Emit a record for a CharSourceRange.
198
  void EmitCharSourceRange(CharSourceRange R, const SourceManager &SM);
199
200
  /// Emit the string information for the category.
201
  unsigned getEmitCategory(unsigned category = 0);
202
203
  /// Emit the string information for diagnostic flags.
204
  unsigned getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel,
205
                                 unsigned DiagID = 0);
206
207
  unsigned getEmitDiagnosticFlag(StringRef DiagName);
208
209
  /// Emit (lazily) the file string and retrieved the file identifier.
210
  unsigned getEmitFile(const char *Filename);
211
212
  /// Add SourceLocation information the specified record.
213
  void AddLocToRecord(FullSourceLoc Loc, PresumedLoc PLoc,
214
                      RecordDataImpl &Record, unsigned TokSize = 0);
215
216
  /// Add SourceLocation information the specified record.
217
  void AddLocToRecord(FullSourceLoc Loc, RecordDataImpl &Record,
218
0
                      unsigned TokSize = 0) {
219
0
    AddLocToRecord(Loc, Loc.hasManager() ? Loc.getPresumedLoc() : PresumedLoc(),
220
0
                   Record, TokSize);
221
0
  }
222
223
  /// Add CharSourceRange information the specified record.
224
  void AddCharSourceRangeToRecord(CharSourceRange R, RecordDataImpl &Record,
225
                                  const SourceManager &SM);
226
227
  /// Language options, which can differ from one clone of this client
228
  /// to another.
229
  const LangOptions *LangOpts;
230
231
  /// Whether this is the original instance (rather than one of its
232
  /// clones), responsible for writing the file at the end.
233
  bool OriginalInstance;
234
235
  /// Whether this instance should aggregate diagnostics that are
236
  /// generated from child processes.
237
  bool MergeChildRecords;
238
239
  /// Whether we've started finishing and tearing down this instance.
240
  bool IsFinishing = false;
241
242
  /// State that is shared among the various clones of this diagnostic
243
  /// consumer.
244
  struct SharedState {
245
    SharedState(StringRef File, DiagnosticOptions *Diags)
246
        : DiagOpts(Diags), Stream(Buffer), OutputFile(File.str()),
247
0
          EmittedAnyDiagBlocks(false) {}
248
249
    /// Diagnostic options.
250
    IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
251
252
    /// The byte buffer for the serialized content.
253
    SmallString<1024> Buffer;
254
255
    /// The BitStreamWriter for the serialized diagnostics.
256
    llvm::BitstreamWriter Stream;
257
258
    /// The name of the diagnostics file.
259
    std::string OutputFile;
260
261
    /// The set of constructed record abbreviations.
262
    AbbreviationMap Abbrevs;
263
264
    /// A utility buffer for constructing record content.
265
    RecordData Record;
266
267
    /// A text buffer for rendering diagnostic text.
268
    SmallString<256> diagBuf;
269
270
    /// The collection of diagnostic categories used.
271
    llvm::DenseSet<unsigned> Categories;
272
273
    /// The collection of files used.
274
    llvm::DenseMap<const char *, unsigned> Files;
275
276
    typedef llvm::DenseMap<const void *, std::pair<unsigned, StringRef> >
277
    DiagFlagsTy;
278
279
    /// Map for uniquing strings.
280
    DiagFlagsTy DiagFlags;
281
282
    /// Whether we have already started emission of any DIAG blocks. Once
283
    /// this becomes \c true, we never close a DIAG block until we know that we're
284
    /// starting another one or we're done.
285
    bool EmittedAnyDiagBlocks;
286
287
    /// Engine for emitting diagnostics about the diagnostics.
288
    std::unique_ptr<DiagnosticsEngine> MetaDiagnostics;
289
  };
290
291
  /// State shared among the various clones of this diagnostic consumer.
292
  std::shared_ptr<SharedState> State;
293
};
294
} // end anonymous namespace
295
296
namespace clang {
297
namespace serialized_diags {
298
std::unique_ptr<DiagnosticConsumer>
299
0
create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords) {
300
0
  return std::make_unique<SDiagsWriter>(OutputFile, Diags, MergeChildRecords);
301
0
}
302
303
} // end namespace serialized_diags
304
} // end namespace clang
305
306
//===----------------------------------------------------------------------===//
307
// Serialization methods.
308
//===----------------------------------------------------------------------===//
309
310
/// Emits a block ID in the BLOCKINFO block.
311
static void EmitBlockID(unsigned ID, const char *Name,
312
                        llvm::BitstreamWriter &Stream,
313
0
                        RecordDataImpl &Record) {
314
0
  Record.clear();
315
0
  Record.push_back(ID);
316
0
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
317
318
  // Emit the block name if present.
319
0
  if (!Name || Name[0] == 0)
320
0
    return;
321
322
0
  Record.clear();
323
324
0
  while (*Name)
325
0
    Record.push_back(*Name++);
326
327
0
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
328
0
}
329
330
/// Emits a record ID in the BLOCKINFO block.
331
static void EmitRecordID(unsigned ID, const char *Name,
332
                         llvm::BitstreamWriter &Stream,
333
0
                         RecordDataImpl &Record){
334
0
  Record.clear();
335
0
  Record.push_back(ID);
336
337
0
  while (*Name)
338
0
    Record.push_back(*Name++);
339
340
0
  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
341
0
}
342
343
void SDiagsWriter::AddLocToRecord(FullSourceLoc Loc, PresumedLoc PLoc,
344
0
                                  RecordDataImpl &Record, unsigned TokSize) {
345
0
  if (PLoc.isInvalid()) {
346
    // Emit a "sentinel" location.
347
0
    Record.push_back((unsigned)0); // File.
348
0
    Record.push_back((unsigned)0); // Line.
349
0
    Record.push_back((unsigned)0); // Column.
350
0
    Record.push_back((unsigned)0); // Offset.
351
0
    return;
352
0
  }
353
354
0
  Record.push_back(getEmitFile(PLoc.getFilename()));
355
0
  Record.push_back(PLoc.getLine());
356
0
  Record.push_back(PLoc.getColumn()+TokSize);
357
0
  Record.push_back(Loc.getFileOffset());
358
0
}
359
360
void SDiagsWriter::AddCharSourceRangeToRecord(CharSourceRange Range,
361
                                              RecordDataImpl &Record,
362
0
                                              const SourceManager &SM) {
363
0
  AddLocToRecord(FullSourceLoc(Range.getBegin(), SM), Record);
364
0
  unsigned TokSize = 0;
365
0
  if (Range.isTokenRange())
366
0
    TokSize = Lexer::MeasureTokenLength(Range.getEnd(),
367
0
                                        SM, *LangOpts);
368
369
0
  AddLocToRecord(FullSourceLoc(Range.getEnd(), SM), Record, TokSize);
370
0
}
371
372
0
unsigned SDiagsWriter::getEmitFile(const char *FileName){
373
0
  if (!FileName)
374
0
    return 0;
375
376
0
  unsigned &entry = State->Files[FileName];
377
0
  if (entry)
378
0
    return entry;
379
380
  // Lazily generate the record for the file.
381
0
  entry = State->Files.size();
382
0
  StringRef Name(FileName);
383
0
  RecordData::value_type Record[] = {RECORD_FILENAME, entry, 0 /* For legacy */,
384
0
                                     0 /* For legacy */, Name.size()};
385
0
  State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_FILENAME), Record,
386
0
                                   Name);
387
388
0
  return entry;
389
0
}
390
391
void SDiagsWriter::EmitCharSourceRange(CharSourceRange R,
392
0
                                       const SourceManager &SM) {
393
0
  State->Record.clear();
394
0
  State->Record.push_back(RECORD_SOURCE_RANGE);
395
0
  AddCharSourceRangeToRecord(R, State->Record, SM);
396
0
  State->Stream.EmitRecordWithAbbrev(State->Abbrevs.get(RECORD_SOURCE_RANGE),
397
0
                                     State->Record);
398
0
}
399
400
/// Emits the preamble of the diagnostics file.
401
0
void SDiagsWriter::EmitPreamble() {
402
  // Emit the file header.
403
0
  State->Stream.Emit((unsigned)'D', 8);
404
0
  State->Stream.Emit((unsigned)'I', 8);
405
0
  State->Stream.Emit((unsigned)'A', 8);
406
0
  State->Stream.Emit((unsigned)'G', 8);
407
408
0
  EmitBlockInfoBlock();
409
0
  EmitMetaBlock();
410
0
}
411
412
0
static void AddSourceLocationAbbrev(llvm::BitCodeAbbrev &Abbrev) {
413
0
  using namespace llvm;
414
0
  Abbrev.Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // File ID.
415
0
  Abbrev.Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Line.
416
0
  Abbrev.Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Column.
417
0
  Abbrev.Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Offset;
418
0
}
419
420
0
static void AddRangeLocationAbbrev(llvm::BitCodeAbbrev &Abbrev) {
421
0
  AddSourceLocationAbbrev(Abbrev);
422
0
  AddSourceLocationAbbrev(Abbrev);
423
0
}
424
425
0
void SDiagsWriter::EmitBlockInfoBlock() {
426
0
  State->Stream.EnterBlockInfoBlock();
427
428
0
  using namespace llvm;
429
0
  llvm::BitstreamWriter &Stream = State->Stream;
430
0
  RecordData &Record = State->Record;
431
0
  AbbreviationMap &Abbrevs = State->Abbrevs;
432
433
  // ==---------------------------------------------------------------------==//
434
  // The subsequent records and Abbrevs are for the "Meta" block.
435
  // ==---------------------------------------------------------------------==//
436
437
0
  EmitBlockID(BLOCK_META, "Meta", Stream, Record);
438
0
  EmitRecordID(RECORD_VERSION, "Version", Stream, Record);
439
0
  auto Abbrev = std::make_shared<BitCodeAbbrev>();
440
0
  Abbrev->Add(BitCodeAbbrevOp(RECORD_VERSION));
441
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
442
0
  Abbrevs.set(RECORD_VERSION, Stream.EmitBlockInfoAbbrev(BLOCK_META, Abbrev));
443
444
  // ==---------------------------------------------------------------------==//
445
  // The subsequent records and Abbrevs are for the "Diagnostic" block.
446
  // ==---------------------------------------------------------------------==//
447
448
0
  EmitBlockID(BLOCK_DIAG, "Diag", Stream, Record);
449
0
  EmitRecordID(RECORD_DIAG, "DiagInfo", Stream, Record);
450
0
  EmitRecordID(RECORD_SOURCE_RANGE, "SrcRange", Stream, Record);
451
0
  EmitRecordID(RECORD_CATEGORY, "CatName", Stream, Record);
452
0
  EmitRecordID(RECORD_DIAG_FLAG, "DiagFlag", Stream, Record);
453
0
  EmitRecordID(RECORD_FILENAME, "FileName", Stream, Record);
454
0
  EmitRecordID(RECORD_FIXIT, "FixIt", Stream, Record);
455
456
  // Emit abbreviation for RECORD_DIAG.
457
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
458
0
  Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG));
459
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));  // Diag level.
460
0
  AddSourceLocationAbbrev(*Abbrev);
461
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Category.
462
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID.
463
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Text size.
464
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Diagnostc text.
465
0
  Abbrevs.set(RECORD_DIAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
466
467
  // Emit abbreviation for RECORD_CATEGORY.
468
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
469
0
  Abbrev->Add(BitCodeAbbrevOp(RECORD_CATEGORY));
470
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Category ID.
471
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));  // Text size.
472
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));      // Category text.
473
0
  Abbrevs.set(RECORD_CATEGORY, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
474
475
  // Emit abbreviation for RECORD_SOURCE_RANGE.
476
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
477
0
  Abbrev->Add(BitCodeAbbrevOp(RECORD_SOURCE_RANGE));
478
0
  AddRangeLocationAbbrev(*Abbrev);
479
0
  Abbrevs.set(RECORD_SOURCE_RANGE,
480
0
              Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev));
481
482
  // Emit the abbreviation for RECORD_DIAG_FLAG.
483
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
484
0
  Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG_FLAG));
485
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID.
486
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
487
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Flag name text.
488
0
  Abbrevs.set(RECORD_DIAG_FLAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG,
489
0
                                                           Abbrev));
490
491
  // Emit the abbreviation for RECORD_FILENAME.
492
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
493
0
  Abbrev->Add(BitCodeAbbrevOp(RECORD_FILENAME));
494
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped file ID.
495
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Size.
496
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Modification time.
497
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
498
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name text.
499
0
  Abbrevs.set(RECORD_FILENAME, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG,
500
0
                                                          Abbrev));
501
502
  // Emit the abbreviation for RECORD_FIXIT.
503
0
  Abbrev = std::make_shared<BitCodeAbbrev>();
504
0
  Abbrev->Add(BitCodeAbbrevOp(RECORD_FIXIT));
505
0
  AddRangeLocationAbbrev(*Abbrev);
506
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size.
507
0
  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));      // FixIt text.
508
0
  Abbrevs.set(RECORD_FIXIT, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG,
509
0
                                                       Abbrev));
510
511
0
  Stream.ExitBlock();
512
0
}
513
514
0
void SDiagsWriter::EmitMetaBlock() {
515
0
  llvm::BitstreamWriter &Stream = State->Stream;
516
0
  AbbreviationMap &Abbrevs = State->Abbrevs;
517
518
0
  Stream.EnterSubblock(BLOCK_META, 3);
519
0
  RecordData::value_type Record[] = {RECORD_VERSION, VersionNumber};
520
0
  Stream.EmitRecordWithAbbrev(Abbrevs.get(RECORD_VERSION), Record);
521
0
  Stream.ExitBlock();
522
0
}
523
524
0
unsigned SDiagsWriter::getEmitCategory(unsigned int category) {
525
0
  if (!State->Categories.insert(category).second)
526
0
    return category;
527
528
  // We use a local version of 'Record' so that we can be generating
529
  // another record when we lazily generate one for the category entry.
530
0
  StringRef catName = DiagnosticIDs::getCategoryNameFromID(category);
531
0
  RecordData::value_type Record[] = {RECORD_CATEGORY, category, catName.size()};
532
0
  State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_CATEGORY), Record,
533
0
                                   catName);
534
535
0
  return category;
536
0
}
537
538
unsigned SDiagsWriter::getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel,
539
0
                                             unsigned DiagID) {
540
0
  if (DiagLevel == DiagnosticsEngine::Note)
541
0
    return 0; // No flag for notes.
542
543
0
  StringRef FlagName = DiagnosticIDs::getWarningOptionForDiag(DiagID);
544
0
  return getEmitDiagnosticFlag(FlagName);
545
0
}
546
547
0
unsigned SDiagsWriter::getEmitDiagnosticFlag(StringRef FlagName) {
548
0
  if (FlagName.empty())
549
0
    return 0;
550
551
  // Here we assume that FlagName points to static data whose pointer
552
  // value is fixed.  This allows us to unique by diagnostic groups.
553
0
  const void *data = FlagName.data();
554
0
  std::pair<unsigned, StringRef> &entry = State->DiagFlags[data];
555
0
  if (entry.first == 0) {
556
0
    entry.first = State->DiagFlags.size();
557
0
    entry.second = FlagName;
558
559
    // Lazily emit the string in a separate record.
560
0
    RecordData::value_type Record[] = {RECORD_DIAG_FLAG, entry.first,
561
0
                                       FlagName.size()};
562
0
    State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_DIAG_FLAG),
563
0
                                     Record, FlagName);
564
0
  }
565
566
0
  return entry.first;
567
0
}
568
569
void SDiagsWriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
570
0
                                    const Diagnostic &Info) {
571
0
  assert(!IsFinishing &&
572
0
         "Received a diagnostic after we've already started teardown.");
573
0
  if (IsFinishing) {
574
0
    SmallString<256> diagnostic;
575
0
    Info.FormatDiagnostic(diagnostic);
576
0
    getMetaDiags()->Report(
577
0
        diag::warn_fe_serialized_diag_failure_during_finalisation)
578
0
        << diagnostic;
579
0
    return;
580
0
  }
581
582
  // Enter the block for a non-note diagnostic immediately, rather than waiting
583
  // for beginDiagnostic, in case associated notes are emitted before we get
584
  // there.
585
0
  if (DiagLevel != DiagnosticsEngine::Note) {
586
0
    if (State->EmittedAnyDiagBlocks)
587
0
      ExitDiagBlock();
588
589
0
    EnterDiagBlock();
590
0
    State->EmittedAnyDiagBlocks = true;
591
0
  }
592
593
  // Compute the diagnostic text.
594
0
  State->diagBuf.clear();
595
0
  Info.FormatDiagnostic(State->diagBuf);
596
597
0
  if (Info.getLocation().isInvalid()) {
598
    // Special-case diagnostics with no location. We may not have entered a
599
    // source file in this case, so we can't use the normal DiagnosticsRenderer
600
    // machinery.
601
602
    // Make sure we bracket all notes as "sub-diagnostics".  This matches
603
    // the behavior in SDiagsRenderer::emitDiagnostic().
604
0
    if (DiagLevel == DiagnosticsEngine::Note)
605
0
      EnterDiagBlock();
606
607
0
    EmitDiagnosticMessage(FullSourceLoc(), PresumedLoc(), DiagLevel,
608
0
                          State->diagBuf, &Info);
609
610
0
    if (DiagLevel == DiagnosticsEngine::Note)
611
0
      ExitDiagBlock();
612
613
0
    return;
614
0
  }
615
616
0
  assert(Info.hasSourceManager() && LangOpts &&
617
0
         "Unexpected diagnostic with valid location outside of a source file");
618
0
  SDiagsRenderer Renderer(*this, *LangOpts, &*State->DiagOpts);
619
0
  Renderer.emitDiagnostic(
620
0
      FullSourceLoc(Info.getLocation(), Info.getSourceManager()), DiagLevel,
621
0
      State->diagBuf, Info.getRanges(), Info.getFixItHints(), &Info);
622
0
}
623
624
0
static serialized_diags::Level getStableLevel(DiagnosticsEngine::Level Level) {
625
0
  switch (Level) {
626
0
#define CASE(X) case DiagnosticsEngine::X: return serialized_diags::X;
627
0
  CASE(Ignored)
628
0
  CASE(Note)
629
0
  CASE(Remark)
630
0
  CASE(Warning)
631
0
  CASE(Error)
632
0
  CASE(Fatal)
633
0
#undef CASE
634
0
  }
635
636
0
  llvm_unreachable("invalid diagnostic level");
637
0
}
638
639
void SDiagsWriter::EmitDiagnosticMessage(FullSourceLoc Loc, PresumedLoc PLoc,
640
                                         DiagnosticsEngine::Level Level,
641
                                         StringRef Message,
642
0
                                         DiagOrStoredDiag D) {
643
0
  llvm::BitstreamWriter &Stream = State->Stream;
644
0
  RecordData &Record = State->Record;
645
0
  AbbreviationMap &Abbrevs = State->Abbrevs;
646
647
  // Emit the RECORD_DIAG record.
648
0
  Record.clear();
649
0
  Record.push_back(RECORD_DIAG);
650
0
  Record.push_back(getStableLevel(Level));
651
0
  AddLocToRecord(Loc, PLoc, Record);
652
653
0
  if (const Diagnostic *Info = D.dyn_cast<const Diagnostic*>()) {
654
    // Emit the category string lazily and get the category ID.
655
0
    unsigned DiagID = DiagnosticIDs::getCategoryNumberForDiag(Info->getID());
656
0
    Record.push_back(getEmitCategory(DiagID));
657
    // Emit the diagnostic flag string lazily and get the mapped ID.
658
0
    Record.push_back(getEmitDiagnosticFlag(Level, Info->getID()));
659
0
  } else {
660
0
    Record.push_back(getEmitCategory());
661
0
    Record.push_back(getEmitDiagnosticFlag(Level));
662
0
  }
663
664
0
  Record.push_back(Message.size());
665
0
  Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_DIAG), Record, Message);
666
0
}
667
668
void SDiagsRenderer::emitDiagnosticMessage(
669
    FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level,
670
    StringRef Message, ArrayRef<clang::CharSourceRange> Ranges,
671
0
    DiagOrStoredDiag D) {
672
0
  Writer.EmitDiagnosticMessage(Loc, PLoc, Level, Message, D);
673
0
}
674
675
0
void SDiagsWriter::EnterDiagBlock() {
676
0
  State->Stream.EnterSubblock(BLOCK_DIAG, 4);
677
0
}
678
679
0
void SDiagsWriter::ExitDiagBlock() {
680
0
  State->Stream.ExitBlock();
681
0
}
682
683
void SDiagsRenderer::beginDiagnostic(DiagOrStoredDiag D,
684
0
                                     DiagnosticsEngine::Level Level) {
685
0
  if (Level == DiagnosticsEngine::Note)
686
0
    Writer.EnterDiagBlock();
687
0
}
688
689
void SDiagsRenderer::endDiagnostic(DiagOrStoredDiag D,
690
0
                                   DiagnosticsEngine::Level Level) {
691
  // Only end note diagnostics here, because we can't be sure when we've seen
692
  // the last note associated with a non-note diagnostic.
693
0
  if (Level == DiagnosticsEngine::Note)
694
0
    Writer.ExitDiagBlock();
695
0
}
696
697
void SDiagsWriter::EmitCodeContext(SmallVectorImpl<CharSourceRange> &Ranges,
698
                                   ArrayRef<FixItHint> Hints,
699
0
                                   const SourceManager &SM) {
700
0
  llvm::BitstreamWriter &Stream = State->Stream;
701
0
  RecordData &Record = State->Record;
702
0
  AbbreviationMap &Abbrevs = State->Abbrevs;
703
704
  // Emit Source Ranges.
705
0
  for (ArrayRef<CharSourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
706
0
       I != E; ++I)
707
0
    if (I->isValid())
708
0
      EmitCharSourceRange(*I, SM);
709
710
  // Emit FixIts.
711
0
  for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
712
0
       I != E; ++I) {
713
0
    const FixItHint &Fix = *I;
714
0
    if (Fix.isNull())
715
0
      continue;
716
0
    Record.clear();
717
0
    Record.push_back(RECORD_FIXIT);
718
0
    AddCharSourceRangeToRecord(Fix.RemoveRange, Record, SM);
719
0
    Record.push_back(Fix.CodeToInsert.size());
720
0
    Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_FIXIT), Record,
721
0
                              Fix.CodeToInsert);
722
0
  }
723
0
}
724
725
void SDiagsRenderer::emitCodeContext(FullSourceLoc Loc,
726
                                     DiagnosticsEngine::Level Level,
727
                                     SmallVectorImpl<CharSourceRange> &Ranges,
728
0
                                     ArrayRef<FixItHint> Hints) {
729
0
  Writer.EmitCodeContext(Ranges, Hints, Loc.getManager());
730
0
}
731
732
0
void SDiagsRenderer::emitNote(FullSourceLoc Loc, StringRef Message) {
733
0
  Writer.EnterDiagBlock();
734
0
  PresumedLoc PLoc = Loc.hasManager() ? Loc.getPresumedLoc() : PresumedLoc();
735
0
  Writer.EmitDiagnosticMessage(Loc, PLoc, DiagnosticsEngine::Note, Message,
736
0
                               DiagOrStoredDiag());
737
0
  Writer.ExitDiagBlock();
738
0
}
739
740
0
DiagnosticsEngine *SDiagsWriter::getMetaDiags() {
741
  // FIXME: It's slightly absurd to create a new diagnostics engine here, but
742
  // the other options that are available today are worse:
743
  //
744
  // 1. Teach DiagnosticsConsumers to emit diagnostics to the engine they are a
745
  //    part of. The DiagnosticsEngine would need to know not to send
746
  //    diagnostics back to the consumer that failed. This would require us to
747
  //    rework ChainedDiagnosticsConsumer and teach the engine about multiple
748
  //    consumers, which is difficult today because most APIs interface with
749
  //    consumers rather than the engine itself.
750
  //
751
  // 2. Pass a DiagnosticsEngine to SDiagsWriter on creation - this would need
752
  //    to be distinct from the engine the writer was being added to and would
753
  //    normally not be used.
754
0
  if (!State->MetaDiagnostics) {
755
0
    IntrusiveRefCntPtr<DiagnosticIDs> IDs(new DiagnosticIDs());
756
0
    auto Client =
757
0
        new TextDiagnosticPrinter(llvm::errs(), State->DiagOpts.get());
758
0
    State->MetaDiagnostics = std::make_unique<DiagnosticsEngine>(
759
0
        IDs, State->DiagOpts.get(), Client);
760
0
  }
761
0
  return State->MetaDiagnostics.get();
762
0
}
763
764
0
void SDiagsWriter::RemoveOldDiagnostics() {
765
0
  if (!llvm::sys::fs::remove(State->OutputFile))
766
0
    return;
767
768
0
  getMetaDiags()->Report(diag::warn_fe_serialized_diag_merge_failure);
769
  // Disable merging child records, as whatever is in this file may be
770
  // misleading.
771
0
  MergeChildRecords = false;
772
0
}
773
774
0
void SDiagsWriter::finish() {
775
0
  assert(!IsFinishing);
776
0
  IsFinishing = true;
777
778
  // The original instance is responsible for writing the file.
779
0
  if (!OriginalInstance)
780
0
    return;
781
782
  // Finish off any diagnostic we were in the process of emitting.
783
0
  if (State->EmittedAnyDiagBlocks)
784
0
    ExitDiagBlock();
785
786
0
  if (MergeChildRecords) {
787
0
    if (!State->EmittedAnyDiagBlocks)
788
      // We have no diagnostics of our own, so we can just leave the child
789
      // process' output alone
790
0
      return;
791
792
0
    if (llvm::sys::fs::exists(State->OutputFile))
793
0
      if (SDiagsMerger(*this).mergeRecordsFromFile(State->OutputFile.c_str()))
794
0
        getMetaDiags()->Report(diag::warn_fe_serialized_diag_merge_failure);
795
0
  }
796
797
0
  std::error_code EC;
798
0
  auto OS = std::make_unique<llvm::raw_fd_ostream>(State->OutputFile.c_str(),
799
0
                                                    EC, llvm::sys::fs::OF_None);
800
0
  if (EC) {
801
0
    getMetaDiags()->Report(diag::warn_fe_serialized_diag_failure)
802
0
        << State->OutputFile << EC.message();
803
0
    OS->clear_error();
804
0
    return;
805
0
  }
806
807
  // Write the generated bitstream to "Out".
808
0
  OS->write((char *)&State->Buffer.front(), State->Buffer.size());
809
0
  OS->flush();
810
811
0
  assert(!OS->has_error());
812
0
  if (OS->has_error()) {
813
0
    getMetaDiags()->Report(diag::warn_fe_serialized_diag_failure)
814
0
        << State->OutputFile << OS->error().message();
815
0
    OS->clear_error();
816
0
  }
817
0
}
818
819
0
std::error_code SDiagsMerger::visitStartOfDiagnostic() {
820
0
  Writer.EnterDiagBlock();
821
0
  return std::error_code();
822
0
}
823
824
0
std::error_code SDiagsMerger::visitEndOfDiagnostic() {
825
0
  Writer.ExitDiagBlock();
826
0
  return std::error_code();
827
0
}
828
829
std::error_code
830
SDiagsMerger::visitSourceRangeRecord(const serialized_diags::Location &Start,
831
0
                                     const serialized_diags::Location &End) {
832
0
  RecordData::value_type Record[] = {
833
0
      RECORD_SOURCE_RANGE, FileLookup[Start.FileID], Start.Line, Start.Col,
834
0
      Start.Offset, FileLookup[End.FileID], End.Line, End.Col, End.Offset};
835
0
  Writer.State->Stream.EmitRecordWithAbbrev(
836
0
      Writer.State->Abbrevs.get(RECORD_SOURCE_RANGE), Record);
837
0
  return std::error_code();
838
0
}
839
840
std::error_code SDiagsMerger::visitDiagnosticRecord(
841
    unsigned Severity, const serialized_diags::Location &Location,
842
0
    unsigned Category, unsigned Flag, StringRef Message) {
843
0
  RecordData::value_type Record[] = {
844
0
      RECORD_DIAG, Severity, FileLookup[Location.FileID], Location.Line,
845
0
      Location.Col, Location.Offset, CategoryLookup[Category],
846
0
      Flag ? DiagFlagLookup[Flag] : 0, Message.size()};
847
848
0
  Writer.State->Stream.EmitRecordWithBlob(
849
0
      Writer.State->Abbrevs.get(RECORD_DIAG), Record, Message);
850
0
  return std::error_code();
851
0
}
852
853
std::error_code
854
SDiagsMerger::visitFixitRecord(const serialized_diags::Location &Start,
855
                               const serialized_diags::Location &End,
856
0
                               StringRef Text) {
857
0
  RecordData::value_type Record[] = {RECORD_FIXIT, FileLookup[Start.FileID],
858
0
                                     Start.Line, Start.Col, Start.Offset,
859
0
                                     FileLookup[End.FileID], End.Line, End.Col,
860
0
                                     End.Offset, Text.size()};
861
862
0
  Writer.State->Stream.EmitRecordWithBlob(
863
0
      Writer.State->Abbrevs.get(RECORD_FIXIT), Record, Text);
864
0
  return std::error_code();
865
0
}
866
867
std::error_code SDiagsMerger::visitFilenameRecord(unsigned ID, unsigned Size,
868
                                                  unsigned Timestamp,
869
0
                                                  StringRef Name) {
870
0
  FileLookup[ID] = Writer.getEmitFile(Name.str().c_str());
871
0
  return std::error_code();
872
0
}
873
874
0
std::error_code SDiagsMerger::visitCategoryRecord(unsigned ID, StringRef Name) {
875
0
  CategoryLookup[ID] = Writer.getEmitCategory(ID);
876
0
  return std::error_code();
877
0
}
878
879
0
std::error_code SDiagsMerger::visitDiagFlagRecord(unsigned ID, StringRef Name) {
880
0
  DiagFlagLookup[ID] = Writer.getEmitDiagnosticFlag(Name);
881
0
  return std::error_code();
882
0
}