1 //===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitstreamReader class. This class can be used to
11 // read an arbitrary bitstream, regardless of its contents.
13 //===----------------------------------------------------------------------===//
15 #ifndef BITSTREAM_READER_H
16 #define BITSTREAM_READER_H
18 #include "llvm/Bitcode/BitCodes.h"
23 class BitstreamReader {
24 const unsigned char *NextChar;
25 const unsigned char *LastChar;
27 /// CurWord - This is the current data we have pulled from the stream but have
28 /// not returned to the client.
31 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
32 /// is always from [0...31] inclusive.
33 unsigned BitsInCurWord;
35 // CurCodeSize - This is the declared size of code values used for the current
39 /// CurAbbrevs - Abbrevs installed at in this block.
40 std::vector<BitCodeAbbrev*> CurAbbrevs;
43 unsigned PrevCodeSize;
44 std::vector<BitCodeAbbrev*> PrevAbbrevs;
45 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
48 /// BlockScope - This tracks the codesize of parent blocks.
49 SmallVector<Block, 8> BlockScope;
51 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
52 /// These describe abbreviations that all blocks of the specified ID inherit.
55 std::vector<BitCodeAbbrev*> Abbrevs;
57 std::vector<BlockInfo> BlockInfoRecords;
59 /// FirstChar - This remembers the first byte of the stream.
60 const unsigned char *FirstChar;
63 NextChar = FirstChar = LastChar = 0;
69 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
73 void init(const unsigned char *Start, const unsigned char *End) {
74 NextChar = FirstChar = Start;
76 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
83 // Abbrevs could still exist if the stream was broken. If so, don't leak
85 for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
86 CurAbbrevs[i]->dropRef();
88 for (unsigned S = 0, e = BlockScope.size(); S != e; ++S) {
89 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
90 for (unsigned i = 0, e = Abbrevs.size(); i != e; ++i)
91 Abbrevs[i]->dropRef();
94 // Free the BlockInfoRecords.
95 while (!BlockInfoRecords.empty()) {
96 BlockInfo &Info = BlockInfoRecords.back();
97 // Free blockinfo abbrev info.
98 for (unsigned i = 0, e = Info.Abbrevs.size(); i != e; ++i)
99 Info.Abbrevs[i]->dropRef();
100 BlockInfoRecords.pop_back();
104 bool AtEndOfStream() const {
105 return NextChar == LastChar && BitsInCurWord == 0;
108 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
109 uint64_t GetCurrentBitNo() const {
110 return (NextChar-FirstChar)*8 + ((32-BitsInCurWord) & 31);
113 /// JumpToBit - Reset the stream to the specified bit number.
114 void JumpToBit(uint64_t BitNo) {
115 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
116 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
117 assert(ByteNo < (uintptr_t)(LastChar-FirstChar) && "Invalid location");
119 // Move the cursor to the right word.
120 NextChar = FirstChar+ByteNo;
123 // Skip over any bits that are already consumed.
130 /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
131 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
133 uint32_t Read(unsigned NumBits) {
134 // If the field is fully contained by CurWord, return it quickly.
135 if (BitsInCurWord >= NumBits) {
136 uint32_t R = CurWord & ((1U << NumBits)-1);
138 BitsInCurWord -= NumBits;
142 // If we run out of data, stop at the end of the stream.
143 if (LastChar == NextChar) {
149 unsigned R = CurWord;
151 // Read the next word from the stream.
152 CurWord = (NextChar[0] << 0) | (NextChar[1] << 8) |
153 (NextChar[2] << 16) | (NextChar[3] << 24);
156 // Extract NumBits-BitsInCurWord from what we just read.
157 unsigned BitsLeft = NumBits-BitsInCurWord;
159 // Be careful here, BitsLeft is in the range [1..32] inclusive.
160 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
162 // BitsLeft bits have just been used up from CurWord.
164 CurWord >>= BitsLeft;
167 BitsInCurWord = 32-BitsLeft;
171 uint64_t Read64(unsigned NumBits) {
172 if (NumBits <= 32) return Read(NumBits);
174 uint64_t V = Read(32);
175 return V | (uint64_t)Read(NumBits-32) << 32;
178 uint32_t ReadVBR(unsigned NumBits) {
179 uint32_t Piece = Read(NumBits);
180 if ((Piece & (1U << (NumBits-1))) == 0)
184 unsigned NextBit = 0;
186 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
188 if ((Piece & (1U << (NumBits-1))) == 0)
191 NextBit += NumBits-1;
192 Piece = Read(NumBits);
196 uint64_t ReadVBR64(unsigned NumBits) {
197 uint64_t Piece = Read(NumBits);
198 if ((Piece & (1U << (NumBits-1))) == 0)
202 unsigned NextBit = 0;
204 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
206 if ((Piece & (1U << (NumBits-1))) == 0)
209 NextBit += NumBits-1;
210 Piece = Read(NumBits);
220 unsigned ReadCode() {
221 return Read(CurCodeSize);
224 //===--------------------------------------------------------------------===//
225 // Block Manipulation
226 //===--------------------------------------------------------------------===//
229 /// getBlockInfo - If there is block info for the specified ID, return it,
230 /// otherwise return null.
231 BlockInfo *getBlockInfo(unsigned BlockID) {
232 // Common case, the most recent entry matches BlockID.
233 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
234 return &BlockInfoRecords.back();
236 for (unsigned i = 0, e = BlockInfoRecords.size(); i != e; ++i)
237 if (BlockInfoRecords[i].BlockID == BlockID)
238 return &BlockInfoRecords[i];
245 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
247 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
249 unsigned ReadSubBlockID() {
250 return ReadVBR(bitc::BlockIDWidth);
253 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
254 /// over the body of this block. If the block record is malformed, return
257 // Read and ignore the codelen value. Since we are skipping this block, we
258 // don't care what code widths are used inside of it.
259 ReadVBR(bitc::CodeLenWidth);
261 unsigned NumWords = Read(bitc::BlockSizeWidth);
263 // Check that the block wasn't partially defined, and that the offset isn't
265 if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
268 NextChar += NumWords*4;
272 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, read and enter
273 /// the block, returning the BlockID of the block we just entered.
274 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
275 // Save the current block's state on BlockScope.
276 BlockScope.push_back(Block(CurCodeSize));
277 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
279 // Add the abbrevs specific to this block to the CurAbbrevs list.
280 if (BlockInfo *Info = getBlockInfo(BlockID)) {
281 for (unsigned i = 0, e = Info->Abbrevs.size(); i != e; ++i) {
282 CurAbbrevs.push_back(Info->Abbrevs[i]);
283 CurAbbrevs.back()->addRef();
287 // Get the codesize of this block.
288 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
290 unsigned NumWords = Read(bitc::BlockSizeWidth);
291 if (NumWordsP) *NumWordsP = NumWords;
293 // Validate that this block is sane.
294 if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
300 bool ReadBlockEnd() {
301 if (BlockScope.empty()) return true;
304 // [END_BLOCK, <align4bytes>]
306 CurCodeSize = BlockScope.back().PrevCodeSize;
308 // Delete abbrevs from popped scope.
309 for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
310 CurAbbrevs[i]->dropRef();
312 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
313 BlockScope.pop_back();
317 //===--------------------------------------------------------------------===//
319 //===--------------------------------------------------------------------===//
322 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
323 SmallVectorImpl<uint64_t> &Vals) {
324 if (Op.isLiteral()) {
325 // If the abbrev specifies the literal value to use, use it.
326 Vals.push_back(Op.getLiteralValue());
328 // Decode the value as we are commanded.
329 switch (Op.getEncoding()) {
330 default: assert(0 && "Unknown encoding!");
331 case BitCodeAbbrevOp::Fixed:
332 Vals.push_back(Read((unsigned)Op.getEncodingData()));
334 case BitCodeAbbrevOp::VBR:
335 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
337 case BitCodeAbbrevOp::Char6:
338 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
344 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals) {
345 if (AbbrevID == bitc::UNABBREV_RECORD) {
346 unsigned Code = ReadVBR(6);
347 unsigned NumElts = ReadVBR(6);
348 for (unsigned i = 0; i != NumElts; ++i)
349 Vals.push_back(ReadVBR64(6));
353 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
354 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
355 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
357 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
358 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
359 if (Op.isLiteral() || Op.getEncoding() != BitCodeAbbrevOp::Array) {
360 ReadAbbreviatedField(Op, Vals);
362 // Array case. Read the number of elements as a vbr6.
363 unsigned NumElts = ReadVBR(6);
365 // Get the element encoding.
366 assert(i+2 == e && "array op not second to last?");
367 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
369 // Read all the elements.
370 for (; NumElts; --NumElts)
371 ReadAbbreviatedField(EltEnc, Vals);
375 unsigned Code = (unsigned)Vals[0];
376 Vals.erase(Vals.begin());
380 //===--------------------------------------------------------------------===//
382 //===--------------------------------------------------------------------===//
384 void ReadAbbrevRecord() {
385 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
386 unsigned NumOpInfo = ReadVBR(5);
387 for (unsigned i = 0; i != NumOpInfo; ++i) {
388 bool IsLiteral = Read(1);
390 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
394 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
395 if (BitCodeAbbrevOp::hasEncodingData(E))
396 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
398 Abbv->Add(BitCodeAbbrevOp(E));
400 CurAbbrevs.push_back(Abbv);
403 //===--------------------------------------------------------------------===//
404 // BlockInfo Block Reading
405 //===--------------------------------------------------------------------===//
408 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
409 if (BlockInfo *BI = getBlockInfo(BlockID))
412 // Otherwise, add a new record.
413 BlockInfoRecords.push_back(BlockInfo());
414 BlockInfoRecords.back().BlockID = BlockID;
415 return BlockInfoRecords.back();
420 bool ReadBlockInfoBlock() {
421 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
423 SmallVector<uint64_t, 64> Record;
424 BlockInfo *CurBlockInfo = 0;
426 // Read all the records for this module.
428 unsigned Code = ReadCode();
429 if (Code == bitc::END_BLOCK)
430 return ReadBlockEnd();
431 if (Code == bitc::ENTER_SUBBLOCK) {
433 if (SkipBlock()) return true;
437 // Read abbrev records, associate them with CurBID.
438 if (Code == bitc::DEFINE_ABBREV) {
439 if (!CurBlockInfo) return true;
442 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
443 // appropriate BlockInfo.
444 BitCodeAbbrev *Abbv = CurAbbrevs.back();
445 CurAbbrevs.pop_back();
446 CurBlockInfo->Abbrevs.push_back(Abbv);
452 switch (ReadRecord(Code, Record)) {
453 default: break; // Default behavior, ignore unknown content.
454 case bitc::BLOCKINFO_CODE_SETBID:
455 if (Record.size() < 1) return true;
456 CurBlockInfo = &getOrCreateBlockInfo((unsigned)Record[0]);
463 } // End llvm namespace