1 //===- BitstreamReader.h - Low-level bitstream reader 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 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"
26 class BitstreamReader {
27 const unsigned char *NextChar;
28 const unsigned char *LastChar;
29 friend class Deserializer;
31 /// CurWord - This is the current data we have pulled from the stream but have
32 /// not returned to the client.
35 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
36 /// is always from [0...31] inclusive.
37 unsigned BitsInCurWord;
39 // CurCodeSize - This is the declared size of code values used for the current
43 /// CurAbbrevs - Abbrevs installed at in this block.
44 std::vector<BitCodeAbbrev*> CurAbbrevs;
47 unsigned PrevCodeSize;
48 std::vector<BitCodeAbbrev*> PrevAbbrevs;
49 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
52 /// BlockScope - This tracks the codesize of parent blocks.
53 SmallVector<Block, 8> 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 /// FirstChar - This remembers the first byte of the stream.
64 const unsigned char *FirstChar;
67 NextChar = FirstChar = LastChar = 0;
73 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
77 void init(const unsigned char *Start, const unsigned char *End) {
78 NextChar = FirstChar = Start;
80 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
87 // Abbrevs could still exist if the stream was broken. If so, don't leak
89 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
91 CurAbbrevs[i]->dropRef();
93 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
95 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
96 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
98 Abbrevs[i]->dropRef();
101 // Free the BlockInfoRecords.
102 while (!BlockInfoRecords.empty()) {
103 BlockInfo &Info = BlockInfoRecords.back();
104 // Free blockinfo abbrev info.
105 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
107 Info.Abbrevs[i]->dropRef();
108 BlockInfoRecords.pop_back();
112 bool AtEndOfStream() const {
113 return NextChar == LastChar && BitsInCurWord == 0;
116 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
117 uint64_t GetCurrentBitNo() const {
118 return (NextChar-FirstChar)*CHAR_BIT + ((32-BitsInCurWord) & 31);
121 /// JumpToBit - Reset the stream to the specified bit number.
122 void JumpToBit(uint64_t BitNo) {
123 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
124 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
125 assert(ByteNo < (uintptr_t)(LastChar-FirstChar) && "Invalid location");
127 // Move the cursor to the right word.
128 NextChar = FirstChar+ByteNo;
132 // Skip over any bits that are already consumed.
135 Read(static_cast<unsigned>(WordBitNo));
139 /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
140 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
142 uint32_t Read(unsigned NumBits) {
143 // If the field is fully contained by CurWord, return it quickly.
144 if (BitsInCurWord >= NumBits) {
145 uint32_t R = CurWord & ((1U << NumBits)-1);
147 BitsInCurWord -= NumBits;
151 // If we run out of data, stop at the end of the stream.
152 if (LastChar == NextChar) {
158 unsigned R = CurWord;
160 // Read the next word from the stream.
161 CurWord = (NextChar[0] << 0) | (NextChar[1] << 8) |
162 (NextChar[2] << 16) | (NextChar[3] << 24);
165 // Extract NumBits-BitsInCurWord from what we just read.
166 unsigned BitsLeft = NumBits-BitsInCurWord;
168 // Be careful here, BitsLeft is in the range [1..32] inclusive.
169 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
171 // BitsLeft bits have just been used up from CurWord.
173 CurWord >>= BitsLeft;
176 BitsInCurWord = 32-BitsLeft;
180 uint64_t Read64(unsigned NumBits) {
181 if (NumBits <= 32) return Read(NumBits);
183 uint64_t V = Read(32);
184 return V | (uint64_t)Read(NumBits-32) << 32;
187 uint32_t ReadVBR(unsigned NumBits) {
188 uint32_t Piece = Read(NumBits);
189 if ((Piece & (1U << (NumBits-1))) == 0)
193 unsigned NextBit = 0;
195 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
197 if ((Piece & (1U << (NumBits-1))) == 0)
200 NextBit += NumBits-1;
201 Piece = Read(NumBits);
205 uint64_t ReadVBR64(unsigned NumBits) {
206 uint64_t Piece = Read(NumBits);
207 if ((Piece & (1U << (NumBits-1))) == 0)
211 unsigned NextBit = 0;
213 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
215 if ((Piece & (1U << (NumBits-1))) == 0)
218 NextBit += NumBits-1;
219 Piece = Read(NumBits);
229 unsigned ReadCode() {
230 return Read(CurCodeSize);
233 //===--------------------------------------------------------------------===//
234 // Block Manipulation
235 //===--------------------------------------------------------------------===//
238 /// getBlockInfo - If there is block info for the specified ID, return it,
239 /// otherwise return null.
240 BlockInfo *getBlockInfo(unsigned BlockID) {
241 // Common case, the most recent entry matches BlockID.
242 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
243 return &BlockInfoRecords.back();
245 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
247 if (BlockInfoRecords[i].BlockID == BlockID)
248 return &BlockInfoRecords[i];
255 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
257 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
259 unsigned ReadSubBlockID() {
260 return ReadVBR(bitc::BlockIDWidth);
263 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
264 /// over the body of this block. If the block record is malformed, return
267 // Read and ignore the codelen value. Since we are skipping this block, we
268 // don't care what code widths are used inside of it.
269 ReadVBR(bitc::CodeLenWidth);
271 unsigned NumWords = Read(bitc::BlockSizeWidth);
273 // Check that the block wasn't partially defined, and that the offset isn't
275 if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
278 NextChar += NumWords*4;
282 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
283 /// the block, and return true if the block is valid.
284 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
285 // Save the current block's state on BlockScope.
286 BlockScope.push_back(Block(CurCodeSize));
287 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
289 // Add the abbrevs specific to this block to the CurAbbrevs list.
290 if (BlockInfo *Info = getBlockInfo(BlockID)) {
291 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
293 CurAbbrevs.push_back(Info->Abbrevs[i]);
294 CurAbbrevs.back()->addRef();
298 // Get the codesize of this block.
299 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
301 unsigned NumWords = Read(bitc::BlockSizeWidth);
302 if (NumWordsP) *NumWordsP = NumWords;
304 // Validate that this block is sane.
305 if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
311 bool ReadBlockEnd() {
312 if (BlockScope.empty()) return true;
315 // [END_BLOCK, <align4bytes>]
323 void PopBlockScope() {
324 CurCodeSize = BlockScope.back().PrevCodeSize;
326 // Delete abbrevs from popped scope.
327 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
329 CurAbbrevs[i]->dropRef();
331 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
332 BlockScope.pop_back();
335 //===--------------------------------------------------------------------===//
337 //===--------------------------------------------------------------------===//
340 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
341 SmallVectorImpl<uint64_t> &Vals) {
342 if (Op.isLiteral()) {
343 // If the abbrev specifies the literal value to use, use it.
344 Vals.push_back(Op.getLiteralValue());
347 // Decode the value as we are commanded.
348 switch (Op.getEncoding()) {
349 default: assert(0 && "Unknown encoding!");
350 case BitCodeAbbrevOp::Fixed:
351 Vals.push_back(Read((unsigned)Op.getEncodingData()));
353 case BitCodeAbbrevOp::VBR:
354 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
356 case BitCodeAbbrevOp::Char6:
357 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
362 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals) {
363 if (AbbrevID == bitc::UNABBREV_RECORD) {
364 unsigned Code = ReadVBR(6);
365 unsigned NumElts = ReadVBR(6);
366 for (unsigned i = 0; i != NumElts; ++i)
367 Vals.push_back(ReadVBR64(6));
371 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
372 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
373 BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
375 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
376 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
377 if (Op.isLiteral() || Op.getEncoding() != BitCodeAbbrevOp::Array) {
378 ReadAbbreviatedField(Op, Vals);
380 // Array case. Read the number of elements as a vbr6.
381 unsigned NumElts = ReadVBR(6);
383 // Get the element encoding.
384 assert(i+2 == e && "array op not second to last?");
385 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
387 // Read all the elements.
388 for (; NumElts; --NumElts)
389 ReadAbbreviatedField(EltEnc, Vals);
393 unsigned Code = (unsigned)Vals[0];
394 Vals.erase(Vals.begin());
398 //===--------------------------------------------------------------------===//
400 //===--------------------------------------------------------------------===//
402 void ReadAbbrevRecord() {
403 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
404 unsigned NumOpInfo = ReadVBR(5);
405 for (unsigned i = 0; i != NumOpInfo; ++i) {
406 bool IsLiteral = Read(1) ? true : false;
408 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
412 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
413 if (BitCodeAbbrevOp::hasEncodingData(E))
414 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
416 Abbv->Add(BitCodeAbbrevOp(E));
418 CurAbbrevs.push_back(Abbv);
421 //===--------------------------------------------------------------------===//
422 // BlockInfo Block Reading
423 //===--------------------------------------------------------------------===//
426 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
427 if (BlockInfo *BI = getBlockInfo(BlockID))
430 // Otherwise, add a new record.
431 BlockInfoRecords.push_back(BlockInfo());
432 BlockInfoRecords.back().BlockID = BlockID;
433 return BlockInfoRecords.back();
438 bool ReadBlockInfoBlock() {
439 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
441 SmallVector<uint64_t, 64> Record;
442 BlockInfo *CurBlockInfo = 0;
444 // Read all the records for this module.
446 unsigned Code = ReadCode();
447 if (Code == bitc::END_BLOCK)
448 return ReadBlockEnd();
449 if (Code == bitc::ENTER_SUBBLOCK) {
451 if (SkipBlock()) return true;
455 // Read abbrev records, associate them with CurBID.
456 if (Code == bitc::DEFINE_ABBREV) {
457 if (!CurBlockInfo) return true;
460 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
461 // appropriate BlockInfo.
462 BitCodeAbbrev *Abbv = CurAbbrevs.back();
463 CurAbbrevs.pop_back();
464 CurBlockInfo->Abbrevs.push_back(Abbv);
470 switch (ReadRecord(Code, Record)) {
471 default: break; // Default behavior, ignore unknown content.
472 case bitc::BLOCKINFO_CODE_SETBID:
473 if (Record.size() < 1) return true;
474 CurBlockInfo = &getOrCreateBlockInfo((unsigned)Record[0]);
481 } // End llvm namespace