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