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<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
49 unsigned PrevCodeSize;
51 std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
52 Block(unsigned PCS, size_t 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<std::shared_ptr<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 size_t GetBufferOffset() const { return Out.size(); }
78 size_t GetWordIndex() const {
79 size_t Offset = GetBufferOffset();
80 assert((Offset & 3) == 0 && "Not 32-bit aligned");
85 explicit BitstreamWriter(SmallVectorImpl<char> &O)
86 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
89 assert(CurBit == 0 && "Unflushed data remaining");
90 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
93 /// \brief Retrieve the current position in the stream, in bits.
94 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
96 /// \brief Retrieve the number of bits currently used to encode an abbrev ID.
97 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
99 //===--------------------------------------------------------------------===//
100 // Basic Primitives for emitting bits to the stream.
101 //===--------------------------------------------------------------------===//
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);
115 void BackpatchWord64(uint64_t BitNo, uint64_t Val) {
116 BackpatchWord(BitNo, (uint32_t)Val);
117 BackpatchWord(BitNo + 32, (uint32_t)(Val >> 32));
120 void Emit(uint32_t Val, unsigned NumBits) {
121 assert(NumBits && NumBits <= 32 && "Invalid value size!");
122 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
123 CurValue |= Val << CurBit;
124 if (CurBit + NumBits < 32) {
129 // Add the current word.
133 CurValue = Val >> (32-CurBit);
136 CurBit = (CurBit+NumBits) & 31;
147 void EmitVBR(uint32_t Val, unsigned NumBits) {
148 assert(NumBits <= 32 && "Too many bits to emit!");
149 uint32_t Threshold = 1U << (NumBits-1);
151 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
152 while (Val >= Threshold) {
153 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
160 void EmitVBR64(uint64_t Val, unsigned NumBits) {
161 assert(NumBits <= 32 && "Too many bits to emit!");
162 if ((uint32_t)Val == Val)
163 return EmitVBR((uint32_t)Val, NumBits);
165 uint32_t Threshold = 1U << (NumBits-1);
167 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
168 while (Val >= Threshold) {
169 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
170 (1 << (NumBits-1)), NumBits);
174 Emit((uint32_t)Val, NumBits);
177 /// EmitCode - Emit the specified code.
178 void EmitCode(unsigned Val) {
179 Emit(Val, CurCodeSize);
182 //===--------------------------------------------------------------------===//
183 // Block Manipulation
184 //===--------------------------------------------------------------------===//
186 /// getBlockInfo - If there is block info for the specified ID, return it,
187 /// otherwise return null.
188 BlockInfo *getBlockInfo(unsigned BlockID) {
189 // Common case, the most recent entry matches BlockID.
190 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
191 return &BlockInfoRecords.back();
193 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
195 if (BlockInfoRecords[i].BlockID == BlockID)
196 return &BlockInfoRecords[i];
200 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
202 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
203 EmitCode(bitc::ENTER_SUBBLOCK);
204 EmitVBR(BlockID, bitc::BlockIDWidth);
205 EmitVBR(CodeLen, bitc::CodeLenWidth);
208 size_t BlockSizeWordIndex = GetWordIndex();
209 unsigned OldCodeSize = CurCodeSize;
211 // Emit a placeholder, which will be replaced when the block is popped.
212 Emit(0, bitc::BlockSizeWidth);
214 CurCodeSize = CodeLen;
216 // Push the outer block's abbrev set onto the stack, start out with an
218 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
219 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
221 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
222 // to the abbrev list.
223 if (BlockInfo *Info = getBlockInfo(BlockID)) {
224 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
225 Info->Abbrevs.end());
230 assert(!BlockScope.empty() && "Block scope imbalance!");
231 const Block &B = BlockScope.back();
234 // [END_BLOCK, <align4bytes>]
235 EmitCode(bitc::END_BLOCK);
238 // Compute the size of the block, in words, not counting the size field.
239 size_t SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
240 uint64_t BitNo = uint64_t(B.StartSizeWord) * 32;
242 // Update the block size field in the header of this sub-block.
243 BackpatchWord(BitNo, SizeInWords);
245 // Restore the inner block's code size and abbrev table.
246 CurCodeSize = B.PrevCodeSize;
247 CurAbbrevs = std::move(B.PrevAbbrevs);
248 BlockScope.pop_back();
251 //===--------------------------------------------------------------------===//
253 //===--------------------------------------------------------------------===//
256 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
257 /// record. This is a no-op, since the abbrev specifies the literal to use.
258 template<typename uintty>
259 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
260 assert(Op.isLiteral() && "Not a literal");
261 // If the abbrev specifies the literal value to use, don't emit
263 assert(V == Op.getLiteralValue() &&
264 "Invalid abbrev for record!");
267 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
269 template<typename uintty>
270 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
271 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
273 // Encode the value as we are commanded.
274 switch (Op.getEncoding()) {
275 default: llvm_unreachable("Unknown encoding!");
276 case BitCodeAbbrevOp::Fixed:
277 if (Op.getEncodingData())
278 Emit((unsigned)V, (unsigned)Op.getEncodingData());
280 case BitCodeAbbrevOp::VBR:
281 if (Op.getEncodingData())
282 EmitVBR64(V, (unsigned)Op.getEncodingData());
284 case BitCodeAbbrevOp::Char6:
285 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
290 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
291 /// emission code. If BlobData is non-null, then it specifies an array of
292 /// data that should be emitted as part of the Blob or Array operand that is
293 /// known to exist at the end of the record. If Code is specified, then
294 /// it is the record code to emit before the Vals, which must not contain
296 template <typename uintty>
297 void EmitRecordWithAbbrevImpl(unsigned Abbrev, ArrayRef<uintty> Vals,
298 StringRef Blob, Optional<unsigned> Code) {
299 const char *BlobData = Blob.data();
300 unsigned BlobLen = (unsigned) Blob.size();
301 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
302 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
303 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
307 unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
309 assert(e && "Expected non-empty abbreviation");
310 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i++);
313 EmitAbbreviatedLiteral(Op, Code.getValue());
315 assert(Op.getEncoding() != BitCodeAbbrevOp::Array &&
316 Op.getEncoding() != BitCodeAbbrevOp::Blob &&
317 "Expected literal or scalar");
318 EmitAbbreviatedField(Op, Code.getValue());
322 unsigned RecordIdx = 0;
323 for (; i != e; ++i) {
324 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
325 if (Op.isLiteral()) {
326 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
327 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
329 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
331 assert(i + 2 == e && "array op not second to last?");
332 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
334 // If this record has blob data, emit it, otherwise we must have record
335 // entries to encode this way.
337 assert(RecordIdx == Vals.size() &&
338 "Blob data and record entries specified for array!");
339 // Emit a vbr6 to indicate the number of elements present.
340 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
343 for (unsigned i = 0; i != BlobLen; ++i)
344 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
346 // Know that blob data is consumed for assertion below.
349 // Emit a vbr6 to indicate the number of elements present.
350 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
353 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
354 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
356 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
357 // If this record has blob data, emit it, otherwise we must have record
358 // entries to encode this way.
361 assert(RecordIdx == Vals.size() &&
362 "Blob data and record entries specified for blob operand!");
364 assert(Blob.data() == BlobData && "BlobData got moved");
365 assert(Blob.size() == BlobLen && "BlobLen got changed");
369 emitBlob(Vals.slice(RecordIdx));
371 } else { // Single scalar field.
372 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
373 EmitAbbreviatedField(Op, Vals[RecordIdx]);
377 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
378 assert(BlobData == nullptr &&
379 "Blob data specified for record that doesn't use it!");
383 /// Emit a blob, including flushing before and tail-padding.
384 template <class UIntTy>
385 void emitBlob(ArrayRef<UIntTy> Bytes, bool ShouldEmitSize = true) {
386 // Emit a vbr6 to indicate the number of elements present.
388 EmitVBR(static_cast<uint32_t>(Bytes.size()), 6);
390 // Flush to a 32-bit alignment boundary.
393 // Emit literal bytes.
394 for (const auto &B : Bytes) {
395 assert(isUInt<8>(B) && "Value too large to emit as byte");
396 WriteByte((unsigned char)B);
399 // Align end to 32-bits.
400 while (GetBufferOffset() & 3)
403 void emitBlob(StringRef Bytes, bool ShouldEmitSize = true) {
404 emitBlob(makeArrayRef((const uint8_t *)Bytes.data(), Bytes.size()),
408 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
409 /// we have one to compress the output.
410 template <typename Container>
411 void EmitRecord(unsigned Code, const Container &Vals, unsigned Abbrev = 0) {
413 // If we don't have an abbrev to use, emit this in its fully unabbreviated
415 auto Count = static_cast<uint32_t>(makeArrayRef(Vals).size());
416 EmitCode(bitc::UNABBREV_RECORD);
419 for (unsigned i = 0, e = Count; i != e; ++i)
420 EmitVBR64(Vals[i], 6);
424 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), Code);
427 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
428 /// Unlike EmitRecord, the code for the record should be included in Vals as
430 template <typename Container>
431 void EmitRecordWithAbbrev(unsigned Abbrev, const Container &Vals) {
432 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), StringRef(), None);
435 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
436 /// abbrev that includes a blob at the end. The blob data to emit is
437 /// specified by the pointer and length specified at the end. In contrast to
438 /// EmitRecord, this routine expects that the first entry in Vals is the code
440 template <typename Container>
441 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
443 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Blob, None);
445 template <typename Container>
446 void EmitRecordWithBlob(unsigned Abbrev, const Container &Vals,
447 const char *BlobData, unsigned BlobLen) {
448 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
449 StringRef(BlobData, BlobLen), None);
452 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
453 /// that end with an array.
454 template <typename Container>
455 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
457 EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals), Array, None);
459 template <typename Container>
460 void EmitRecordWithArray(unsigned Abbrev, const Container &Vals,
461 const char *ArrayData, unsigned ArrayLen) {
462 return EmitRecordWithAbbrevImpl(Abbrev, makeArrayRef(Vals),
463 StringRef(ArrayData, ArrayLen), None);
466 //===--------------------------------------------------------------------===//
468 //===--------------------------------------------------------------------===//
471 // Emit the abbreviation as a DEFINE_ABBREV record.
472 void EncodeAbbrev(const BitCodeAbbrev &Abbv) {
473 EmitCode(bitc::DEFINE_ABBREV);
474 EmitVBR(Abbv.getNumOperandInfos(), 5);
475 for (unsigned i = 0, e = static_cast<unsigned>(Abbv.getNumOperandInfos());
477 const BitCodeAbbrevOp &Op = Abbv.getOperandInfo(i);
478 Emit(Op.isLiteral(), 1);
479 if (Op.isLiteral()) {
480 EmitVBR64(Op.getLiteralValue(), 8);
482 Emit(Op.getEncoding(), 3);
483 if (Op.hasEncodingData())
484 EmitVBR64(Op.getEncodingData(), 5);
490 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
491 /// method takes ownership of the specified abbrev.
492 unsigned EmitAbbrev(std::shared_ptr<BitCodeAbbrev> Abbv) {
493 // Emit the abbreviation as a record.
495 CurAbbrevs.push_back(std::move(Abbv));
496 return static_cast<unsigned>(CurAbbrevs.size())-1 +
497 bitc::FIRST_APPLICATION_ABBREV;
500 //===--------------------------------------------------------------------===//
501 // BlockInfo Block Emission
502 //===--------------------------------------------------------------------===//
504 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
505 void EnterBlockInfoBlock() {
506 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, 2);
507 BlockInfoCurBID = ~0U;
508 BlockInfoRecords.clear();
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, std::shared_ptr<BitCodeAbbrev> Abbv) {
536 SwitchToBlockID(BlockID);
539 // Add the abbrev to the specified block record.
540 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
541 Info.Abbrevs.push_back(std::move(Abbv));
543 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
548 } // End llvm namespace