1 //===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
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 header defines the BitstreamWriter class.  This class can be used to
10 // write an arbitrary bitstream, regardless of its contents.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_BITSTREAM_BITSTREAMWRITER_H
15 #define LLVM_BITSTREAM_BITSTREAMWRITER_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Bitstream/BitCodes.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <algorithm>
26 #include <vector>
27 
28 namespace llvm {
29 
30 class BitstreamWriter {
31   /// Out - The buffer that keeps unflushed bytes.
32   SmallVectorImpl<char> &Out;
33 
34   /// FS - The file stream that Out flushes to. If FS is nullptr, it does not
35   /// support read or seek, Out cannot be flushed until all data are written.
36   raw_fd_stream *FS;
37 
38   /// FlushThreshold - If FS is valid, this is the threshold (unit B) to flush
39   /// FS.
40   const uint64_t FlushThreshold;
41 
42   /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
43   unsigned CurBit;
44 
45   /// CurValue - The current value. Only bits < CurBit are valid.
46   uint32_t CurValue;
47 
48   /// CurCodeSize - This is the declared size of code values used for the
49   /// current block, in bits.
50   unsigned CurCodeSize;
51 
52   /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
53   /// selected BLOCK ID.
54   unsigned BlockInfoCurBID;
55 
56   /// CurAbbrevs - Abbrevs installed at in this block.
57   std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
58 
59   struct Block {
60     unsigned PrevCodeSize;
61     size_t StartSizeWord;
62     std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
63     Block(unsigned PCS, size_t SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
64   };
65 
66   /// BlockScope - This tracks the current blocks that we have entered.
67   std::vector<Block> BlockScope;
68 
69   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
70   /// These describe abbreviations that all blocks of the specified ID inherit.
71   struct BlockInfo {
72     unsigned BlockID;
73     std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
74   };
75   std::vector<BlockInfo> BlockInfoRecords;
76 
77   void WriteWord(unsigned Value) {
78     Value = support::endian::byte_swap<uint32_t, support::little>(Value);
79     Out.append(reinterpret_cast<const char *>(&Value),
80                reinterpret_cast<const char *>(&Value + 1));
81   }
82 
83   uint64_t GetNumOfFlushedBytes() const { return FS ? FS->tell() : 0; }
84 
85   size_t GetBufferOffset() const { return Out.size() + GetNumOfFlushedBytes(); }
86 
87   size_t GetWordIndex() const {
88     size_t Offset = GetBufferOffset();
89     assert((Offset & 3) == 0 && "Not 32-bit aligned");
90     return Offset / 4;
91   }
92 
93   /// If the related file stream supports reading, seeking and writing, flush
94   /// the buffer if its size is above a threshold.
95   void FlushToFile() {
96     if (!FS)
97       return;
98     if (Out.size() < FlushThreshold)
99       return;
100     FS->write((char *)&Out.front(), Out.size());
101     Out.clear();
102   }
103 
104 public:
105   /// Create a BitstreamWriter that writes to Buffer \p O.
106   ///
107   /// \p FS is the file stream that \p O flushes to incrementally. If \p FS is
108   /// null, \p O does not flush incrementially, but writes to disk at the end.
109   ///
110   /// \p FlushThreshold is the threshold (unit M) to flush \p O if \p FS is
111   /// valid. Flushing only occurs at (sub)block boundaries.
112   BitstreamWriter(SmallVectorImpl<char> &O, raw_fd_stream *FS = nullptr,
113                   uint32_t FlushThreshold = 512)
114       : Out(O), FS(FS), FlushThreshold(FlushThreshold << 20), CurBit(0),
115         CurValue(0), CurCodeSize(2) {}
116 
117   ~BitstreamWriter() {
118     assert(CurBit == 0 && "Unflushed data remaining");
119     assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
120   }
121 
122   /// Retrieve the current position in the stream, in bits.
123   uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
124 
125   /// Retrieve the number of bits currently used to encode an abbrev ID.
126   unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
127 
128   //===--------------------------------------------------------------------===//
129   // Basic Primitives for emitting bits to the stream.
130   //===--------------------------------------------------------------------===//
131 
132   /// Backpatch a 32-bit word in the output at the given bit offset
133   /// with the specified value.
134   void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
135     using namespace llvm::support;
136     uint64_t ByteNo = BitNo / 8;
137     uint64_t StartBit = BitNo & 7;
138     uint64_t NumOfFlushedBytes = GetNumOfFlushedBytes();
139 
140     if (ByteNo >= NumOfFlushedBytes) {
141       assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
142                  &Out[ByteNo - NumOfFlushedBytes], StartBit)) &&
143              "Expected to be patching over 0-value placeholders");
144       endian::writeAtBitAlignment<uint32_t, little, unaligned>(
145           &Out[ByteNo - NumOfFlushedBytes], NewWord, StartBit);
146       return;
147     }
148 
149     // If the byte offset to backpatch is flushed, use seek to backfill data.
150     // First, save the file position to restore later.
151     uint64_t CurPos = FS->tell();
152 
153     // Copy data to update into Bytes from the file FS and the buffer Out.
154     char Bytes[9]; // Use one more byte to silence a warning from Visual C++.
155     size_t BytesNum = StartBit ? 8 : 4;
156     size_t BytesFromDisk = std::min(static_cast<uint64_t>(BytesNum), NumOfFlushedBytes - ByteNo);
157     size_t BytesFromBuffer = BytesNum - BytesFromDisk;
158 
159     // When unaligned, copy existing data into Bytes from the file FS and the
160     // buffer Out so that it can be updated before writing. For debug builds
161     // read bytes unconditionally in order to check that the existing value is 0
162     // as expected.
163 #ifdef NDEBUG
164     if (StartBit)
165 #endif
166     {
167       FS->seek(ByteNo);
168       ssize_t BytesRead = FS->read(Bytes, BytesFromDisk);
169       (void)BytesRead; // silence warning
170       assert(BytesRead >= 0 && static_cast<size_t>(BytesRead) == BytesFromDisk);
171       for (size_t i = 0; i < BytesFromBuffer; ++i)
172         Bytes[BytesFromDisk + i] = Out[i];
173       assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
174                  Bytes, StartBit)) &&
175              "Expected to be patching over 0-value placeholders");
176     }
177 
178     // Update Bytes in terms of bit offset and value.
179     endian::writeAtBitAlignment<uint32_t, little, unaligned>(Bytes, NewWord,
180                                                              StartBit);
181 
182     // Copy updated data back to the file FS and the buffer Out.
183     FS->seek(ByteNo);
184     FS->write(Bytes, BytesFromDisk);
185     for (size_t i = 0; i < BytesFromBuffer; ++i)
186       Out[i] = Bytes[BytesFromDisk + i];
187 
188     // Restore the file position.
189     FS->seek(CurPos);
190   }
191 
192   void BackpatchWord64(uint64_t BitNo, uint64_t Val) {
193     BackpatchWord(BitNo, (uint32_t)Val);
194     BackpatchWord(BitNo + 32, (uint32_t)(Val >> 32));
195   }
196 
197   void Emit(uint32_t Val, unsigned NumBits) {
198     assert(NumBits && NumBits <= 32 && "Invalid value size!");
199     assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
200     CurValue |= Val << CurBit;
201     if (CurBit + NumBits < 32) {
202       CurBit += NumBits;
203       return;
204     }
205 
206     // Add the current word.
207     WriteWord(CurValue);
208 
209     if (CurBit)
210       CurValue = Val >> (32-CurBit);
211     else
212       CurValue = 0;
213     CurBit = (CurBit+NumBits) & 31;
214   }
215 
216   void FlushToWord() {
217     if (CurBit) {
218       WriteWord(CurValue);
219       CurBit = 0;
220       CurValue = 0;
221     }
222   }
223 
224   void EmitVBR(uint32_t Val, unsigned NumBits) {
225     assert(NumBits <= 32 && "Too many bits to emit!");
226     uint32_t Threshold = 1U << (NumBits-1);
227 
228     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
229     while (Val >= Threshold) {
230       Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
231       Val >>= NumBits-1;
232     }
233 
234     Emit(Val, NumBits);
235   }
236 
237   void EmitVBR64(uint64_t Val, unsigned NumBits) {
238     assert(NumBits <= 32 && "Too many bits to emit!");
239     if ((uint32_t)Val == Val)
240       return EmitVBR((uint32_t)Val, NumBits);
241 
242     uint32_t Threshold = 1U << (NumBits-1);
243 
244     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
245     while (Val >= Threshold) {
246       Emit(((uint32_t)Val & ((1 << (NumBits - 1)) - 1)) | (1 << (NumBits - 1)),
247            NumBits);
248       Val >>= NumBits-1;
249     }
250 
251     Emit((uint32_t)Val, NumBits);
252   }
253 
254   /// EmitCode - Emit the specified code.
255   void EmitCode(unsigned Val) {
256     Emit(Val, CurCodeSize);
257   }
258 
259   //===--------------------------------------------------------------------===//
260   // Block Manipulation
261   //===--------------------------------------------------------------------===//
262 
263   /// getBlockInfo - If there is block info for the specified ID, return it,
264   /// otherwise return null.
265   BlockInfo *getBlockInfo(unsigned BlockID) {
266     // Common case, the most recent entry matches BlockID.
267     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
268       return &BlockInfoRecords.back();
269 
270     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
271          i != e; ++i)
272       if (BlockInfoRecords[i].BlockID == BlockID)
273         return &BlockInfoRecords[i];
274     return nullptr;
275   }
276 
277   void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
278     // Block header:
279     //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
280     EmitCode(bitc::ENTER_SUBBLOCK);
281     EmitVBR(BlockID, bitc::BlockIDWidth);
282     EmitVBR(CodeLen, bitc::CodeLenWidth);
283     FlushToWord();
284 
285     size_t BlockSizeWordIndex = GetWordIndex();
286     unsigned OldCodeSize = CurCodeSize;
287 
288     // Emit a placeholder, which will be replaced when the block is popped.
289     Emit(0, bitc::BlockSizeWidth);
290 
291     CurCodeSize = CodeLen;
292 
293     // Push the outer block's abbrev set onto the stack, start out with an
294     // empty abbrev set.
295     BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
296     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
297 
298     // If there is a blockinfo for this BlockID, add all the predefined abbrevs
299     // to the abbrev list.
300     if (BlockInfo *Info = getBlockInfo(BlockID))
301       append_range(CurAbbrevs, Info->Abbrevs);
302   }
303 
304   void ExitBlock() {
305     assert(!BlockScope.empty() && "Block scope imbalance!");
306     const Block &B = BlockScope.back();
307 
308     // Block tail:
309     //    [END_BLOCK, <align4bytes>]
310     EmitCode(bitc::END_BLOCK);
311     FlushToWord();
312 
313     // Compute the size of the block, in words, not counting the size field.
314     size_t SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
315     uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
316 
317     // Update the block size field in the header of this sub-block.
318     BackpatchWord(BitNo, SizeInWords);
319 
320     // Restore the inner block's code size and abbrev table.
321     CurCodeSize = B.PrevCodeSize;
322     CurAbbrevs = std::move(B.PrevAbbrevs);
323     BlockScope.pop_back();
324     FlushToFile();
325   }
326 
327   //===--------------------------------------------------------------------===//
328   // Record Emission
329   //===--------------------------------------------------------------------===//
330 
331 private:
332   /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
333   /// record.  This is a no-op, since the abbrev specifies the literal to use.
334   template<typename uintty>
335   void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
336     assert(Op.isLiteral() && "Not a literal");
337     // If the abbrev specifies the literal value to use, don't emit
338     // anything.
339     assert(V == Op.getLiteralValue() &&
340            "Invalid abbrev for record!");
341   }
342 
343   /// EmitAbbreviatedField - Emit a single scalar field value with the specified
344   /// encoding.
345   template<typename uintty>
346   void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
347     assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
348 
349     // Encode the value as we are commanded.
350     switch (Op.getEncoding()) {
351     default: llvm_unreachable("Unknown encoding!");
352     case BitCodeAbbrevOp::Fixed:
353       if (Op.getEncodingData())
354         Emit((unsigned)V, (unsigned)Op.getEncodingData());
355       break;
356     case BitCodeAbbrevOp::VBR:
357       if (Op.getEncodingData())
358         EmitVBR64(V, (unsigned)Op.getEncodingData());
359       break;
360     case BitCodeAbbrevOp::Char6:
361       Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
362       break;
363     }
364   }
365 
366   /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
367   /// emission code.  If BlobData is non-null, then it specifies an array of
368   /// data that should be emitted as part of the Blob or Array operand that is
369   /// known to exist at the end of the record. If Code is specified, then
370   /// it is the record code to emit before the Vals, which must not contain
371   /// the code.
372   template <typename uintty>
373   void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
374                                 StringRef Blob, Optional<unsigned> Code) {
375     const char *BlobData = Blob.data();
376     unsigned BlobLen = (unsigned) Blob.size();
377     unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
378     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
379     const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
380 
381     EmitCode(Abbrev);
382 
383     unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
384     if (Code) {
385       assert(e && "Expected non-empty abbreviation");
386       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
387 
388       if (Op.isLiteral())
389         EmitAbbreviatedLiteral(Op, Code.value());
390       else {
391         assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
392                Op.getEncoding() != BitCodeAbbrevOp::Blob &&
393                "Expected literal or scalar");
394         EmitAbbreviatedField(Op, Code.value());
395       }
396     }
397 
398     unsigned RecordIdx = 0;
399     for (; i != e; ++i) {
400       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
401       if (Op.isLiteral()) {
402         assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
403         EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
404         ++RecordIdx;
405       } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
406         // Array case.
407         assert(i + 2 == e && "array op not second to last?");
408         const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
409 
410         // If this record has blob data, emit it, otherwise we must have record
411         // entries to encode this way.
412         if (BlobData) {
413           assert(RecordIdx == Vals.size() &&
414                  "Blob data and record entries specified for array!");
415           // Emit a vbr6 to indicate the number of elements present.
416           EmitVBR(static_cast<uint32_t>(BlobLen), 6);
417 
418           // Emit each field.
419           for (unsigned i = 0; i != BlobLen; ++i)
420             EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
421 
422           // Know that blob data is consumed for assertion below.
423           BlobData = nullptr;
424         } else {
425           // Emit a vbr6 to indicate the number of elements present.
426           EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
427 
428           // Emit each field.
429           for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
430             EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
431         }
432       } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
433         // If this record has blob data, emit it, otherwise we must have record
434         // entries to encode this way.
435 
436         if (BlobData) {
437           assert(RecordIdx == Vals.size() &&
438                  "Blob data and record entries specified for blob operand!");
439 
440           assert(Blob.data() == BlobData && "BlobData got moved");
441           assert(Blob.size() == BlobLen && "BlobLen got changed");
442           emitBlob(Blob);
443           BlobData = nullptr;
444         } else {
445           emitBlob(Vals.slice(RecordIdx));
446         }
447       } else {  // Single scalar field.
448         assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
449         EmitAbbreviatedField(Op, Vals[RecordIdx]);
450         ++RecordIdx;
451       }
452     }
453     assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
454     assert(BlobData == nullptr &&
455            "Blob data specified for record that doesn't use it!");
456   }
457 
458 public:
459   /// Emit a blob, including flushing before and tail-padding.
460   template <class UIntTy>
461   void emitBlob(ArrayRef<UIntTy> Bytes, bool ShouldEmitSize = true) {
462     // Emit a vbr6 to indicate the number of elements present.
463     if (ShouldEmitSize)
464       EmitVBR(static_cast<uint32_t>(Bytes.size()), 6);
465 
466     // Flush to a 32-bit alignment boundary.
467     FlushToWord();
468 
469     // Emit literal bytes.
470     assert(llvm::all_of(Bytes, [](UIntTy B) { return isUInt<8>(B); }));
471     Out.append(Bytes.begin(), Bytes.end());
472 
473     // Align end to 32-bits.
474     while (GetBufferOffset() & 3)
475       Out.push_back(0);
476   }
477   void emitBlob(StringRef Bytes, bool ShouldEmitSize = true) {
478     emitBlob(makeArrayRef((const uint8_t *)Bytes.data(), Bytes.size()),
479              ShouldEmitSize);
480   }
481 
482   /// EmitRecord - Emit the specified record to the stream, using an abbrev if
483   /// we have one to compress the output.
484   template <typename Container>
485   void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
486     if (!Abbrev) {
487       // If we don't have an abbrev to use, emit this in its fully unabbreviated
488       // form.
489       auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
490       EmitCode(bitc::UNABBREV_RECORD);
491       EmitVBR(Code, 6);
492       EmitVBR(Count, 6);
493       for (unsigned i = 0, e = Count; i != e; ++i)
494         EmitVBR64(Vals[i], 6);
495       return;
496     }
497 
498     EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
499   }
500 
501   /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
502   /// Unlike EmitRecord, the code for the record should be included in Vals as
503   /// the first entry.
504   template <typename Container>
505   void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
506     EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), None);
507   }
508 
509   /// EmitRecordWithBlob - Emit the specified record to the stream, using an
510   /// abbrev that includes a blob at the end.  The blob data to emit is
511   /// specified by the pointer and length specified at the end.  In contrast to
512   /// EmitRecord, this routine expects that the first entry in Vals is the code
513   /// of the record.
514   template <typename Container>
515   void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
516                           StringRef Blob) {
517     EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
518   }
519   template <typename Container>
520   void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
521                           const char *BlobData, unsigned BlobLen) {
522     return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
523                                     StringRef(BlobData, BlobLen), None);
524   }
525 
526   /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
527   /// that end with an array.
528   template <typename Container>
529   void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
530                            StringRef Array) {
531     EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
532   }
533   template <typename Container>
534   void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
535                            const char *ArrayData, unsigned ArrayLen) {
536     return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
537                                     StringRef(ArrayData, ArrayLen), None);
538   }
539 
540   //===--------------------------------------------------------------------===//
541   // Abbrev Emission
542   //===--------------------------------------------------------------------===//
543 
544 private:
545   // Emit the abbreviation as a DEFINE_ABBREV record.
546   void EncodeAbbrev(const BitCodeAbbrev &Abbv) {
547     EmitCode(bitc::DEFINE_ABBREV);
548     EmitVBR(Abbv.getNumOperandInfos(), 5);
549     for (unsigned i = 0, e = static_cast<unsigned>(Abbv.getNumOperandInfos());
550          i != e; ++i) {
551       const BitCodeAbbrevOp &Op = Abbv.getOperandInfo(i);
552       Emit(Op.isLiteral(), 1);
553       if (Op.isLiteral()) {
554         EmitVBR64(Op.getLiteralValue(), 8);
555       } else {
556         Emit(Op.getEncoding(), 3);
557         if (Op.hasEncodingData())
558           EmitVBR64(Op.getEncodingData(), 5);
559       }
560     }
561   }
562 public:
563 
564   /// Emits the abbreviation \p Abbv to the stream.
565   unsigned EmitAbbrev(std::shared_ptr<BitCodeAbbrev> Abbv) {
566     EncodeAbbrev(*Abbv);
567     CurAbbrevs.push_back(std::move(Abbv));
568     return static_cast<unsigned>(CurAbbrevs.size())-1 +
569       bitc::FIRST_APPLICATION_ABBREV;
570   }
571 
572   //===--------------------------------------------------------------------===//
573   // BlockInfo Block Emission
574   //===--------------------------------------------------------------------===//
575 
576   /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
577   void EnterBlockInfoBlock() {
578     EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
579     BlockInfoCurBID = ~0U;
580     BlockInfoRecords.clear();
581   }
582 private:
583   /// SwitchToBlockID - If we aren't already talking about the specified block
584   /// ID, emit a BLOCKINFO_CODE_SETBID record.
585   void SwitchToBlockID(unsigned BlockID) {
586     if (BlockInfoCurBID == BlockID) return;
587     SmallVector<unsigned, 2> V;
588     V.push_back(BlockID);
589     EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
590     BlockInfoCurBID = BlockID;
591   }
592 
593   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
594     if (BlockInfo *BI = getBlockInfo(BlockID))
595       return *BI;
596 
597     // Otherwise, add a new record.
598     BlockInfoRecords.emplace_back();
599     BlockInfoRecords.back().BlockID = BlockID;
600     return BlockInfoRecords.back();
601   }
602 
603 public:
604 
605   /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
606   /// BlockID.
607   unsigned EmitBlockInfoAbbrev(unsigned BlockID, std::shared_ptr<BitCodeAbbrev> Abbv) {
608     SwitchToBlockID(BlockID);
609     EncodeAbbrev(*Abbv);
610 
611     // Add the abbrev to the specified block record.
612     BlockInfo &Info = getOrCreateBlockInfo(BlockID);
613     Info.Abbrevs.push_back(std::move(Abbv));
614 
615     return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
616   }
617 };
618 
619 
620 } // End llvm namespace
621 
622 #endif
623