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 // BackpatchWord - Backpatch a 32-bit word in the output with the specified
162 void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
163 Out[ByteNo++] = (unsigned char)(NewWord >> 0);
164 Out[ByteNo++] = (unsigned char)(NewWord >> 8);
165 Out[ByteNo++] = (unsigned char)(NewWord >> 16);
166 Out[ByteNo ] = (unsigned char)(NewWord >> 24);
169 //===--------------------------------------------------------------------===//
170 // Block Manipulation
171 //===--------------------------------------------------------------------===//
173 /// getBlockInfo - If there is block info for the specified ID, return it,
174 /// otherwise return null.
175 BlockInfo *getBlockInfo(unsigned BlockID) {
176 // Common case, the most recent entry matches BlockID.
177 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
178 return &BlockInfoRecords.back();
180 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
182 if (BlockInfoRecords[i].BlockID == BlockID)
183 return &BlockInfoRecords[i];
187 void EnterSubblock(unsigned BlockID, unsigned CodeLen) {
189 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
190 EmitCode(bitc::ENTER_SUBBLOCK);
191 EmitVBR(BlockID, bitc::BlockIDWidth);
192 EmitVBR(CodeLen, bitc::CodeLenWidth);
195 unsigned BlockSizeWordLoc = static_cast<unsigned>(Out.size());
196 unsigned OldCodeSize = CurCodeSize;
198 // Emit a placeholder, which will be replaced when the block is popped.
199 Emit(0, bitc::BlockSizeWidth);
201 CurCodeSize = CodeLen;
203 // Push the outer block's abbrev set onto the stack, start out with an
205 BlockScope.push_back(Block(OldCodeSize, BlockSizeWordLoc/4));
206 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
208 // If there is a blockinfo for this BlockID, add all the predefined abbrevs
209 // to the abbrev list.
210 if (BlockInfo *Info = getBlockInfo(BlockID)) {
211 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
213 CurAbbrevs.push_back(Info->Abbrevs[i]);
214 Info->Abbrevs[i]->addRef();
220 assert(!BlockScope.empty() && "Block scope imbalance!");
222 // Delete all abbrevs.
223 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
225 CurAbbrevs[i]->dropRef();
227 const Block &B = BlockScope.back();
230 // [END_BLOCK, <align4bytes>]
231 EmitCode(bitc::END_BLOCK);
234 // Compute the size of the block, in words, not counting the size field.
235 unsigned SizeInWords= static_cast<unsigned>(Out.size())/4-B.StartSizeWord-1;
236 unsigned ByteNo = B.StartSizeWord*4;
238 // Update the block size field in the header of this sub-block.
239 BackpatchWord(ByteNo, SizeInWords);
241 // Restore the inner block's code size and abbrev table.
242 CurCodeSize = B.PrevCodeSize;
243 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
244 BlockScope.pop_back();
247 //===--------------------------------------------------------------------===//
249 //===--------------------------------------------------------------------===//
252 /// EmitAbbreviatedField - Emit a single scalar field value with the specified
254 template<typename uintty>
255 void EmitAbbreviatedField(const BitCodeAbbrevOp &Op, uintty V) {
256 if (Op.isLiteral()) {
257 // If the abbrev specifies the literal value to use, don't emit
259 assert(V == Op.getLiteralValue() &&
260 "Invalid abbrev for record!");
264 // Encode the value as we are commanded.
265 switch (Op.getEncoding()) {
266 default: assert(0 && "Unknown encoding!");
267 case BitCodeAbbrevOp::Fixed:
268 Emit((unsigned)V, (unsigned)Op.getEncodingData());
270 case BitCodeAbbrevOp::VBR:
271 EmitVBR64(V, (unsigned)Op.getEncodingData());
273 case BitCodeAbbrevOp::Char6:
274 Emit(BitCodeAbbrevOp::EncodeChar6((char)V), 6);
280 /// EmitRecord - Emit the specified record to the stream, using an abbrev if
281 /// we have one to compress the output.
282 template<typename uintty>
283 void EmitRecord(unsigned Code, SmallVectorImpl<uintty> &Vals,
284 unsigned Abbrev = 0) {
286 unsigned AbbrevNo = Abbrev-bitc::FIRST_APPLICATION_ABBREV;
287 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
288 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
292 // Insert the code into Vals to treat it uniformly.
293 Vals.insert(Vals.begin(), Code);
295 unsigned RecordIdx = 0;
296 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
298 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
299 if (Op.isLiteral() || Op.getEncoding() != BitCodeAbbrevOp::Array) {
300 assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
301 EmitAbbreviatedField(Op, Vals[RecordIdx]);
305 assert(i+2 == e && "array op not second to last?");
306 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
308 // Emit a vbr6 to indicate the number of elements present.
309 EmitVBR(static_cast<uint32_t>(Vals.size()-RecordIdx), 6);
312 for (; RecordIdx != Vals.size(); ++RecordIdx)
313 EmitAbbreviatedField(EltEnc, Vals[RecordIdx]);
316 assert(RecordIdx == Vals.size() && "Not all record operands emitted!");
318 // If we don't have an abbrev to use, emit this in its fully unabbreviated
320 EmitCode(bitc::UNABBREV_RECORD);
322 EmitVBR(static_cast<uint32_t>(Vals.size()), 6);
323 for (unsigned i = 0, e = static_cast<unsigned>(Vals.size()); i != e; ++i)
324 EmitVBR64(Vals[i], 6);
328 //===--------------------------------------------------------------------===//
330 //===--------------------------------------------------------------------===//
333 // Emit the abbreviation as a DEFINE_ABBREV record.
334 void EncodeAbbrev(BitCodeAbbrev *Abbv) {
335 EmitCode(bitc::DEFINE_ABBREV);
336 EmitVBR(Abbv->getNumOperandInfos(), 5);
337 for (unsigned i = 0, e = static_cast<unsigned>(Abbv->getNumOperandInfos());
339 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
340 Emit(Op.isLiteral(), 1);
341 if (Op.isLiteral()) {
342 EmitVBR64(Op.getLiteralValue(), 8);
344 Emit(Op.getEncoding(), 3);
345 if (Op.hasEncodingData())
346 EmitVBR64(Op.getEncodingData(), 5);
352 /// EmitAbbrev - This emits an abbreviation to the stream. Note that this
353 /// method takes ownership of the specified abbrev.
354 unsigned EmitAbbrev(BitCodeAbbrev *Abbv) {
355 // Emit the abbreviation as a record.
357 CurAbbrevs.push_back(Abbv);
358 return static_cast<unsigned>(CurAbbrevs.size())-1 +
359 bitc::FIRST_APPLICATION_ABBREV;
362 //===--------------------------------------------------------------------===//
363 // BlockInfo Block Emission
364 //===--------------------------------------------------------------------===//
366 /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
367 void EnterBlockInfoBlock(unsigned CodeWidth) {
368 EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
369 BlockInfoCurBID = -1U;
372 /// SwitchToBlockID - If we aren't already talking about the specified block
373 /// ID, emit a BLOCKINFO_CODE_SETBID record.
374 void SwitchToBlockID(unsigned BlockID) {
375 if (BlockInfoCurBID == BlockID) return;
376 SmallVector<unsigned, 2> V;
377 V.push_back(BlockID);
378 EmitRecord(bitc::BLOCKINFO_CODE_SETBID, V);
379 BlockInfoCurBID = BlockID;
382 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
383 if (BlockInfo *BI = getBlockInfo(BlockID))
386 // Otherwise, add a new record.
387 BlockInfoRecords.push_back(BlockInfo());
388 BlockInfoRecords.back().BlockID = BlockID;
389 return BlockInfoRecords.back();
394 /// EmitBlockInfoAbbrev - Emit a DEFINE_ABBREV record for the specified
396 unsigned EmitBlockInfoAbbrev(unsigned BlockID, BitCodeAbbrev *Abbv) {
397 SwitchToBlockID(BlockID);
400 // Add the abbrev to the specified block record.
401 BlockInfo &Info = getOrCreateBlockInfo(BlockID);
402 Info.Abbrevs.push_back(Abbv);
404 return Info.Abbrevs.size()-1+bitc::FIRST_APPLICATION_ABBREV;
409 } // End llvm namespace