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<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 assert(NumBits <= 32 && "Too many bits to emit!");
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((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
170 void EmitVBR64(uint64_t Val, unsigned NumBits) {
171 assert(NumBits <= 32 && "Too many bits to emit!");
172 if ((uint32_t)Val == Val)
173 return EmitVBR((uint32_t)Val, NumBits);
175 uint32_t Threshold = 1U << (NumBits-1);
177 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
178 while (Val >= Threshold) {
179 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
180 (1 << (NumBits-1)), NumBits);
184 Emit((uint32_t)Val, NumBits);
187 /// EmitCode - Emit the specified code.
188 void EmitCode(unsigned Val) {
189 Emit(Val, CurCodeSize);
192 //===--------------------------------------------------------------------===//
193 // Block Manipulation
194 //===--------------------------------------------------------------------===//
196 /// getBlockInfo - If there is block info for the specified ID, return it,
197 /// otherwise return null.
198 BlockInfo *getBlockInfo(unsigned BlockID) {
199 // Common case, the most recent entry matches BlockID.
200 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
201 return &BlockInfoRecords.back();
203 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
205 if (BlockInfoRecords[i].BlockID == BlockID)
206 return &BlockInfoRecords[i];
210 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
212 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
213 EmitCode(bitc::ENTER_SUBBLOCK);
214 EmitVBR(BlockID, bitc::BlockIDWidth);
215 EmitVBR(CodeLen, bitc::CodeLenWidth);
218 unsigned BlockSizeWordIndex = GetWordIndex();
219 unsigned OldCodeSize = CurCodeSize;
221 // Emit a placeholder, which will be replaced when the block is popped.
222 Emit(0, bitc::BlockSizeWidth);
224 CurCodeSize = CodeLen;
226 // Push the outer block's abbrev set onto the stack, start out with an
228 BlockScope.push_back(Block(OldCodeSize, BlockSizeWordIndex));
229 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
231 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
232 // to the abbrev list.
233 if (BlockInfo *Info = getBlockInfo(BlockID)) {
234 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
236 CurAbbrevs.push_back(Info->Abbrevs[i]);
237 Info->Abbrevs[i]->addRef();
243 assert(!BlockScope.empty() && "Block scope imbalance!");
245 // Delete all abbrevs.
246 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
248 CurAbbrevs[i]->dropRef();
250 const Block &B = BlockScope.back();
253 // [END_BLOCK, <align4bytes>]
254 EmitCode(bitc::END_BLOCK);
257 // Compute the size of the block, in words, not counting the size field.
258 unsigned SizeInWords = GetWordIndex() - B.StartSizeWord - 1;
259 unsigned ByteNo = B.StartSizeWord*4;
261 // Update the block size field in the header of this sub-block.
262 BackpatchWord(ByteNo, SizeInWords);
264 // Restore the inner block's code size and abbrev table.
265 CurCodeSize = B.PrevCodeSize;
266 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
267 BlockScope.pop_back();
270 //===--------------------------------------------------------------------===//
272 //===--------------------------------------------------------------------===//
275 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
276 /// record. This is a no-op, since the abbrev specifies the literal to use.
277 template<typename uintty>
278 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
279 assert(Op.isLiteral() && "Not a literal");
280 // If the abbrev specifies the literal value to use, don't emit
282 assert(V == Op.getLiteralValue() &&
283 "Invalid abbrev for record!");
286 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
288 template<typename uintty>
289 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
290 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
292 // Encode the value as we are commanded.
293 switch (Op.getEncoding()) {
294 default: llvm_unreachable("Unknown encoding!");
295 case BitCodeAbbrevOp::Fixed:
296 if (Op.getEncodingData())
297 Emit((unsigned)V, (unsigned)Op.getEncodingData());
299 case BitCodeAbbrevOp::VBR:
300 if (Op.getEncodingData())
301 EmitVBR64(V, (unsigned)Op.getEncodingData());
303 case BitCodeAbbrevOp::Char6:
304 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
309 /// EmitRecordWithAbbrevImpl - This is the core implementation of the record
310 /// emission code. If BlobData is non-null, then it specifies an array of
311 /// data that should be emitted as part of the Blob or Array operand that is
312 /// known to exist at the end of the record.
313 template<typename uintty>
314 void EmitRecordWithAbbrevImpl(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
316 const char *BlobData = Blob.data();
317 unsigned BlobLen = (unsigned) Blob.size();
318 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
319 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
320 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
324 unsigned RecordIdx = 0;
325 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
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 == 0 &&
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 uintty>
409 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
410 unsigned Abbrev = 0) {
412 // If we don't have an abbrev to use, emit this in its fully unabbreviated
414 EmitCode(bitc::UNABBREV_RECORD);
416 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
417 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
418 EmitVBR64(Vals[i], 6);
422 // Insert the code into Vals to treat it uniformly.
423 Vals.insert(Vals.begin(), Code);
425 EmitRecordWithAbbrev(Abbrev, Vals);
428 /// EmitRecordWithAbbrev - Emit a record with the specified abbreviation.
429 /// Unlike EmitRecord, the code for the record should be included in Vals as
431 template<typename uintty>
432 void EmitRecordWithAbbrev(unsigned Abbrev, SmallVectorImpl<uintty> &Vals) {
433 EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef());
436 /// EmitRecordWithBlob - Emit the specified record to the stream, using an
437 /// abbrev that includes a blob at the end. The blob data to emit is
438 /// specified by the pointer and length specified at the end. In contrast to
439 /// EmitRecord, this routine expects that the first entry in Vals is the code
441 template<typename uintty>
442 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
444 EmitRecordWithAbbrevImpl(Abbrev, Vals, Blob);
446 template<typename uintty>
447 void EmitRecordWithBlob(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
448 const char *BlobData, unsigned BlobLen) {
449 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(BlobData, BlobLen));
452 /// EmitRecordWithArray - Just like EmitRecordWithBlob, works with records
453 /// that end with an array.
454 template<typename uintty>
455 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
457 EmitRecordWithAbbrevImpl(Abbrev, Vals, Array);
459 template<typename uintty>
460 void EmitRecordWithArray(unsigned Abbrev, SmallVectorImpl<uintty> &Vals,
461 const char *ArrayData, unsigned ArrayLen) {
462 return EmitRecordWithAbbrevImpl(Abbrev, Vals, StringRef(ArrayData,
466 //===--------------------------------------------------------------------===//
468 //===--------------------------------------------------------------------===//
471 // Emit the abbreviation as a DEFINE_ABBREV record.
472 void EncodeAbbrev(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(BitCodeAbbrev *Abbv) {
493 // Emit the abbreviation as a record.
495 CurAbbrevs.push_back(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(unsigned CodeWidth) {
506 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
507 BlockInfoCurBID = ~0U;
510 /// SwitchToBlockID - If we aren't already talking about the specified block
511 /// ID, emit a BLOCKINFO_CODE_SETBID record.
512 void SwitchToBlockID(unsigned BlockID) {
513 if (BlockInfoCurBID == BlockID) return;
514 SmallVector<unsigned, 2> V;
515 V.push_back(BlockID);
516 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
517 BlockInfoCurBID = BlockID;
520 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
521 if (BlockInfo *BI = getBlockInfo(BlockID))
524 // Otherwise, add a new record.
525 BlockInfoRecords.push_back(BlockInfo());
526 BlockInfoRecords.back().BlockID = BlockID;
527 return BlockInfoRecords.back();
532 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
534 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
535 SwitchToBlockID(BlockID);
538 // Add the abbrev to the specified block record.
539 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
540 Info.Abbrevs.push_back(Abbv);
542 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
547 } // End llvm namespace