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