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 {
28 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
29 /// These describe abbreviations that all blocks of the specified ID inherit.
32 std::vector<BitCodeAbbrev*> Abbrevs;
35 /// FirstChar/LastChar - This remembers the first and last bytes of the
37 const unsigned char *FirstChar, *LastChar;
39 std::vector<BlockInfo> BlockInfoRecords;
42 BitstreamReader() : FirstChar(0), LastChar(0) {
45 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
49 void init(const unsigned char *Start, const unsigned char *End) {
52 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
56 // Free the BlockInfoRecords.
57 while (!BlockInfoRecords.empty()) {
58 BlockInfo &Info = BlockInfoRecords.back();
59 // Free blockinfo abbrev info.
60 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
62 Info.Abbrevs[i]->dropRef();
63 BlockInfoRecords.pop_back();
67 const unsigned char *getFirstChar() const { return FirstChar; }
68 const unsigned char *getLastChar() const { return LastChar; }
70 //===--------------------------------------------------------------------===//
72 //===--------------------------------------------------------------------===//
74 /// getBlockInfo - If there is block info for the specified ID, return it,
75 /// otherwise return null.
76 BlockInfo *getBlockInfo(unsigned BlockID) {
77 // Common case, the most recent entry matches BlockID.
78 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
79 return &BlockInfoRecords.back();
81 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
83 if (BlockInfoRecords[i].BlockID == BlockID)
84 return &BlockInfoRecords[i];
88 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
89 if (BlockInfo *BI = getBlockInfo(BlockID))
92 // Otherwise, add a new record.
93 BlockInfoRecords.push_back(BlockInfo());
94 BlockInfoRecords.back().BlockID = BlockID;
95 return BlockInfoRecords.back();
100 class BitstreamCursor {
101 friend class Deserializer;
102 BitstreamReader *BitStream;
103 const unsigned char *NextChar;
105 /// CurWord - This is the current data we have pulled from the stream but have
106 /// not returned to the client.
109 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
110 /// is always from [0...31] inclusive.
111 unsigned BitsInCurWord;
113 // CurCodeSize - This is the declared size of code values used for the current
115 unsigned CurCodeSize;
117 /// CurAbbrevs - Abbrevs installed at in this block.
118 std::vector<BitCodeAbbrev*> CurAbbrevs;
121 unsigned PrevCodeSize;
122 std::vector<BitCodeAbbrev*> PrevAbbrevs;
123 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
126 /// BlockScope - This tracks the codesize of parent blocks.
127 SmallVector<Block, 8> BlockScope;
129 BitstreamCursor(const BitstreamCursor&); // NOT YET IMPLEMENTED.
130 void operator=(const BitstreamCursor&); // NOT YET IMPLEMENTED.
132 BitstreamCursor() : BitStream(0), NextChar(0) {
134 explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
135 NextChar = R.getFirstChar();
136 assert(NextChar && "Bitstream not initialized yet");
142 void init(BitstreamReader &R) {
146 NextChar = R.getFirstChar();
147 assert(NextChar && "Bitstream not initialized yet");
158 // Free all the Abbrevs.
159 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
161 CurAbbrevs[i]->dropRef();
164 // Free all the Abbrevs in the block scope.
165 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
167 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
168 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
170 Abbrevs[i]->dropRef();
175 /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
176 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
178 bool AtEndOfStream() const {
179 return NextChar == BitStream->getLastChar() && BitsInCurWord == 0;
182 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
183 uint64_t GetCurrentBitNo() const {
184 return (NextChar-BitStream->getFirstChar())*CHAR_BIT - BitsInCurWord;
188 /// JumpToBit - Reset the stream to the specified bit number.
189 void JumpToBit(uint64_t BitNo) {
190 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
191 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
192 assert(ByteNo <= (uintptr_t)(BitStream->getLastChar()-
193 BitStream->getFirstChar()) &&
196 // Move the cursor to the right word.
197 NextChar = BitStream->getFirstChar()+ByteNo;
201 // Skip over any bits that are already consumed.
203 Read(static_cast<unsigned>(WordBitNo));
207 uint32_t Read(unsigned NumBits) {
208 // If the field is fully contained by CurWord, return it quickly.
209 if (BitsInCurWord >= NumBits) {
210 uint32_t R = CurWord & ((1U << NumBits)-1);
212 BitsInCurWord -= NumBits;
216 // If we run out of data, stop at the end of the stream.
217 if (NextChar == BitStream->getLastChar()) {
223 unsigned R = CurWord;
225 // Read the next word from the stream.
226 CurWord = (NextChar[0] << 0) | (NextChar[1] << 8) |
227 (NextChar[2] << 16) | (NextChar[3] << 24);
230 // Extract NumBits-BitsInCurWord from what we just read.
231 unsigned BitsLeft = NumBits-BitsInCurWord;
233 // Be careful here, BitsLeft is in the range [1..32] inclusive.
234 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
236 // BitsLeft bits have just been used up from CurWord.
238 CurWord >>= BitsLeft;
241 BitsInCurWord = 32-BitsLeft;
245 uint64_t Read64(unsigned NumBits) {
246 if (NumBits <= 32) return Read(NumBits);
248 uint64_t V = Read(32);
249 return V | (uint64_t)Read(NumBits-32) << 32;
252 uint32_t ReadVBR(unsigned NumBits) {
253 uint32_t Piece = Read(NumBits);
254 if ((Piece & (1U << (NumBits-1))) == 0)
258 unsigned NextBit = 0;
260 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
262 if ((Piece & (1U << (NumBits-1))) == 0)
265 NextBit += NumBits-1;
266 Piece = Read(NumBits);
270 uint64_t ReadVBR64(unsigned NumBits) {
271 uint64_t Piece = Read(NumBits);
272 if ((Piece & (1U << (NumBits-1))) == 0)
276 unsigned NextBit = 0;
278 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
280 if ((Piece & (1U << (NumBits-1))) == 0)
283 NextBit += NumBits-1;
284 Piece = Read(NumBits);
293 unsigned ReadCode() {
294 return Read(CurCodeSize);
299 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
301 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
303 unsigned ReadSubBlockID() {
304 return ReadVBR(bitc::BlockIDWidth);
307 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
308 /// over the body of this block. If the block record is malformed, return
311 // Read and ignore the codelen value. Since we are skipping this block, we
312 // don't care what code widths are used inside of it.
313 ReadVBR(bitc::CodeLenWidth);
315 unsigned NumWords = Read(bitc::BlockSizeWidth);
317 // Check that the block wasn't partially defined, and that the offset isn't
319 if (AtEndOfStream() || NextChar+NumWords*4 > BitStream->getLastChar())
322 NextChar += NumWords*4;
326 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
327 /// the block, and return true if the block is valid.
328 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
329 // Save the current block's state on BlockScope.
330 BlockScope.push_back(Block(CurCodeSize));
331 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
333 // Add the abbrevs specific to this block to the CurAbbrevs list.
334 if (BitstreamReader::BlockInfo *Info = BitStream->getBlockInfo(BlockID)) {
335 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
337 CurAbbrevs.push_back(Info->Abbrevs[i]);
338 CurAbbrevs.back()->addRef();
342 // Get the codesize of this block.
343 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
345 unsigned NumWords = Read(bitc::BlockSizeWidth);
346 if (NumWordsP) *NumWordsP = NumWords;
348 // Validate that this block is sane.
349 if (CurCodeSize == 0 || AtEndOfStream() ||
350 NextChar+NumWords*4 > BitStream->getLastChar())
356 bool ReadBlockEnd() {
357 if (BlockScope.empty()) return true;
360 // [END_BLOCK, <align4bytes>]
368 void PopBlockScope() {
369 CurCodeSize = BlockScope.back().PrevCodeSize;
371 // Delete abbrevs from popped scope.
372 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
374 CurAbbrevs[i]->dropRef();
376 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
377 BlockScope.pop_back();
380 //===--------------------------------------------------------------------===//
382 //===--------------------------------------------------------------------===//
385 void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
386 SmallVectorImpl<uint64_t> &Vals) {
387 assert(Op.isLiteral() && "Not a literal");
388 // If the abbrev specifies the literal value to use, use it.
389 Vals.push_back(Op.getLiteralValue());
392 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
393 SmallVectorImpl<uint64_t> &Vals) {
394 assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
396 // Decode the value as we are commanded.
397 switch (Op.getEncoding()) {
398 default: assert(0 && "Unknown encoding!");
399 case BitCodeAbbrevOp::Fixed:
400 Vals.push_back(Read((unsigned)Op.getEncodingData()));
402 case BitCodeAbbrevOp::VBR:
403 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
405 case BitCodeAbbrevOp::Char6:
406 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
412 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
413 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
414 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
415 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
416 return CurAbbrevs[AbbrevNo];
419 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
420 const char **BlobStart = 0, unsigned *BlobLen = 0) {
421 if (AbbrevID == bitc::UNABBREV_RECORD) {
422 unsigned Code = ReadVBR(6);
423 unsigned NumElts = ReadVBR(6);
424 for (unsigned i = 0; i != NumElts; ++i)
425 Vals.push_back(ReadVBR64(6));
429 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
431 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
432 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
433 if (Op.isLiteral()) {
434 ReadAbbreviatedLiteral(Op, Vals);
435 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
436 // Array case. Read the number of elements as a vbr6.
437 unsigned NumElts = ReadVBR(6);
439 // Get the element encoding.
440 assert(i+2 == e && "array op not second to last?");
441 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
443 // Read all the elements.
444 for (; NumElts; --NumElts)
445 ReadAbbreviatedField(EltEnc, Vals);
446 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
447 // Blob case. Read the number of bytes as a vbr6.
448 unsigned NumElts = ReadVBR(6);
449 SkipToWord(); // 32-bit alignment
451 // Figure out where the end of this blob will be including tail padding.
452 const unsigned char *NewEnd = NextChar+((NumElts+3)&~3);
454 // If this would read off the end of the bitcode file, just set the
455 // record to empty and return.
456 if (NewEnd > BitStream->getLastChar()) {
457 Vals.append(NumElts, 0);
458 NextChar = BitStream->getLastChar();
462 // Otherwise, read the number of bytes. If we can return a reference to
463 // the data, do so to avoid copying it.
465 *BlobStart = (const char*)NextChar;
468 for (; NumElts; ++NextChar, --NumElts)
469 Vals.push_back(*NextChar);
471 // Skip over tail padding.
474 ReadAbbreviatedField(Op, Vals);
478 unsigned Code = (unsigned)Vals[0];
479 Vals.erase(Vals.begin());
483 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
484 const char *&BlobStart, unsigned &BlobLen) {
485 return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
489 //===--------------------------------------------------------------------===//
491 //===--------------------------------------------------------------------===//
493 void ReadAbbrevRecord() {
494 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
495 unsigned NumOpInfo = ReadVBR(5);
496 for (unsigned i = 0; i != NumOpInfo; ++i) {
497 bool IsLiteral = Read(1) ? true : false;
499 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
503 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
504 if (BitCodeAbbrevOp::hasEncodingData(E))
505 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
507 Abbv->Add(BitCodeAbbrevOp(E));
509 CurAbbrevs.push_back(Abbv);
514 bool ReadBlockInfoBlock() {
515 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
517 SmallVector<uint64_t, 64> Record;
518 BitstreamReader::BlockInfo *CurBlockInfo = 0;
520 // Read all the records for this module.
522 unsigned Code = ReadCode();
523 if (Code == bitc::END_BLOCK)
524 return ReadBlockEnd();
525 if (Code == bitc::ENTER_SUBBLOCK) {
527 if (SkipBlock()) return true;
531 // Read abbrev records, associate them with CurBID.
532 if (Code == bitc::DEFINE_ABBREV) {
533 if (!CurBlockInfo) return true;
536 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
537 // appropriate BlockInfo.
538 BitCodeAbbrev *Abbv = CurAbbrevs.back();
539 CurAbbrevs.pop_back();
540 CurBlockInfo->Abbrevs.push_back(Abbv);
546 switch (ReadRecord(Code, Record)) {
547 default: break; // Default behavior, ignore unknown content.
548 case bitc::BLOCKINFO_CODE_SETBID:
549 if (Record.size() < 1) return true;
550 CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
557 } // End llvm namespace