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 // BackpatchWord - Backpatch a 32-bit word in the output with the specified
68 void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
69 support::endian::write32le(&Out[ByteNo], NewWord);
72 void WriteByte(unsigned char Value) {
76 void WriteWord(unsigned Value) {
77 Value = support::endian::byte_swap<uint32_t, support::little>(Value);
78 Out.append(reinterpret_cast<const char *>(&Value),
79 reinterpret_cast<const char *>(&Value + 1));
82 unsigned GetBufferOffset() const {
86 unsigned GetWordIndex() const {
87 unsigned Offset = GetBufferOffset();
88 assert((Offset & 3) == 0 && "Not 32-bit aligned");
93 explicit BitstreamWriter(SmallVectorImpl<char> &O)
94 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
97 assert(CurBit == 0 && "Unflushed data remaining");
98 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
101 /// \brief Retrieve the current position in the stream, in bits.
102 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
104 //===--------------------------------------------------------------------===//
105 // Basic Primitives for emitting bits to the stream.
106 //===--------------------------------------------------------------------===//
108 void Emit(uint32_t Val, unsigned NumBits) {
109 assert(NumBits && NumBits <= 32 && "Invalid value size!");
110 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
111 CurValue |= Val << CurBit;
112 if (CurBit + NumBits < 32) {
117 // Add the current word.
121 CurValue = Val >> (32-CurBit);
124 CurBit = (CurBit+NumBits) & 31;
127 void Emit64(uint64_t Val, unsigned NumBits) {
129 Emit((uint32_t)Val, NumBits);
131 Emit((uint32_t)Val, 32);
132 Emit((uint32_t)(Val >> 32), NumBits-32);
144 void EmitVBR(uint32_t Val, unsigned NumBits) {
145 assert(NumBits <= 32 && "Too many bits to emit!");
146 uint32_t Threshold = 1U << (NumBits-1);
148 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
149 while (Val >= Threshold) {
150 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
157 void EmitVBR64(uint64_t Val, unsigned NumBits) {
158 assert(NumBits <= 32 && "Too many bits to emit!");
159 if ((uint32_t)Val == Val)
160 return EmitVBR((uint32_t)Val, NumBits);
162 uint32_t Threshold = 1U << (NumBits-1);
164 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
165 while (Val >= Threshold) {
166 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
167 (1 << (NumBits-1)), NumBits);
171 Emit((uint32_t)Val, NumBits);
174 /// EmitCode - Emit the specified code.
175 void EmitCode(unsigned Val) {
176 Emit(Val, CurCodeSize);
179 //===--------------------------------------------------------------------===//
180 // Block Manipulation
181 //===--------------------------------------------------------------------===//
183 /// getBlockInfo - If there is block info for the specified ID, return it,
184 /// otherwise return null.
185 BlockInfo *getBlockInfo(unsigned BlockID) {
186 // Common case, the most recent entry matches BlockID.
187 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
188 return &BlockInfoRecords.back();
190 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
192 if (BlockInfoRecords[i].BlockID == BlockID)
193 return &BlockInfoRecords[i];
197 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
199 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
200 EmitCode(bitc::ENTER_SUBBLOCK);
201 EmitVBR(BlockID, bitc::BlockIDWidth);
202 EmitVBR(CodeLen, bitc::CodeLenWidth);
205 unsigned BlockSizeWordIndex = GetWordIndex();
206 unsigned OldCodeSize = CurCodeSize;
208 // Emit a placeholder, which will be replaced when the block is popped.
209 Emit(0, bitc::BlockSizeWidth);
211 CurCodeSize = CodeLen;
213 // Push the outer block's abbrev set onto the stack, start out with an
215 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
216 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
218 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
219 // to the abbrev list.
220 if (BlockInfo *Info = getBlockInfo(BlockID)) {
221 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
222 Info->Abbrevs.end());
227 assert(!BlockScope.empty() && "Block scope imbalance!");
228 const Block &B = BlockScope.back();
231 // [END_BLOCK, <align4bytes>]
232 EmitCode(bitc::END_BLOCK);
235 // Compute the size of the block, in words, not counting the size field.
236 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
237 unsigned ByteNo = B.StartSizeWord*4;
239 // Update the block size field in the header of this sub-block.
240 BackpatchWord(ByteNo, SizeInWords);
242 // Restore the inner block's code size and abbrev table.
243 CurCodeSize = B.PrevCodeSize;
244 CurAbbrevs = std::move(B.PrevAbbrevs);
245 BlockScope.pop_back();
248 //===--------------------------------------------------------------------===//
250 //===--------------------------------------------------------------------===//
253 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
254 /// record. This is a no-op, since the abbrev specifies the literal to use.
255 template<typename uintty>
256 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
257 assert(Op.isLiteral() && "Not a literal");
258 // If the abbrev specifies the literal value to use, don't emit
260 assert(V == Op.getLiteralValue() &&
261 "Invalid abbrev for record!");
264 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
266 template<typename uintty>
267 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
268 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
270 // Encode the value as we are commanded.
271 switch (Op.getEncoding()) {
272 default: llvm_unreachable("Unknown encoding!");
273 case BitCodeAbbrevOp::Fixed:
274 if (Op.getEncodingData())
275 Emit((unsigned)V, (unsigned)Op.getEncodingData());
277 case BitCodeAbbrevOp::VBR:
278 if (Op.getEncodingData())
279 EmitVBR64(V, (unsigned)Op.getEncodingData());
281 case BitCodeAbbrevOp::Char6:
282 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
287 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
288 /// emission code. If BlobData is non-null, then it specifies an array of
289 /// data that should be emitted as part of the Blob or Array operand that is
290 /// known to exist at the end of the record. If Code is specified, then
291 /// it is the record code to emit before the Vals, which must not contain
293 template <typename uintty>
294 void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
295 StringRef Blob, Optional<unsigned> Code) {
296 const char *BlobData = Blob.data();
297 unsigned BlobLen = (unsigned) Blob.size();
298 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
299 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
300 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
304 unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
306 assert(e && "Expected non-empty abbreviation");
307 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
310 EmitAbbreviatedLiteral(Op, Code.getValue());
312 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
313 Op.getEncoding() != BitCodeAbbrevOp::Blob &&
314 "Expected literal or scalar");
315 EmitAbbreviatedField(Op, Code.getValue());
319 unsigned RecordIdx = 0;
320 for (; i != e; ++i) {
321 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
322 if (Op.isLiteral()) {
323 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
324 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
326 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
328 assert(i + 2 == e && "array op not second to last?");
329 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
331 // If this record has blob data, emit it, otherwise we must have record
332 // entries to encode this way.
334 assert(RecordIdx == Vals.size() &&
335 "Blob data and record entries specified for array!");
336 // Emit a vbr6 to indicate the number of elements present.
337 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
340 for (unsigned i = 0; i != BlobLen; ++i)
341 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
343 // Know that blob data is consumed for assertion below.
346 // Emit a vbr6 to indicate the number of elements present.
347 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
350 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
351 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
353 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
354 // If this record has blob data, emit it, otherwise we must have record
355 // entries to encode this way.
357 // Emit a vbr6 to indicate the number of elements present.
359 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
360 assert(RecordIdx == Vals.size() &&
361 "Blob data and record entries specified for blob operand!");
363 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
366 // Flush to a 32-bit alignment boundary.
369 // Emit each field as a literal byte.
371 for (unsigned i = 0; i != BlobLen; ++i)
372 WriteByte((unsigned char)BlobData[i]);
374 // Know that blob data is consumed for assertion below.
377 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
378 assert(isUInt<8>(Vals[RecordIdx]) &&
379 "Value too large to emit as blob");
380 WriteByte((unsigned char)Vals[RecordIdx]);
384 // Align end to 32-bits.
385 while (GetBufferOffset() & 3)
387 } else { // Single scalar field.
388 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
389 EmitAbbreviatedField(Op, Vals[RecordIdx]);
393 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
394 assert(BlobData == nullptr &&
395 "Blob data specified for record that doesn't use it!");
400 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
401 /// we have one to compress the output.
402 template <typename Container>
403 void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
405 // If we don't have an abbrev to use, emit this in its fully unabbreviated
407 auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
408 EmitCode(bitc::UNABBREV_RECORD);
411 for (unsigned i = 0, e = Count; i != e; ++i)
412 EmitVBR64(Vals[i], 6);
416 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
419 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
420 /// Unlike EmitRecord, the code for the record should be included in Vals as
422 template <typename Container>
423 void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
424 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), None);
427 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
428 /// abbrev that includes a blob at the end. The blob data to emit is
429 /// specified by the pointer and length specified at the end. In contrast to
430 /// EmitRecord, this routine expects that the first entry in Vals is the code
432 template <typename Container>
433 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
435 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
437 template <typename Container>
438 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
439 const char *BlobData, unsigned BlobLen) {
440 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
441 StringRef(BlobData, BlobLen), None);
444 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
445 /// that end with an array.
446 template <typename Container>
447 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
449 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
451 template <typename Container>
452 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
453 const char *ArrayData, unsigned ArrayLen) {
454 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
455 StringRef(ArrayData, ArrayLen), None);
458 //===--------------------------------------------------------------------===//
460 //===--------------------------------------------------------------------===//
463 // Emit the abbreviation as a DEFINE_ABBREV record.
464 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
465 EmitCode(bitc::DEFINE_ABBREV);
466 EmitVBR(Abbv->getNumOperandInfos(), 5);
467 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
469 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
470 Emit(Op.isLiteral(), 1);
471 if (Op.isLiteral()) {
472 EmitVBR64(Op.getLiteralValue(), 8);
474 Emit(Op.getEncoding(), 3);
475 if (Op.hasEncodingData())
476 EmitVBR64(Op.getEncodingData(), 5);
482 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
483 /// method takes ownership of the specified abbrev.
484 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
485 // Emit the abbreviation as a record.
487 CurAbbrevs.push_back(Abbv);
488 return static_cast<unsigned>(CurAbbrevs.size())-1 +
489 bitc::FIRST_APPLICATION_ABBREV;
492 //===--------------------------------------------------------------------===//
493 // BlockInfo Block Emission
494 //===--------------------------------------------------------------------===//
496 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
497 void EnterBlockInfoBlock(unsigned CodeWidth) {
498 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
499 BlockInfoCurBID = ~0U;
502 /// SwitchToBlockID - If we aren't already talking about the specified block
503 /// ID, emit a BLOCKINFO_CODE_SETBID record.
504 void SwitchToBlockID(unsigned BlockID) {
505 if (BlockInfoCurBID == BlockID) return;
506 SmallVector<unsigned, 2> V;
507 V.push_back(BlockID);
508 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
509 BlockInfoCurBID = BlockID;
512 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
513 if (BlockInfo *BI = getBlockInfo(BlockID))
516 // Otherwise, add a new record.
517 BlockInfoRecords.emplace_back();
518 BlockInfoRecords.back().BlockID = BlockID;
519 return BlockInfoRecords.back();
524 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
526 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
527 SwitchToBlockID(BlockID);
530 // Add the abbrev to the specified block record.
531 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
532 Info.Abbrevs.push_back(Abbv);
534 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
539 } // End llvm namespace