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/Bitcode/BitCodes.h"
24 class BitstreamWriter {
25 std::vector<unsigned char> &Out;
27 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
30 /// CurValue - The current value. Only bits < CurBit are valid.
33 /// CurCodeSize - This is the declared size of code values used for the
34 /// current block, in bits.
37 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
38 /// selected BLOCK ID.
39 unsigned BlockInfoCurBID;
41 /// CurAbbrevs - Abbrevs installed at in this block.
42 std::vector<BitCodeAbbrev*> CurAbbrevs;
45 unsigned PrevCodeSize;
46 unsigned StartSizeWord;
47 std::vector<BitCodeAbbrev*> PrevAbbrevs;
48 Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
51 /// BlockScope - This tracks the current blocks that we have entered.
52 std::vector<Block> BlockScope;
54 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
55 /// These describe abbreviations that all blocks of the specified ID inherit.
58 std::vector<BitCodeAbbrev*> Abbrevs;
60 std::vector<BlockInfo> BlockInfoRecords;
62 // BackpatchWord - Backpatch a 32-bit word in the output with the specified
64 void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
65 Out[ByteNo++] = (unsigned char)(NewWord >> 0);
66 Out[ByteNo++] = (unsigned char)(NewWord >> 8);
67 Out[ByteNo++] = (unsigned char)(NewWord >> 16);
68 Out[ByteNo ] = (unsigned char)(NewWord >> 24);
72 explicit BitstreamWriter(std::vector<unsigned char> &O)
73 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
76 assert(CurBit == 0 && "Unflused data remaining");
77 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
79 // Free the BlockInfoRecords.
80 while (!BlockInfoRecords.empty()) {
81 BlockInfo &Info = BlockInfoRecords.back();
82 // Free blockinfo abbrev info.
83 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
85 Info.Abbrevs[i]->dropRef();
86 BlockInfoRecords.pop_back();
90 /// \brief Retrieve the current position in the stream, in bits.
91 uint64_t GetCurrentBitNo() const { return Out.size() * 8 + CurBit; }
93 //===--------------------------------------------------------------------===//
94 // Basic Primitives for emitting bits to the stream.
95 //===--------------------------------------------------------------------===//
97 void Emit(uint32_t Val, unsigned NumBits) {
98 assert(NumBits && NumBits <= 32 && "Invalid value size!");
99 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
100 CurValue |= Val << CurBit;
101 if (CurBit + NumBits < 32) {
106 // Add the current word.
107 unsigned V = CurValue;
108 Out.push_back((unsigned char)(V >> 0));
109 Out.push_back((unsigned char)(V >> 8));
110 Out.push_back((unsigned char)(V >> 16));
111 Out.push_back((unsigned char)(V >> 24));
114 CurValue = Val >> (32-CurBit);
117 CurBit = (CurBit+NumBits) & 31;
120 void Emit64(uint64_t Val, unsigned NumBits) {
122 Emit((uint32_t)Val, NumBits);
124 Emit((uint32_t)Val, 32);
125 Emit((uint32_t)(Val >> 32), NumBits-32);
131 unsigned V = CurValue;
132 Out.push_back((unsigned char)(V >> 0));
133 Out.push_back((unsigned char)(V >> 8));
134 Out.push_back((unsigned char)(V >> 16));
135 Out.push_back((unsigned char)(V >> 24));
141 void EmitVBR(uint32_t Val, unsigned NumBits) {
142 uint32_t Threshold = 1U << (NumBits-1);
144 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
145 while (Val >= Threshold) {
146 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
153 void EmitVBR64(uint64_t Val, unsigned NumBits) {
154 if ((uint32_t)Val == Val)
155 return EmitVBR((uint32_t)Val, NumBits);
157 uint64_t Threshold = 1U << (NumBits-1);
159 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
160 while (Val >= Threshold) {
161 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
162 (1 << (NumBits-1)), NumBits);
166 Emit((uint32_t)Val, NumBits);
169 /// EmitCode - Emit the specified code.
170 void EmitCode(unsigned Val) {
171 Emit(Val, CurCodeSize);
174 //===--------------------------------------------------------------------===//
175 // Block Manipulation
176 //===--------------------------------------------------------------------===//
178 /// getBlockInfo - If there is block info for the specified ID, return it,
179 /// otherwise return null.
180 BlockInfo *getBlockInfo(unsigned BlockID) {
181 // Common case, the most recent entry matches BlockID.
182 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
183 return &BlockInfoRecords.back();
185 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
187 if (BlockInfoRecords[i].BlockID == BlockID)
188 return &BlockInfoRecords[i];
192 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
194 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
195 EmitCode(bitc::ENTER_SUBBLOCK);
196 EmitVBR(BlockID, bitc::BlockIDWidth);
197 EmitVBR(CodeLen, bitc::CodeLenWidth);
200 unsigned BlockSizeWordLoc = static_cast<unsigned>(Out.size());
201 unsigned OldCodeSize = CurCodeSize;
203 // Emit a placeholder, which will be replaced when the block is popped.
204 Emit(0, bitc::BlockSizeWidth);
206 CurCodeSize = CodeLen;
208 // Push the outer block's abbrev set onto the stack, start out with an
210 BlockScope.push_back(Block(OldCodeSize, BlockSizeWordLoc/4));
211 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
213 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
214 // to the abbrev list.
215 if (BlockInfo *Info = getBlockInfo(BlockID)) {
216 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
218 CurAbbrevs.push_back(Info->Abbrevs[i]);
219 Info->Abbrevs[i]->addRef();
225 assert(!BlockScope.empty() && "Block scope imbalance!");
227 // Delete all abbrevs.
228 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
230 CurAbbrevs[i]->dropRef();
232 const Block &B = BlockScope.back();
235 // [END_BLOCK, <align4bytes>]
236 EmitCode(bitc::END_BLOCK);
239 // Compute the size of the block, in words, not counting the size field.
240 unsigned SizeInWords= static_cast<unsigned>(Out.size())/4-B.StartSizeWord-1;
241 unsigned ByteNo = B.StartSizeWord*4;
243 // Update the block size field in the header of this sub-block.
244 BackpatchWord(ByteNo, SizeInWords);
246 // Restore the inner block's code size and abbrev table.
247 CurCodeSize = B.PrevCodeSize;
248 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
249 BlockScope.pop_back();
252 //===--------------------------------------------------------------------===//
254 //===--------------------------------------------------------------------===//
257 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
258 /// record. This is a no-op, since the abbrev specifies the literal to use.
259 template<typename uintty>
260 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
261 assert(Op.isLiteral() && "Not a literal");
262 // If the abbrev specifies the literal value to use, don't emit
264 assert(V == Op.getLiteralValue() &&
265 "Invalid abbrev for record!");
268 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
270 template<typename uintty>
271 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
272 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
274 // Encode the value as we are commanded.
275 switch (Op.getEncoding()) {
276 default: llvm_unreachable("Unknown encoding!");
277 case BitCodeAbbrevOp::Fixed:
278 if (Op.getEncodingData())
279 Emit((unsigned)V, (unsigned)Op.getEncodingData());
281 case BitCodeAbbrevOp::VBR:
282 if (Op.getEncodingData())
283 EmitVBR64(V, (unsigned)Op.getEncodingData());
285 case BitCodeAbbrevOp::Char6:
286 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
291 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
292 /// emission code. If BlobData is non-null, then it specifies an array of
293 /// data that should be emitted as part of the Blob or Array operand that is
294 /// known to exist at the end of the record.
295 template<typename uintty>
296 void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
298 const char *BlobData = Blob.data();
299 unsigned BlobLen = (unsigned) Blob.size();
300 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
301 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
302 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
306 unsigned RecordIdx = 0;
307 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
309 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
310 if (Op.isLiteral()) {
311 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
312 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
314 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
316 assert(i+2 == e && "array op not second to last?");
317 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
319 // If this record has blob data, emit it, otherwise we must have record
320 // entries to encode this way.
322 assert(RecordIdx == Vals.size() &&
323 "Blob data and record entries specified for array!");
324 // Emit a vbr6 to indicate the number of elements present.
325 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
328 for (unsigned i = 0; i != BlobLen; ++i)
329 EmitAbbreviatedField(EltEnc, (unsigned char)BlobData[i]);
331 // Know that blob data is consumed for assertion below.
334 // Emit a vbr6 to indicate the number of elements present.
335 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
338 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx)
339 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
341 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
342 // If this record has blob data, emit it, otherwise we must have record
343 // entries to encode this way.
345 // Emit a vbr6 to indicate the number of elements present.
347 EmitVBR(static_cast<uint32_t>(BlobLen), 6);
348 assert(RecordIdx == Vals.size() &&
349 "Blob data and record entries specified for blob operand!");
351 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
354 // Flush to a 32-bit alignment boundary.
356 assert((Out.size() & 3) == 0 && "Not 32-bit aligned");
358 // Emit each field as a literal byte.
360 for (unsigned i = 0; i != BlobLen; ++i)
361 Out.push_back((unsigned char)BlobData[i]);
363 // Know that blob data is consumed for assertion below.
366 for (unsigned e = Vals.size(); RecordIdx != e; ++RecordIdx) {
367 assert(Vals[RecordIdx] < 256 && "Value too large to emit as blob");
368 Out.push_back((unsigned char)Vals[RecordIdx]);
371 // Align end to 32-bits.
372 while (Out.size() & 3)
375 } else { // Single scalar field.
376 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
377 EmitAbbreviatedField(Op, Vals[RecordIdx]);
381 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
382 assert(BlobData == 0 &&
383 "Blob data specified for record that doesn't use it!");
388 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
389 /// we have one to compress the output.
390 template<typename uintty>
391 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
392 unsigned Abbrev = 0) {
394 // If we don't have an abbrev to use, emit this in its fully unabbreviated
396 EmitCode(bitc::UNABBREV_RECORD);
398 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
399 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
400 EmitVBR64(Vals[i], 6);
404 // Insert the code into Vals to treat it uniformly.
405 Vals.insert(Vals.begin(), Code);
407 EmitRecordWithAbbrev(Abbrev, Vals);
410 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
411 /// Unlike EmitRecord, the code for the record should be included in Vals as
413 template<typename uintty>
414 void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
415 EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
418 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
419 /// abbrev that includes a blob at the end. The blob data to emit is
420 /// specified by the pointer and length specified at the end. In contrast to
421 /// EmitRecord, this routine expects that the first entry in Vals is the code
423 template<typename uintty>
424 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
426 EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
428 template<typename uintty>
429 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
430 const char *BlobData, unsigned BlobLen) {
431 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
434 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
435 /// that end with an array.
436 template<typename uintty>
437 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
439 EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
441 template<typename uintty>
442 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
443 const char *ArrayData, unsigned ArrayLen) {
444 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
448 //===--------------------------------------------------------------------===//
450 //===--------------------------------------------------------------------===//
453 // Emit the abbreviation as a DEFINE_ABBREV record.
454 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
455 EmitCode(bitc::DEFINE_ABBREV);
456 EmitVBR(Abbv->getNumOperandInfos(), 5);
457 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
459 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
460 Emit(Op.isLiteral(), 1);
461 if (Op.isLiteral()) {
462 EmitVBR64(Op.getLiteralValue(), 8);
464 Emit(Op.getEncoding(), 3);
465 if (Op.hasEncodingData())
466 EmitVBR64(Op.getEncodingData(), 5);
472 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
473 /// method takes ownership of the specified abbrev.
474 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
475 // Emit the abbreviation as a record.
477 CurAbbrevs.push_back(Abbv);
478 return static_cast<unsigned>(CurAbbrevs.size())-1 +
479 bitc::FIRST_APPLICATION_ABBREV;
482 //===--------------------------------------------------------------------===//
483 // BlockInfo Block Emission
484 //===--------------------------------------------------------------------===//
486 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
487 void EnterBlockInfoBlock(unsigned CodeWidth) {
488 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
489 BlockInfoCurBID = -1U;
492 /// SwitchToBlockID - If we aren't already talking about the specified block
493 /// ID, emit a BLOCKINFO_CODE_SETBID record.
494 void SwitchToBlockID(unsigned BlockID) {
495 if (BlockInfoCurBID == BlockID) return;
496 SmallVector<unsigned, 2> V;
497 V.push_back(BlockID);
498 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
499 BlockInfoCurBID = BlockID;
502 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
503 if (BlockInfo *BI = getBlockInfo(BlockID))
506 // Otherwise, add a new record.
507 BlockInfoRecords.push_back(BlockInfo());
508 BlockInfoRecords.back().BlockID = BlockID;
509 return BlockInfoRecords.back();
514 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
516 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
517 SwitchToBlockID(BlockID);
520 // Add the abbrev to the specified block record.
521 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
522 Info.Abbrevs.push_back(Abbv);
524 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
529 } // End llvm namespace