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/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Bitcode/BitCodes.h"
25 class BitstreamWriter {
26 SmallVectorImpl<char> &Out;
28 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
31 /// CurValue - The current value. Only bits < CurBit are valid.
34 /// CurCodeSize - This is the declared size of code values used for the
35 /// current block, in bits.
38 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
39 /// selected BLOCK ID.
40 unsigned BlockInfoCurBID;
42 /// CurAbbrevs - Abbrevs installed at in this block.
43 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
46 unsigned PrevCodeSize;
47 unsigned StartSizeWord;
48 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
49 Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
52 /// BlockScope - This tracks the current blocks that we have entered.
53 std::vector<Block> BlockScope;
55 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
56 /// These describe abbreviations that all blocks of the specified ID inherit.
59 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
61 std::vector<BlockInfo> BlockInfoRecords;
63 // BackpatchWord - Backpatch a 32-bit word in the output with the specified
65 void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
66 support::endian::write32le(&Out[ByteNo], NewWord);
69 void WriteByte(unsigned char Value) {
73 void WriteWord(unsigned Value) {
74 Value = support::endian::byte_swap<uint32_t, support::little>(Value);
75 Out.append(reinterpret_cast<const char *>(&Value),
76 reinterpret_cast<const char *>(&Value + 1));
79 unsigned GetBufferOffset() const {
83 unsigned GetWordIndex() const {
84 unsigned Offset = GetBufferOffset();
85 assert((Offset & 3) == 0 && "Not 32-bit aligned");
90 explicit BitstreamWriter(SmallVectorImpl<char> &O)
91 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
94 assert(CurBit == 0 && "Unflushed data remaining");
95 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
98 /// \brief Retrieve the current position in the stream, in bits.
99 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
101 //===--------------------------------------------------------------------===//
102 // Basic Primitives for emitting bits to the stream.
103 //===--------------------------------------------------------------------===//
105 void Emit(uint32_t Val, unsigned NumBits) {
106 assert(NumBits && NumBits <= 32 && "Invalid value size!");
107 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
108 CurValue |= Val << CurBit;
109 if (CurBit + NumBits < 32) {
114 // Add the current word.
118 CurValue = Val >> (32-CurBit);
121 CurBit = (CurBit+NumBits) & 31;
124 void Emit64(uint64_t Val, unsigned NumBits) {
126 Emit((uint32_t)Val, NumBits);
128 Emit((uint32_t)Val, 32);
129 Emit((uint32_t)(Val >> 32), NumBits-32);
141 void EmitVBR(uint32_t Val, unsigned NumBits) {
142 assert(NumBits <= 32 && "Too many bits to emit!");
143 uint32_t Threshold = 1U << (NumBits-1);
145 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
146 while (Val >= Threshold) {
147 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
154 void EmitVBR64(uint64_t Val, unsigned NumBits) {
155 assert(NumBits <= 32 && "Too many bits to emit!");
156 if ((uint32_t)Val == Val)
157 return EmitVBR((uint32_t)Val, NumBits);
159 uint32_t Threshold = 1U << (NumBits-1);
161 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
162 while (Val >= Threshold) {
163 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
164 (1 << (NumBits-1)), NumBits);
168 Emit((uint32_t)Val, NumBits);
171 /// EmitCode - Emit the specified code.
172 void EmitCode(unsigned Val) {
173 Emit(Val, CurCodeSize);
176 //===--------------------------------------------------------------------===//
177 // Block Manipulation
178 //===--------------------------------------------------------------------===//
180 /// getBlockInfo - If there is block info for the specified ID, return it,
181 /// otherwise return null.
182 BlockInfo *getBlockInfo(unsigned BlockID) {
183 // Common case, the most recent entry matches BlockID.
184 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
185 return &BlockInfoRecords.back();
187 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
189 if (BlockInfoRecords[i].BlockID == BlockID)
190 return &BlockInfoRecords[i];
194 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
196 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
197 EmitCode(bitc::ENTER_SUBBLOCK);
198 EmitVBR(BlockID, bitc::BlockIDWidth);
199 EmitVBR(CodeLen, bitc::CodeLenWidth);
202 unsigned BlockSizeWordIndex = GetWordIndex();
203 unsigned OldCodeSize = CurCodeSize;
205 // Emit a placeholder, which will be replaced when the block is popped.
206 Emit(0, bitc::BlockSizeWidth);
208 CurCodeSize = CodeLen;
210 // Push the outer block's abbrev set onto the stack, start out with an
212 BlockScope.emplace_back(OldCodeSize, BlockSizeWordIndex);
213 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
215 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
216 // to the abbrev list.
217 if (BlockInfo *Info = getBlockInfo(BlockID)) {
218 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
219 Info->Abbrevs.end());
224 assert(!BlockScope.empty() && "Block scope imbalance!");
225 const Block &B = BlockScope.back();
228 // [END_BLOCK, <align4bytes>]
229 EmitCode(bitc::END_BLOCK);
232 // Compute the size of the block, in words, not counting the size field.
233 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
234 unsigned ByteNo = B.StartSizeWord*4;
236 // Update the block size field in the header of this sub-block.
237 BackpatchWord(ByteNo, SizeInWords);
239 // Restore the inner block's code size and abbrev table.
240 CurCodeSize = B.PrevCodeSize;
241 CurAbbrevs = std::move(B.PrevAbbrevs);
242 BlockScope.pop_back();
245 //===--------------------------------------------------------------------===//
247 //===--------------------------------------------------------------------===//
250 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
251 /// record. This is a no-op, since the abbrev specifies the literal to use.
252 template<typename uintty>
253 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
254 assert(Op.isLiteral() && "Not a literal");
255 // If the abbrev specifies the literal value to use, don't emit
257 assert(V == Op.getLiteralValue() &&
258 "Invalid abbrev for record!");
261 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
263 template<typename uintty>
264 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
265 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
267 // Encode the value as we are commanded.
268 switch (Op.getEncoding()) {
269 default: llvm_unreachable("Unknown encoding!");
270 case BitCodeAbbrevOp::Fixed:
271 if (Op.getEncodingData())
272 Emit((unsigned)V, (unsigned)Op.getEncodingData());
274 case BitCodeAbbrevOp::VBR:
275 if (Op.getEncodingData())
276 EmitVBR64(V, (unsigned)Op.getEncodingData());
278 case BitCodeAbbrevOp::Char6:
279 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
284 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
285 /// emission code. If BlobData is non-null, then it specifies an array of
286 /// data that should be emitted as part of the Blob or Array operand that is
287 /// known to exist at the end of the record.
288 template<typename uintty>
289 void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
291 const char *BlobData = Blob.data();
292 unsigned BlobLen = (unsigned) Blob.size();
293 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
294 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
295 const BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo].get();
299 unsigned RecordIdx = 0;
300 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
302 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
303 if (Op.isLiteral()) {
304 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
305 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
307 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
309 assert(i+2 == e && "array op not second to last?");
310 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
312 // If this record has blob data, emit it, otherwise we must have record
313 // entries to encode this way.
315 assert(RecordIdx == Vals.size() &&
316 "Blob data and record entries specified for array!");
317 // Emit a vbr6 to indicate the number of elements present.
318 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
321 for (unsigned i = 0; i != BlobLen; ++i)
322 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
324 // Know that blob data is consumed for assertion below.
327 // Emit a vbr6 to indicate the number of elements present.
328 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
331 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
332 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
334 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
335 // If this record has blob data, emit it, otherwise we must have record
336 // entries to encode this way.
338 // Emit a vbr6 to indicate the number of elements present.
340 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
341 assert(RecordIdx == Vals.size() &&
342 "Blob data and record entries specified for blob operand!");
344 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
347 // Flush to a 32-bit alignment boundary.
350 // Emit each field as a literal byte.
352 for (unsigned i = 0; i != BlobLen; ++i)
353 WriteByte((unsigned char)BlobData[i]);
355 // Know that blob data is consumed for assertion below.
358 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
359 assert(isUInt<8>(Vals[RecordIdx]) &&
360 "Value too large to emit as blob");
361 WriteByte((unsigned char)Vals[RecordIdx]);
365 // Align end to 32-bits.
366 while (GetBufferOffset() & 3)
368 } else { // Single scalar field.
369 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
370 EmitAbbreviatedField(Op, Vals[RecordIdx]);
374 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
375 assert(BlobData == nullptr &&
376 "Blob data specified for record that doesn't use it!");
381 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
382 /// we have one to compress the output.
383 template<typename uintty>
384 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
385 unsigned Abbrev = 0) {
387 // If we don't have an abbrev to use, emit this in its fully unabbreviated
389 EmitCode(bitc::UNABBREV_RECORD);
391 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
392 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
393 EmitVBR64(Vals[i], 6);
397 // Insert the code into Vals to treat it uniformly.
398 Vals.insert(Vals.begin(), Code);
400 EmitRecordWithAbbrev(Abbrev, Vals);
403 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
404 /// Unlike EmitRecord, the code for the record should be included in Vals as
406 template<typename uintty>
407 void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
408 EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
411 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
412 /// abbrev that includes a blob at the end. The blob data to emit is
413 /// specified by the pointer and length specified at the end. In contrast to
414 /// EmitRecord, this routine expects that the first entry in Vals is the code
416 template<typename uintty>
417 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
419 EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
421 template<typename uintty>
422 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
423 const char *BlobData, unsigned BlobLen) {
424 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
427 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
428 /// that end with an array.
429 template<typename uintty>
430 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
432 EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
434 template<typename uintty>
435 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
436 const char *ArrayData, unsigned ArrayLen) {
437 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
441 //===--------------------------------------------------------------------===//
443 //===--------------------------------------------------------------------===//
446 // Emit the abbreviation as a DEFINE_ABBREV record.
447 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
448 EmitCode(bitc::DEFINE_ABBREV);
449 EmitVBR(Abbv->getNumOperandInfos(), 5);
450 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
452 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
453 Emit(Op.isLiteral(), 1);
454 if (Op.isLiteral()) {
455 EmitVBR64(Op.getLiteralValue(), 8);
457 Emit(Op.getEncoding(), 3);
458 if (Op.hasEncodingData())
459 EmitVBR64(Op.getEncodingData(), 5);
465 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
466 /// method takes ownership of the specified abbrev.
467 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
468 // Emit the abbreviation as a record.
470 CurAbbrevs.push_back(Abbv);
471 return static_cast<unsigned>(CurAbbrevs.size())-1 +
472 bitc::FIRST_APPLICATION_ABBREV;
475 //===--------------------------------------------------------------------===//
476 // BlockInfo Block Emission
477 //===--------------------------------------------------------------------===//
479 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
480 void EnterBlockInfoBlock(unsigned CodeWidth) {
481 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
482 BlockInfoCurBID = ~0U;
485 /// SwitchToBlockID - If we aren't already talking about the specified block
486 /// ID, emit a BLOCKINFO_CODE_SETBID record.
487 void SwitchToBlockID(unsigned BlockID) {
488 if (BlockInfoCurBID == BlockID) return;
489 SmallVector<unsigned, 2> V;
490 V.push_back(BlockID);
491 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
492 BlockInfoCurBID = BlockID;
495 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
496 if (BlockInfo *BI = getBlockInfo(BlockID))
499 // Otherwise, add a new record.
500 BlockInfoRecords.emplace_back();
501 BlockInfoRecords.back().BlockID = BlockID;
502 return BlockInfoRecords.back();
507 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
509 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
510 SwitchToBlockID(BlockID);
513 // Add the abbrev to the specified block record.
514 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
515 Info.Abbrevs.push_back(Abbv);
517 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
522 } // End llvm namespace