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 //===--------------------------------------------------------------------===//
99 // Basic Primitives for emitting bits to the stream.
100 //===--------------------------------------------------------------------===//
102 /// Backpatch a 32-bit word in the output at the given bit offset
103 /// with the specified value.
104 void BackpatchWord(uint64_t BitNo, unsigned NewWord) {
105 using namespace llvm::support;
106 unsigned ByteNo = BitNo / 8;
107 assert((!endian::readAtBitAlignment<uint32_t, little, unaligned>(
108 &Out[ByteNo], BitNo & 7)) &&
109 "Expected to be patching over 0-value placeholders");
110 endian::writeAtBitAlignment<uint32_t, little, unaligned>(
111 &Out[ByteNo], NewWord, BitNo & 7);
114 void Emit(uint32_t Val, unsigned NumBits) {
115 assert(NumBits && NumBits <= 32 && "Invalid value size!");
116 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
117 CurValue |= Val << CurBit;
118 if (CurBit + NumBits < 32) {
123 // Add the current word.
127 CurValue = Val >> (32-CurBit);
130 CurBit = (CurBit+NumBits) & 31;
133 void Emit64(uint64_t Val, unsigned NumBits) {
135 Emit((uint32_t)Val, NumBits);
137 Emit((uint32_t)Val, 32);
138 Emit((uint32_t)(Val >> 32), NumBits-32);
150 void EmitVBR(uint32_t Val, unsigned NumBits) {
151 assert(NumBits <= 32 && "Too many bits to emit!");
152 uint32_t Threshold = 1U << (NumBits-1);
154 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
155 while (Val >= Threshold) {
156 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
163 void EmitVBR64(uint64_t Val, unsigned NumBits) {
164 assert(NumBits <= 32 && "Too many bits to emit!");
165 if ((uint32_t)Val == Val)
166 return EmitVBR((uint32_t)Val, NumBits);
168 uint32_t Threshold = 1U << (NumBits-1);
170 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
171 while (Val >= Threshold) {
172 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
173 (1 << (NumBits-1)), NumBits);
177 Emit((uint32_t)Val, NumBits);
180 /// EmitCode - Emit the specified code.
181 void EmitCode(unsigned Val) {
182 Emit(Val, CurCodeSize);
185 //===--------------------------------------------------------------------===//
186 // Block Manipulation
187 //===--------------------------------------------------------------------===//
189 /// getBlockInfo - If there is block info for the specified ID, return it,
190 /// otherwise return null.
191 BlockInfo *getBlockInfo(unsigned BlockID) {
192 // Common case, the most recent entry matches BlockID.
193 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
194 return &BlockInfoRecords.back();
196 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
198 if (BlockInfoRecords[i].BlockID == BlockID)
199 return &BlockInfoRecords[i];
203 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
205 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
206 EmitCode(bitc::ENTER_SUBBLOCK);
207 EmitVBR(BlockID, bitc::BlockIDWidth);
208 EmitVBR(CodeLen, bitc::CodeLenWidth);
211 unsigned BlockSizeWordIndex = GetWordIndex();
212 unsigned OldCodeSize = CurCodeSize;
214 // Emit a placeholder, which will be replaced when the block is popped.
215 Emit(0, bitc::BlockSizeWidth);
217 CurCodeSize = CodeLen;
219 // Push the outer block's abbrev set onto the stack, start out with an
221 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
222 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
224 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
225 // to the abbrev list.
226 if (BlockInfo *Info = getBlockInfo(BlockID)) {
227 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
228 Info->Abbrevs.end());
233 assert(!BlockScope.empty() && "Block scope imbalance!");
234 const Block &B = BlockScope.back();
237 // [END_BLOCK, <align4bytes>]
238 EmitCode(bitc::END_BLOCK);
241 // Compute the size of the block, in words, not counting the size field.
242 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
243 uint64_t BitNo = B.StartSizeWord * 32;
245 // Update the block size field in the header of this sub-block.
246 BackpatchWord(BitNo, SizeInWords);
248 // Restore the inner block's code size and abbrev table.
249 CurCodeSize = B.PrevCodeSize;
250 CurAbbrevs = std::move(B.PrevAbbrevs);
251 BlockScope.pop_back();
254 //===--------------------------------------------------------------------===//
256 //===--------------------------------------------------------------------===//
259 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
260 /// record. This is a no-op, since the abbrev specifies the literal to use.
261 template<typename uintty>
262 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
263 assert(Op.isLiteral() && "Not a literal");
264 // If the abbrev specifies the literal value to use, don't emit
266 assert(V == Op.getLiteralValue() &&
267 "Invalid abbrev for record!");
270 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
272 template<typename uintty>
273 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
274 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
276 // Encode the value as we are commanded.
277 switch (Op.getEncoding()) {
278 default: llvm_unreachable("Unknown encoding!");
279 case BitCodeAbbrevOp::Fixed:
280 if (Op.getEncodingData())
281 Emit((unsigned)V, (unsigned)Op.getEncodingData());
283 case BitCodeAbbrevOp::VBR:
284 if (Op.getEncodingData())
285 EmitVBR64(V, (unsigned)Op.getEncodingData());
287 case BitCodeAbbrevOp::Char6:
288 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
293 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
294 /// emission code. If BlobData is non-null, then it specifies an array of
295 /// data that should be emitted as part of the Blob or Array operand that is
296 /// known to exist at the end of the record. If Code is specified, then
297 /// it is the record code to emit before the Vals, which must not contain
299 template <typename uintty>
300 void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
301 StringRef Blob, Optional<unsigned> Code) {
302 const char *BlobData = Blob.data();
303 unsigned BlobLen = (unsigned) Blob.size();
304 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
305 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
306 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
310 unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
312 assert(e && "Expected non-empty abbreviation");
313 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
316 EmitAbbreviatedLiteral(Op, Code.getValue());
318 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
319 Op.getEncoding() != BitCodeAbbrevOp::Blob &&
320 "Expected literal or scalar");
321 EmitAbbreviatedField(Op, Code.getValue());
325 unsigned RecordIdx = 0;
326 for (; i != e; ++i) {
327 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
328 if (Op.isLiteral()) {
329 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
330 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
332 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
334 assert(i + 2 == e && "array op not second to last?");
335 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
337 // If this record has blob data, emit it, otherwise we must have record
338 // entries to encode this way.
340 assert(RecordIdx == Vals.size() &&
341 "Blob data and record entries specified for array!");
342 // Emit a vbr6 to indicate the number of elements present.
343 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
346 for (unsigned i = 0; i != BlobLen; ++i)
347 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
349 // Know that blob data is consumed for assertion below.
352 // Emit a vbr6 to indicate the number of elements present.
353 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
356 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
357 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
359 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
360 // If this record has blob data, emit it, otherwise we must have record
361 // entries to encode this way.
363 // Emit a vbr6 to indicate the number of elements present.
365 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
366 assert(RecordIdx == Vals.size() &&
367 "Blob data and record entries specified for blob operand!");
369 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
372 // Flush to a 32-bit alignment boundary.
375 // Emit each field as a literal byte.
377 for (unsigned i = 0; i != BlobLen; ++i)
378 WriteByte((unsigned char)BlobData[i]);
380 // Know that blob data is consumed for assertion below.
383 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
384 assert(isUInt<8>(Vals[RecordIdx]) &&
385 "Value too large to emit as blob");
386 WriteByte((unsigned char)Vals[RecordIdx]);
390 // Align end to 32-bits.
391 while (GetBufferOffset() & 3)
393 } else { // Single scalar field.
394 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
395 EmitAbbreviatedField(Op, Vals[RecordIdx]);
399 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
400 assert(BlobData == nullptr &&
401 "Blob data specified for record that doesn't use it!");
406 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
407 /// we have one to compress the output.
408 template <typename Container>
409 void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
411 // If we don't have an abbrev to use, emit this in its fully unabbreviated
413 auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
414 EmitCode(bitc::UNABBREV_RECORD);
417 for (unsigned i = 0, e = Count; i != e; ++i)
418 EmitVBR64(Vals[i], 6);
422 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
425 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
426 /// Unlike EmitRecord, the code for the record should be included in Vals as
428 template <typename Container>
429 void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
430 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), None);
433 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
434 /// abbrev that includes a blob at the end. The blob data to emit is
435 /// specified by the pointer and length specified at the end. In contrast to
436 /// EmitRecord, this routine expects that the first entry in Vals is the code
438 template <typename Container>
439 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
441 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
443 template <typename Container>
444 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
445 const char *BlobData, unsigned BlobLen) {
446 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
447 StringRef(BlobData, BlobLen), None);
450 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
451 /// that end with an array.
452 template <typename Container>
453 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
455 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
457 template <typename Container>
458 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
459 const char *ArrayData, unsigned ArrayLen) {
460 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
461 StringRef(ArrayData, ArrayLen), None);
464 //===--------------------------------------------------------------------===//
466 //===--------------------------------------------------------------------===//
469 // Emit the abbreviation as a DEFINE_ABBREV record.
470 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
471 EmitCode(bitc::DEFINE_ABBREV);
472 EmitVBR(Abbv->getNumOperandInfos(), 5);
473 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
475 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
476 Emit(Op.isLiteral(), 1);
477 if (Op.isLiteral()) {
478 EmitVBR64(Op.getLiteralValue(), 8);
480 Emit(Op.getEncoding(), 3);
481 if (Op.hasEncodingData())
482 EmitVBR64(Op.getEncodingData(), 5);
488 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
489 /// method takes ownership of the specified abbrev.
490 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
491 // Emit the abbreviation as a record.
493 CurAbbrevs.push_back(Abbv);
494 return static_cast<unsigned>(CurAbbrevs.size())-1 +
495 bitc::FIRST_APPLICATION_ABBREV;
498 //===--------------------------------------------------------------------===//
499 // BlockInfo Block Emission
500 //===--------------------------------------------------------------------===//
502 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
503 void EnterBlockInfoBlock(unsigned CodeWidth) {
504 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
505 BlockInfoCurBID = ~0U;
508 /// SwitchToBlockID - If we aren't already talking about the specified block
509 /// ID, emit a BLOCKINFO_CODE_SETBID record.
510 void SwitchToBlockID(unsigned BlockID) {
511 if (BlockInfoCurBID == BlockID) return;
512 SmallVector<unsigned, 2> V;
513 V.push_back(BlockID);
514 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
515 BlockInfoCurBID = BlockID;
518 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
519 if (BlockInfo *BI = getBlockInfo(BlockID))
522 // Otherwise, add a new record.
523 BlockInfoRecords.emplace_back();
524 BlockInfoRecords.back().BlockID = BlockID;
525 return BlockInfoRecords.back();
530 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
532 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
533 SwitchToBlockID(BlockID);
536 // Add the abbrev to the specified block record.
537 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
538 Info.Abbrevs.push_back(Abbv);
540 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
545 } // End llvm namespace