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 BITSTREAM_WRITER_H
16 #define BITSTREAM_WRITER_H
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/SmallVector.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<BitCodeAbbrev*> CurAbbrevs;
46 unsigned PrevCodeSize;
47 unsigned StartSizeWord;
48 std::vector<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<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 Out[ByteNo++] = (unsigned char)(NewWord >> 0);
67 Out[ByteNo++] = (unsigned char)(NewWord >> 8);
68 Out[ByteNo++] = (unsigned char)(NewWord >> 16);
69 Out[ByteNo ] = (unsigned char)(NewWord >> 24);
72 void WriteByte(unsigned char Value) {
76 void WriteWord(unsigned Value) {
77 unsigned char Bytes[4] = {
78 (unsigned char)(Value >> 0),
79 (unsigned char)(Value >> 8),
80 (unsigned char)(Value >> 16),
81 (unsigned char)(Value >> 24) };
82 Out.append(&Bytes[0], &Bytes[4]);
85 unsigned GetBufferOffset() const {
89 unsigned GetWordIndex() const {
90 unsigned Offset = GetBufferOffset();
91 assert((Offset & 3) == 0 && "Not 32-bit aligned");
96 explicit BitstreamWriter(SmallVectorImpl<char> &O)
97 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
100 assert(CurBit == 0 && "Unflused data remaining");
101 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
103 // Free the BlockInfoRecords.
104 while (!BlockInfoRecords.empty()) {
105 BlockInfo &Info = BlockInfoRecords.back();
106 // Free blockinfo abbrev info.
107 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
109 Info.Abbrevs[i]->dropRef();
110 BlockInfoRecords.pop_back();
114 /// \brief Retrieve the current position in the stream, in bits.
115 uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit; }
117 //===--------------------------------------------------------------------===//
118 // Basic Primitives for emitting bits to the stream.
119 //===--------------------------------------------------------------------===//
121 void Emit(uint32_t Val, unsigned NumBits) {
122 assert(NumBits && NumBits <= 32 && "Invalid value size!");
123 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
124 CurValue |= Val << CurBit;
125 if (CurBit + NumBits < 32) {
130 // Add the current word.
134 CurValue = Val >> (32-CurBit);
137 CurBit = (CurBit+NumBits) & 31;
140 void Emit64(uint64_t Val, unsigned NumBits) {
142 Emit((uint32_t)Val, NumBits);
144 Emit((uint32_t)Val, 32);
145 Emit((uint32_t)(Val >> 32), NumBits-32);
157 void EmitVBR(uint32_t Val, unsigned NumBits) {
158 uint32_t Threshold = 1U << (NumBits-1);
160 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
161 while (Val >= Threshold) {
162 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
169 void EmitVBR64(uint64_t Val, unsigned NumBits) {
170 if ((uint32_t)Val == Val)
171 return EmitVBR((uint32_t)Val, NumBits);
173 uint64_t Threshold = 1U << (NumBits-1);
175 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
176 while (Val >= Threshold) {
177 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
178 (1 << (NumBits-1)), NumBits);
182 Emit((uint32_t)Val, NumBits);
185 /// EmitCode - Emit the specified code.
186 void EmitCode(unsigned Val) {
187 Emit(Val, CurCodeSize);
190 //===--------------------------------------------------------------------===//
191 // Block Manipulation
192 //===--------------------------------------------------------------------===//
194 /// getBlockInfo - If there is block info for the specified ID, return it,
195 /// otherwise return null.
196 BlockInfo *getBlockInfo(unsigned BlockID) {
197 // Common case, the most recent entry matches BlockID.
198 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
199 return &BlockInfoRecords.back();
201 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
203 if (BlockInfoRecords[i].BlockID == BlockID)
204 return &BlockInfoRecords[i];
208 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
210 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
211 EmitCode(bitc::ENTER_SUBBLOCK);
212 EmitVBR(BlockID, bitc::BlockIDWidth);
213 EmitVBR(CodeLen, bitc::CodeLenWidth);
216 unsigned BlockSizeWordIndex = GetWordIndex();
217 unsigned OldCodeSize = CurCodeSize;
219 // Emit a placeholder, which will be replaced when the block is popped.
220 Emit(0, bitc::BlockSizeWidth);
222 CurCodeSize = CodeLen;
224 // Push the outer block's abbrev set onto the stack, start out with an
226 BlockScope.push_back(Block(OldCodeSize, BlockSizeWordIndex));
227 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
229 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
230 // to the abbrev list.
231 if (BlockInfo *Info = getBlockInfo(BlockID)) {
232 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
234 CurAbbrevs.push_back(Info->Abbrevs[i]);
235 Info->Abbrevs[i]->addRef();
241 assert(!BlockScope.empty() && "Block scope imbalance!");
243 // Delete all abbrevs.
244 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
246 CurAbbrevs[i]->dropRef();
248 const Block &B = BlockScope.back();
251 // [END_BLOCK, <align4bytes>]
252 EmitCode(bitc::END_BLOCK);
255 // Compute the size of the block, in words, not counting the size field.
256 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
257 unsigned ByteNo = B.StartSizeWord*4;
259 // Update the block size field in the header of this sub-block.
260 BackpatchWord(ByteNo, SizeInWords);
262 // Restore the inner block's code size and abbrev table.
263 CurCodeSize = B.PrevCodeSize;
264 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
265 BlockScope.pop_back();
268 //===--------------------------------------------------------------------===//
270 //===--------------------------------------------------------------------===//
273 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
274 /// record. This is a no-op, since the abbrev specifies the literal to use.
275 template<typename uintty>
276 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
277 assert(Op.isLiteral() && "Not a literal");
278 // If the abbrev specifies the literal value to use, don't emit
280 assert(V == Op.getLiteralValue() &&
281 "Invalid abbrev for record!");
284 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
286 template<typename uintty>
287 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
288 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
290 // Encode the value as we are commanded.
291 switch (Op.getEncoding()) {
292 default: llvm_unreachable("Unknown encoding!");
293 case BitCodeAbbrevOp::Fixed:
294 if (Op.getEncodingData())
295 Emit((unsigned)V, (unsigned)Op.getEncodingData());
297 case BitCodeAbbrevOp::VBR:
298 if (Op.getEncodingData())
299 EmitVBR64(V, (unsigned)Op.getEncodingData());
301 case BitCodeAbbrevOp::Char6:
302 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
307 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
308 /// emission code. If BlobData is non-null, then it specifies an array of
309 /// data that should be emitted as part of the Blob or Array operand that is
310 /// known to exist at the end of the record.
311 template<typename uintty>
312 void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
314 const char *BlobData = Blob.data();
315 unsigned BlobLen = (unsigned) Blob.size();
316 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
317 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
318 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
322 unsigned RecordIdx = 0;
323 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
325 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
326 if (Op.isLiteral()) {
327 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
328 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
330 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
332 assert(i+2 == e && "array op not second to last?");
333 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
335 // If this record has blob data, emit it, otherwise we must have record
336 // entries to encode this way.
338 assert(RecordIdx == Vals.size() &&
339 "Blob data and record entries specified for array!");
340 // Emit a vbr6 to indicate the number of elements present.
341 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
344 for (unsigned i = 0; i != BlobLen; ++i)
345 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
347 // Know that blob data is consumed for assertion below.
350 // Emit a vbr6 to indicate the number of elements present.
351 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
354 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
355 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
357 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
358 // If this record has blob data, emit it, otherwise we must have record
359 // entries to encode this way.
361 // Emit a vbr6 to indicate the number of elements present.
363 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
364 assert(RecordIdx == Vals.size() &&
365 "Blob data and record entries specified for blob operand!");
367 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
370 // Flush to a 32-bit alignment boundary.
373 // Emit each field as a literal byte.
375 for (unsigned i = 0; i != BlobLen; ++i)
376 WriteByte((unsigned char)BlobData[i]);
378 // Know that blob data is consumed for assertion below.
381 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
382 assert(Vals[RecordIdx] < 256 && "Value too large to emit as blob");
383 WriteByte((unsigned char)Vals[RecordIdx]);
387 // Align end to 32-bits.
388 while (GetBufferOffset() & 3)
390 } else { // Single scalar field.
391 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
392 EmitAbbreviatedField(Op, Vals[RecordIdx]);
396 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
397 assert(BlobData == 0 &&
398 "Blob data specified for record that doesn't use it!");
403 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
404 /// we have one to compress the output.
405 template<typename uintty>
406 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
407 unsigned Abbrev = 0) {
409 // If we don't have an abbrev to use, emit this in its fully unabbreviated
411 EmitCode(bitc::UNABBREV_RECORD);
413 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
414 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
415 EmitVBR64(Vals[i], 6);
419 // Insert the code into Vals to treat it uniformly.
420 Vals.insert(Vals.begin(), Code);
422 EmitRecordWithAbbrev(Abbrev, Vals);
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 uintty>
429 void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
430 EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
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 uintty>
439 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
441 EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
443 template<typename uintty>
444 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
445 const char *BlobData, unsigned BlobLen) {
446 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
449 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
450 /// that end with an array.
451 template<typename uintty>
452 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
454 EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
456 template<typename uintty>
457 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
458 const char *ArrayData, unsigned ArrayLen) {
459 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
463 //===--------------------------------------------------------------------===//
465 //===--------------------------------------------------------------------===//
468 // Emit the abbreviation as a DEFINE_ABBREV record.
469 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
470 EmitCode(bitc::DEFINE_ABBREV);
471 EmitVBR(Abbv->getNumOperandInfos(), 5);
472 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
474 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
475 Emit(Op.isLiteral(), 1);
476 if (Op.isLiteral()) {
477 EmitVBR64(Op.getLiteralValue(), 8);
479 Emit(Op.getEncoding(), 3);
480 if (Op.hasEncodingData())
481 EmitVBR64(Op.getEncodingData(), 5);
487 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
488 /// method takes ownership of the specified abbrev.
489 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
490 // Emit the abbreviation as a record.
492 CurAbbrevs.push_back(Abbv);
493 return static_cast<unsigned>(CurAbbrevs.size())-1 +
494 bitc::FIRST_APPLICATION_ABBREV;
497 //===--------------------------------------------------------------------===//
498 // BlockInfo Block Emission
499 //===--------------------------------------------------------------------===//
501 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
502 void EnterBlockInfoBlock(unsigned CodeWidth) {
503 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
504 BlockInfoCurBID = ~0U;
507 /// SwitchToBlockID - If we aren't already talking about the specified block
508 /// ID, emit a BLOCKINFO_CODE_SETBID record.
509 void SwitchToBlockID(unsigned BlockID) {
510 if (BlockInfoCurBID == BlockID) return;
511 SmallVector<unsigned, 2> V;
512 V.push_back(BlockID);
513 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
514 BlockInfoCurBID = BlockID;
517 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
518 if (BlockInfo *BI = getBlockInfo(BlockID))
521 // Otherwise, add a new record.
522 BlockInfoRecords.push_back(BlockInfo());
523 BlockInfoRecords.back().BlockID = BlockID;
524 return BlockInfoRecords.back();
529 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
531 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
532 SwitchToBlockID(BlockID);
535 // Add the abbrev to the specified block record.
536 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
537 Info.Abbrevs.push_back(Abbv);
539 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
544 } // End llvm namespace