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/Bitcode/BitCodes.h"
23 class BitstreamWriter {
24 std::vector<unsigned char> &Out;
26 /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
29 /// CurValue - The current value. Only bits < CurBit are valid.
32 /// CurCodeSize - This is the declared size of code values used for the
33 /// current block, in bits.
36 /// BlockInfoCurBID - When emitting a BLOCKINFO_BLOCK, this is the currently
37 /// selected BLOCK ID.
38 unsigned BlockInfoCurBID;
40 /// CurAbbrevs - Abbrevs installed at in this block.
41 std::vector<BitCodeAbbrev*> CurAbbrevs;
44 unsigned PrevCodeSize;
45 unsigned StartSizeWord;
46 std::vector<BitCodeAbbrev*> PrevAbbrevs;
47 Block(unsigned PCS, unsigned SSW) : PrevCodeSize(PCS), StartSizeWord(SSW) {}
50 /// BlockScope - This tracks the current blocks that we have entered.
51 std::vector<Block> BlockScope;
53 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
54 /// These describe abbreviations that all blocks of the specified ID inherit.
57 std::vector<BitCodeAbbrev*> Abbrevs;
59 std::vector<BlockInfo> BlockInfoRecords;
62 explicit BitstreamWriter(std::vector<unsigned char> &O)
63 : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
66 assert(CurBit == 0 && "Unflused data remaining");
67 assert(BlockScope.empty() && CurAbbrevs.empty() && "Block imbalance");
69 // Free the BlockInfoRecords.
70 while (!BlockInfoRecords.empty()) {
71 BlockInfo &Info = BlockInfoRecords.back();
72 // Free blockinfo abbrev info.
73 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
75 Info.Abbrevs[i]->dropRef();
76 BlockInfoRecords.pop_back();
80 std::vector<unsigned char> &getBuffer() { return Out; }
82 //===--------------------------------------------------------------------===//
83 // Basic Primitives for emitting bits to the stream.
84 //===--------------------------------------------------------------------===//
86 void Emit(uint32_t Val, unsigned NumBits) {
87 assert(NumBits <= 32 && "Invalid value size!");
88 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
89 CurValue |= Val << CurBit;
90 if (CurBit + NumBits < 32) {
95 // Add the current word.
96 unsigned V = CurValue;
97 Out.push_back((unsigned char)(V >> 0));
98 Out.push_back((unsigned char)(V >> 8));
99 Out.push_back((unsigned char)(V >> 16));
100 Out.push_back((unsigned char)(V >> 24));
103 CurValue = Val >> (32-CurBit);
106 CurBit = (CurBit+NumBits) & 31;
109 void Emit64(uint64_t Val, unsigned NumBits) {
111 Emit((uint32_t)Val, NumBits);
113 Emit((uint32_t)Val, 32);
114 Emit((uint32_t)(Val >> 32), NumBits-32);
120 unsigned V = CurValue;
121 Out.push_back((unsigned char)(V >> 0));
122 Out.push_back((unsigned char)(V >> 8));
123 Out.push_back((unsigned char)(V >> 16));
124 Out.push_back((unsigned char)(V >> 24));
130 void EmitVBR(uint32_t Val, unsigned NumBits) {
131 uint32_t Threshold = 1U << (NumBits-1);
133 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
134 while (Val >= Threshold) {
135 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
142 void EmitVBR64(uint64_t Val, unsigned NumBits) {
143 if ((uint32_t)Val == Val)
144 return EmitVBR((uint32_t)Val, NumBits);
146 uint64_t Threshold = 1U << (NumBits-1);
148 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
149 while (Val >= Threshold) {
150 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
151 (1 << (NumBits-1)), NumBits);
155 Emit((uint32_t)Val, NumBits);
158 /// EmitCode - Emit the specified code.
159 void EmitCode(unsigned Val) {
160 Emit(Val, CurCodeSize);
163 // BackpatchWord - Backpatch a 32-bit word in the output with the specified
165 void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
166 Out[ByteNo++] = (unsigned char)(NewWord >> 0);
167 Out[ByteNo++] = (unsigned char)(NewWord >> 8);
168 Out[ByteNo++] = (unsigned char)(NewWord >> 16);
169 Out[ByteNo ] = (unsigned char)(NewWord >> 24);
172 //===--------------------------------------------------------------------===//
173 // Block Manipulation
174 //===--------------------------------------------------------------------===//
176 /// getBlockInfo - If there is block info for the specified ID, return it,
177 /// otherwise return null.
178 BlockInfo *getBlockInfo(unsigned BlockID) {
179 // Common case, the most recent entry matches BlockID.
180 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
181 return &BlockInfoRecords.back();
183 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
185 if (BlockInfoRecords[i].BlockID == BlockID)
186 return &BlockInfoRecords[i];
190 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
192 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
193 EmitCode(bitc::ENTER_SUBBLOCK);
194 EmitVBR(BlockID, bitc::BlockIDWidth);
195 EmitVBR(CodeLen, bitc::CodeLenWidth);
198 unsigned BlockSizeWordLoc = static_cast<unsigned>(Out.size());
199 unsigned OldCodeSize = CurCodeSize;
201 // Emit a placeholder, which will be replaced when the block is popped.
202 Emit(0, bitc::BlockSizeWidth);
204 CurCodeSize = CodeLen;
206 // Push the outer block's abbrev set onto the stack, start out with an
208 BlockScope.push_back(Block(OldCodeSize, BlockSizeWordLoc/4));
209 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
211 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
212 // to the abbrev list.
213 if (BlockInfo *Info = getBlockInfo(BlockID)) {
214 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
216 CurAbbrevs.push_back(Info->Abbrevs[i]);
217 Info->Abbrevs[i]->addRef();
223 assert(!BlockScope.empty() && "Block scope imbalance!");
225 // Delete all abbrevs.
226 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
228 CurAbbrevs[i]->dropRef();
230 const Block &B = BlockScope.back();
233 // [END_BLOCK, <align4bytes>]
234 EmitCode(bitc::END_BLOCK);
237 // Compute the size of the block, in words, not counting the size field.
238 unsigned SizeInWords= static_cast<unsigned>(Out.size())/4-B.StartSizeWord-1;
239 unsigned ByteNo = B.StartSizeWord*4;
241 // Update the block size field in the header of this sub-block.
242 BackpatchWord(ByteNo, SizeInWords);
244 // Restore the inner block's code size and abbrev table.
245 CurCodeSize = B.PrevCodeSize;
246 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
247 BlockScope.pop_back();
250 //===--------------------------------------------------------------------===//
252 //===--------------------------------------------------------------------===//
255 /// EmitAbbreviatedLiteral - Emit a literal value according to its abbrev
256 /// record. This is a no-op, since the abbrev specifies the literal to use.
257 template<typename uintty>
258 void EmitAbbreviatedLiteral(const BitCodeAbbrevOp &Op, uintty V) {
259 assert(Op.isLiteral() && "Not a literal");
260 // If the abbrev specifies the literal value to use, don't emit
262 assert(V == Op.getLiteralValue() &&
263 "Invalid abbrev for record!");
266 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
268 template<typename uintty>
269 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
270 assert(!Op.isLiteral() && "Literals should use EmitAbbreviatedLiteral!");
272 // Encode the value as we are commanded.
273 switch (Op.getEncoding()) {
274 default: assert(0 && "Unknown encoding!");
275 case BitCodeAbbrevOp::Fixed:
276 Emit((unsigned)V, (unsigned)Op.getEncodingData());
278 case BitCodeAbbrevOp::VBR:
279 EmitVBR64(V, (unsigned)Op.getEncodingData());
281 case BitCodeAbbrevOp::Char6:
282 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
289 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
290 /// we have one to compress the output.
291 template<typename uintty>
292 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
293 unsigned Abbrev = 0) {
295 // If we don't have an abbrev to use, emit this in its fully unabbreviated
297 EmitCode(bitc::UNABBREV_RECORD);
299 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
300 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
301 EmitVBR64(Vals[i], 6);
305 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
306 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
307 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
311 // Insert the code into Vals to treat it uniformly.
312 Vals.insert(Vals.begin(), Code);
314 unsigned RecordIdx = 0;
315 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
317 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
318 if (Op.isLiteral()) {
319 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
320 EmitAbbreviatedLiteral(Op, Vals[RecordIdx]);
322 } else if (Op.getEncoding() != BitCodeAbbrevOp::Array) {
323 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
324 EmitAbbreviatedField(Op, Vals[RecordIdx]);
328 assert(i+2 == e && "array op not second to last?");
329 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
331 // Emit a vbr6 to indicate the number of elements present.
332 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
335 for (; RecordIdx != Vals.size(); ++RecordIdx)
336 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
339 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
342 //===--------------------------------------------------------------------===//
344 //===--------------------------------------------------------------------===//
347 // Emit the abbreviation as a DEFINE_ABBREV record.
348 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
349 EmitCode(bitc::DEFINE_ABBREV);
350 EmitVBR(Abbv->getNumOperandInfos(), 5);
351 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
353 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
354 Emit(Op.isLiteral(), 1);
355 if (Op.isLiteral()) {
356 EmitVBR64(Op.getLiteralValue(), 8);
358 Emit(Op.getEncoding(), 3);
359 if (Op.hasEncodingData())
360 EmitVBR64(Op.getEncodingData(), 5);
366 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
367 /// method takes ownership of the specified abbrev.
368 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
369 // Emit the abbreviation as a record.
371 CurAbbrevs.push_back(Abbv);
372 return static_cast<unsigned>(CurAbbrevs.size())-1 +
373 bitc::FIRST_APPLICATION_ABBREV;
376 //===--------------------------------------------------------------------===//
377 // BlockInfo Block Emission
378 //===--------------------------------------------------------------------===//
380 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
381 void EnterBlockInfoBlock(unsigned CodeWidth) {
382 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
383 BlockInfoCurBID = -1U;
386 /// SwitchToBlockID - If we aren't already talking about the specified block
387 /// ID, emit a BLOCKINFO_CODE_SETBID record.
388 void SwitchToBlockID(unsigned BlockID) {
389 if (BlockInfoCurBID == BlockID) return;
390 SmallVector<unsigned, 2> V;
391 V.push_back(BlockID);
392 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
393 BlockInfoCurBID = BlockID;
396 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
397 if (BlockInfo *BI = getBlockInfo(BlockID))
400 // Otherwise, add a new record.
401 BlockInfoRecords.push_back(BlockInfo());
402 BlockInfoRecords.back().BlockID = BlockID;
403 return BlockInfoRecords.back();
408 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
410 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
411 SwitchToBlockID(BlockID);
414 // Add the abbrev to the specified block record.
415 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
416 Info.Abbrevs.push_back(Abbv);
418 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
423 } // End llvm namespace