1 //===- BitstreamWriter.h - Low-level bitstream writer interface -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitstreamWriter class. This class can be used to
11 // write an arbitrary bitstream, regardless of its contents.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_BITCODE_BITSTREAMWRITER_H
16 #define LLVM_BITCODE_BITSTREAMWRITER_H
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"
28 class BitstreamWriter {
29 SmallVectorImpl<char> &Out;
31 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
34 /// CurValue - The current value. Only bits < CurBit are valid.
37 /// CurCodeSize - This is the declared size of code values used for the
38 /// current block, in bits.
41 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
42 /// selected BLOCK ID.
43 unsigned BlockInfoCurBID;
45 /// CurAbbrevs - Abbrevs installed at in this block.
46 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
49 unsigned PrevCodeSize;
50 unsigned StartSizeWord;
51 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
52 Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
55 /// BlockScope - This tracks the current blocks that we have entered.
56 std::vector<Block> BlockScope;
58 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
59 /// These describe abbreviations that all blocks of the specified ID inherit.
62 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
64 std::vector<BlockInfo> BlockInfoRecords;
66 void WriteByte(unsigned char Value) {
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));
76 unsigned GetBufferOffset() const {
80 unsigned GetWordIndex() const {
81 unsigned Offset = GetBufferOffset();
82 assert((Offset & 3) == 0 && "Not 32-bit aligned");
87 explicit BitstreamWriter(SmallVectorImpl<char> &O)
88 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
91 assert(CurBit == 0 && "Unflushed data remaining");
92 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
95 /// \brief Retrieve the current position in the stream, in bits.
96 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
98 /// \brief Retrieve the number of bits currently used to encode an abbrev ID.
99 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
101 //===--------------------------------------------------------------------===//
102 // Basic Primitives for emitting bits to the stream.
103 //===--------------------------------------------------------------------===//
105 /// Backpatch a 32-bit word in the output at the given bit offset
106 /// with the specified value.
107 void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
108 using namespace llvm::support;
109 unsigned ByteNo = BitNo / 8;
110 assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
111 &Out[ByteNo], BitNo & 7)) &&
112 "Expected to be patching over 0-value placeholders");
113 endian::writeAtBitAlignment<uint32_t, little, unaligned>(
114 &Out[ByteNo], NewWord, BitNo & 7);
117 void Emit(uint32_t Val, unsigned NumBits) {
118 assert(NumBits && NumBits <= 32 && "Invalid value size!");
119 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
120 CurValue |= Val << CurBit;
121 if (CurBit + NumBits < 32) {
126 // Add the current word.
130 CurValue = Val >> (32-CurBit);
133 CurBit = (CurBit+NumBits) & 31;
136 void Emit64(uint64_t Val, unsigned NumBits) {
138 Emit((uint32_t)Val, NumBits);
140 Emit((uint32_t)Val, 32);
141 Emit((uint32_t)(Val >> 32), NumBits-32);
153 void EmitVBR(uint32_t Val, unsigned NumBits) {
154 assert(NumBits <= 32 && "Too many bits to emit!");
155 uint32_t Threshold = 1U << (NumBits-1);
157 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
158 while (Val >= Threshold) {
159 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
166 void EmitVBR64(uint64_t Val, unsigned NumBits) {
167 assert(NumBits <= 32 && "Too many bits to emit!");
168 if ((uint32_t)Val == Val)
169 return EmitVBR((uint32_t)Val, NumBits);
171 uint32_t Threshold = 1U << (NumBits-1);
173 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
174 while (Val >= Threshold) {
175 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
176 (1 << (NumBits-1)), NumBits);
180 Emit((uint32_t)Val, NumBits);
183 /// EmitCode - Emit the specified code.
184 void EmitCode(unsigned Val) {
185 Emit(Val, CurCodeSize);
188 //===--------------------------------------------------------------------===//
189 // Block Manipulation
190 //===--------------------------------------------------------------------===//
192 /// getBlockInfo - If there is block info for the specified ID, return it,
193 /// otherwise return null.
194 BlockInfo *getBlockInfo(unsigned BlockID) {
195 // Common case, the most recent entry matches BlockID.
196 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
197 return &BlockInfoRecords.back();
199 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
201 if (BlockInfoRecords[i].BlockID == BlockID)
202 return &BlockInfoRecords[i];
206 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
208 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
209 EmitCode(bitc::ENTER_SUBBLOCK);
210 EmitVBR(BlockID, bitc::BlockIDWidth);
211 EmitVBR(CodeLen, bitc::CodeLenWidth);
214 unsigned BlockSizeWordIndex = GetWordIndex();
215 unsigned OldCodeSize = CurCodeSize;
217 // Emit a placeholder, which will be replaced when the block is popped.
218 Emit(0, bitc::BlockSizeWidth);
220 CurCodeSize = CodeLen;
222 // Push the outer block's abbrev set onto the stack, start out with an
224 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
225 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
227 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
228 // to the abbrev list.
229 if (BlockInfo *Info = getBlockInfo(BlockID)) {
230 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
231 Info->Abbrevs.end());
236 assert(!BlockScope.empty() && "Block scope imbalance!");
237 const Block &B = BlockScope.back();
240 // [END_BLOCK, <align4bytes>]
241 EmitCode(bitc::END_BLOCK);
244 // Compute the size of the block, in words, not counting the size field.
245 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
246 uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
248 // Update the block size field in the header of this sub-block.
249 BackpatchWord(BitNo, SizeInWords);
251 // Restore the inner block's code size and abbrev table.
252 CurCodeSize = B.PrevCodeSize;
253 CurAbbrevs = std::move(B.PrevAbbrevs);
254 BlockScope.pop_back();
257 //===--------------------------------------------------------------------===//
259 //===--------------------------------------------------------------------===//
262 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
263 /// record. This is a no-op, since the abbrev specifies the literal to use.
264 template<typename uintty>
265 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
266 assert(Op.isLiteral() && "Not a literal");
267 // If the abbrev specifies the literal value to use, don't emit
269 assert(V == Op.getLiteralValue() &&
270 "Invalid abbrev for record!");
273 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
275 template<typename uintty>
276 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
277 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
279 // Encode the value as we are commanded.
280 switch (Op.getEncoding()) {
281 default: llvm_unreachable("Unknown encoding!");
282 case BitCodeAbbrevOp::Fixed:
283 if (Op.getEncodingData())
284 Emit((unsigned)V, (unsigned)Op.getEncodingData());
286 case BitCodeAbbrevOp::VBR:
287 if (Op.getEncodingData())
288 EmitVBR64(V, (unsigned)Op.getEncodingData());
290 case BitCodeAbbrevOp::Char6:
291 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
296 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
297 /// emission code. If BlobData is non-null, then it specifies an array of
298 /// data that should be emitted as part of the Blob or Array operand that is
299 /// known to exist at the end of the record. If Code is specified, then
300 /// it is the record code to emit before the Vals, which must not contain
302 template <typename uintty>
303 void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
304 StringRef Blob, Optional<unsigned> Code) {
305 const char *BlobData = Blob.data();
306 unsigned BlobLen = (unsigned) Blob.size();
307 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
308 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
309 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
313 unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
315 assert(e && "Expected non-empty abbreviation");
316 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
319 EmitAbbreviatedLiteral(Op, Code.getValue());
321 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
322 Op.getEncoding() != BitCodeAbbrevOp::Blob &&
323 "Expected literal or scalar");
324 EmitAbbreviatedField(Op, Code.getValue());
328 unsigned RecordIdx = 0;
329 for (; i != e; ++i) {
330 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
331 if (Op.isLiteral()) {
332 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
333 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
335 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
337 assert(i + 2 == e && "array op not second to last?");
338 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
340 // If this record has blob data, emit it, otherwise we must have record
341 // entries to encode this way.
343 assert(RecordIdx == Vals.size() &&
344 "Blob data and record entries specified for array!");
345 // Emit a vbr6 to indicate the number of elements present.
346 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
349 for (unsigned i = 0; i != BlobLen; ++i)
350 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
352 // Know that blob data is consumed for assertion below.
355 // Emit a vbr6 to indicate the number of elements present.
356 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
359 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
360 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
362 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
363 // If this record has blob data, emit it, otherwise we must have record
364 // entries to encode this way.
366 // Emit a vbr6 to indicate the number of elements present.
368 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
369 assert(RecordIdx == Vals.size() &&
370 "Blob data and record entries specified for blob operand!");
372 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
375 // Flush to a 32-bit alignment boundary.
378 // Emit each field as a literal byte.
380 for (unsigned i = 0; i != BlobLen; ++i)
381 WriteByte((unsigned char)BlobData[i]);
383 // Know that blob data is consumed for assertion below.
386 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
387 assert(isUInt<8>(Vals[RecordIdx]) &&
388 "Value too large to emit as blob");
389 WriteByte((unsigned char)Vals[RecordIdx]);
393 // Align end to 32-bits.
394 while (GetBufferOffset() & 3)
396 } else { // Single scalar field.
397 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
398 EmitAbbreviatedField(Op, Vals[RecordIdx]);
402 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
403 assert(BlobData == nullptr &&
404 "Blob data specified for record that doesn't use it!");
409 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
410 /// we have one to compress the output.
411 template <typename Container>
412 void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
414 // If we don't have an abbrev to use, emit this in its fully unabbreviated
416 auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
417 EmitCode(bitc::UNABBREV_RECORD);
420 for (unsigned i = 0, e = Count; i != e; ++i)
421 EmitVBR64(Vals[i], 6);
425 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
428 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
429 /// Unlike EmitRecord, the code for the record should be included in Vals as
431 template <typename Container>
432 void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
433 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), None);
436 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
437 /// abbrev that includes a blob at the end. The blob data to emit is
438 /// specified by the pointer and length specified at the end. In contrast to
439 /// EmitRecord, this routine expects that the first entry in Vals is the code
441 template <typename Container>
442 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
444 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
446 template <typename Container>
447 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
448 const char *BlobData, unsigned BlobLen) {
449 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
450 StringRef(BlobData, BlobLen), None);
453 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
454 /// that end with an array.
455 template <typename Container>
456 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
458 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
460 template <typename Container>
461 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
462 const char *ArrayData, unsigned ArrayLen) {
463 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
464 StringRef(ArrayData, ArrayLen), None);
467 //===--------------------------------------------------------------------===//
469 //===--------------------------------------------------------------------===//
472 // Emit the abbreviation as a DEFINE_ABBREV record.
473 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
474 EmitCode(bitc::DEFINE_ABBREV);
475 EmitVBR(Abbv->getNumOperandInfos(), 5);
476 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
478 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
479 Emit(Op.isLiteral(), 1);
480 if (Op.isLiteral()) {
481 EmitVBR64(Op.getLiteralValue(), 8);
483 Emit(Op.getEncoding(), 3);
484 if (Op.hasEncodingData())
485 EmitVBR64(Op.getEncodingData(), 5);
491 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
492 /// method takes ownership of the specified abbrev.
493 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
494 // Emit the abbreviation as a record.
496 CurAbbrevs.push_back(Abbv);
497 return static_cast<unsigned>(CurAbbrevs.size())-1 +
498 bitc::FIRST_APPLICATION_ABBREV;
501 //===--------------------------------------------------------------------===//
502 // BlockInfo Block Emission
503 //===--------------------------------------------------------------------===//
505 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
506 void EnterBlockInfoBlock(unsigned CodeWidth) {
507 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
508 BlockInfoCurBID = ~0U;
511 /// SwitchToBlockID - If we aren't already talking about the specified block
512 /// ID, emit a BLOCKINFO_CODE_SETBID record.
513 void SwitchToBlockID(unsigned BlockID) {
514 if (BlockInfoCurBID == BlockID) return;
515 SmallVector<unsigned, 2> V;
516 V.push_back(BlockID);
517 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
518 BlockInfoCurBID = BlockID;
521 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
522 if (BlockInfo *BI = getBlockInfo(BlockID))
525 // Otherwise, add a new record.
526 BlockInfoRecords.emplace_back();
527 BlockInfoRecords.back().BlockID = BlockID;
528 return BlockInfoRecords.back();
533 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
535 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
536 SwitchToBlockID(BlockID);
539 // Add the abbrev to the specified block record.
540 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
541 Info.Abbrevs.push_back(Abbv);
543 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
548 } // End llvm namespace