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();
79 //===--------------------------------------------------------------------===//
80 // Basic Primitives for emitting bits to the stream.
81 //===--------------------------------------------------------------------===//
83 void Emit(uint32_t Val, unsigned NumBits) {
84 assert(NumBits <= 32 && "Invalid value size!");
85 assert((Val & ~(~0U >> (32-NumBits))) == 0 && "High bits set!");
86 CurValue |= Val << CurBit;
87 if (CurBit + NumBits < 32) {
92 // Add the current word.
93 unsigned V = CurValue;
94 Out.push_back((unsigned char)(V >> 0));
95 Out.push_back((unsigned char)(V >> 8));
96 Out.push_back((unsigned char)(V >> 16));
97 Out.push_back((unsigned char)(V >> 24));
100 CurValue = Val >> (32-CurBit);
103 CurBit = (CurBit+NumBits) & 31;
106 void Emit64(uint64_t Val, unsigned NumBits) {
108 Emit((uint32_t)Val, NumBits);
110 Emit((uint32_t)Val, 32);
111 Emit((uint32_t)(Val >> 32), NumBits-32);
117 unsigned V = CurValue;
118 Out.push_back((unsigned char)(V >> 0));
119 Out.push_back((unsigned char)(V >> 8));
120 Out.push_back((unsigned char)(V >> 16));
121 Out.push_back((unsigned char)(V >> 24));
127 void EmitVBR(uint32_t Val, unsigned NumBits) {
128 uint32_t Threshold = 1U << (NumBits-1);
130 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
131 while (Val >= Threshold) {
132 Emit((Val & ((1 << (NumBits-1))-1)) | (1 << (NumBits-1)), NumBits);
139 void EmitVBR64(uint64_t Val, unsigned NumBits) {
140 if ((uint32_t)Val == Val)
141 return EmitVBR((uint32_t)Val, NumBits);
143 uint64_t Threshold = 1U << (NumBits-1);
145 // Emit the bits with VBR encoding, NumBits-1 bits at a time.
146 while (Val >= Threshold) {
147 Emit(((uint32_t)Val & ((1 << (NumBits-1))-1)) |
148 (1 << (NumBits-1)), NumBits);
152 Emit((uint32_t)Val, NumBits);
155 /// EmitCode - Emit the specified code.
156 void EmitCode(unsigned Val) {
157 Emit(Val, CurCodeSize);
160 //===--------------------------------------------------------------------===//
161 // Block Manipulation
162 //===--------------------------------------------------------------------===//
164 /// getBlockInfo - If there is block info for the specified ID, return it,
165 /// otherwise return null.
166 BlockInfo *getBlockInfo(unsigned BlockID) {
167 // Common case, the most recent entry matches BlockID.
168 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
169 return &BlockInfoRecords.back();
171 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
173 if (BlockInfoRecords[i].BlockID == BlockID)
174 return &BlockInfoRecords[i];
178 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
180 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
181 EmitCode(bitc::ENTER_SUBBLOCK);
182 EmitVBR(BlockID, bitc::BlockIDWidth);
183 EmitVBR(CodeLen, bitc::CodeLenWidth);
186 unsigned BlockSizeWordLoc = static_cast<unsigned>(Out.size());
187 unsigned OldCodeSize = CurCodeSize;
189 // Emit a placeholder, which will be replaced when the block is popped.
190 Emit(0, bitc::BlockSizeWidth);
192 CurCodeSize = CodeLen;
194 // Push the outer block's abbrev set onto the stack, start out with an
196 BlockScope.push_back(Block(OldCodeSize, BlockSizeWordLoc/4));
197 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
199 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
200 // to the abbrev list.
201 if (BlockInfo *Info = getBlockInfo(BlockID)) {
202 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
204 CurAbbrevs.push_back(Info->Abbrevs[i]);
205 Info->Abbrevs[i]->addRef();
211 assert(!BlockScope.empty() && "Block scope imbalance!");
213 // Delete all abbrevs.
214 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
216 CurAbbrevs[i]->dropRef();
218 const Block &B = BlockScope.back();
221 // [END_BLOCK, <align4bytes>]
222 EmitCode(bitc::END_BLOCK);
225 // Compute the size of the block, in words, not counting the size field.
226 unsigned SizeInWords= static_cast<unsigned>(Out.size())/4-B.StartSizeWord-1;
227 unsigned ByteNo = B.StartSizeWord*4;
229 // Update the block size field in the header of this sub-block.
230 Out[ByteNo++] = (unsigned char)(SizeInWords >> 0);
231 Out[ByteNo++] = (unsigned char)(SizeInWords >> 8);
232 Out[ByteNo++] = (unsigned char)(SizeInWords >> 16);
233 Out[ByteNo++] = (unsigned char)(SizeInWords >> 24);
235 // Restore the inner block's code size and abbrev table.
236 CurCodeSize = B.PrevCodeSize;
237 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
238 BlockScope.pop_back();
241 //===--------------------------------------------------------------------===//
243 //===--------------------------------------------------------------------===//
246 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
248 template<typename uintty>
249 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
250 if (Op.isLiteral()) {
251 // If the abbrev specifies the literal value to use, don't emit
253 assert(V == Op.getLiteralValue() &&
254 "Invalid abbrev for record!");
258 // Encode the value as we are commanded.
259 switch (Op.getEncoding()) {
260 default: assert(0 && "Unknown encoding!");
261 case BitCodeAbbrevOp::Fixed:
262 Emit((unsigned)V, (unsigned)Op.getEncodingData());
264 case BitCodeAbbrevOp::VBR:
265 EmitVBR64(V, (unsigned)Op.getEncodingData());
267 case BitCodeAbbrevOp::Char6:
268 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
274 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
275 /// we have one to compress the output.
276 template<typename uintty>
277 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
278 unsigned Abbrev = 0) {
280 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
281 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
282 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
286 // Insert the code into Vals to treat it uniformly.
287 Vals.insert(Vals.begin(), Code);
289 unsigned RecordIdx = 0;
290 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
292 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
293 if (Op.isLiteral() || Op.getEncoding() != BitCodeAbbrevOp::Array) {
294 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
295 EmitAbbreviatedField(Op, Vals[RecordIdx]);
299 assert(i+2 == e && "array op not second to last?");
300 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
302 // Emit a vbr6 to indicate the number of elements present.
303 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
306 for (; RecordIdx != Vals.size(); ++RecordIdx)
307 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
310 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
312 // If we don't have an abbrev to use, emit this in its fully unabbreviated
314 EmitCode(bitc::UNABBREV_RECORD);
316 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
317 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
318 EmitVBR64(Vals[i], 6);
322 //===--------------------------------------------------------------------===//
324 //===--------------------------------------------------------------------===//
327 // Emit the abbreviation as a DEFINE_ABBREV record.
328 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
329 EmitCode(bitc::DEFINE_ABBREV);
330 EmitVBR(Abbv->getNumOperandInfos(), 5);
331 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
333 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
334 Emit(Op.isLiteral(), 1);
335 if (Op.isLiteral()) {
336 EmitVBR64(Op.getLiteralValue(), 8);
338 Emit(Op.getEncoding(), 3);
339 if (Op.hasEncodingData())
340 EmitVBR64(Op.getEncodingData(), 5);
346 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
347 /// method takes ownership of the specified abbrev.
348 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
349 // Emit the abbreviation as a record.
351 CurAbbrevs.push_back(Abbv);
352 return static_cast<unsigned>(CurAbbrevs.size())-1 +
353 bitc::FIRST_APPLICATION_ABBREV;
356 //===--------------------------------------------------------------------===//
357 // BlockInfo Block Emission
358 //===--------------------------------------------------------------------===//
360 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
361 void EnterBlockInfoBlock(unsigned CodeWidth) {
362 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
363 BlockInfoCurBID = -1U;
366 /// SwitchToBlockID - If we aren't already talking about the specified block
367 /// ID, emit a BLOCKINFO_CODE_SETBID record.
368 void SwitchToBlockID(unsigned BlockID) {
369 if (BlockInfoCurBID == BlockID) return;
370 SmallVector<unsigned, 2> V;
371 V.push_back(BlockID);
372 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
373 BlockInfoCurBID = BlockID;
376 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
377 if (BlockInfo *BI = getBlockInfo(BlockID))
380 // Otherwise, add a new record.
381 BlockInfoRecords.push_back(BlockInfo());
382 BlockInfoRecords.back().BlockID = BlockID;
383 return BlockInfoRecords.back();
388 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
390 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
391 SwitchToBlockID(BlockID);
394 // Add the abbrev to the specified block record.
395 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
396 Info.Abbrevs.push_back(Abbv);
398 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
403 } // End llvm namespace