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 std::vector<std::pair<unsigned, std::string> > RecordNames;
38 /// FirstChar/LastChar - This remembers the first and last bytes of the
40 const unsigned char *FirstChar, *LastChar;
42 std::vector<BlockInfo> BlockInfoRecords;
45 BitstreamReader() : FirstChar(0), LastChar(0) {
48 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
52 void init(const unsigned char *Start, const unsigned char *End) {
55 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
59 // Free the BlockInfoRecords.
60 while (!BlockInfoRecords.empty()) {
61 BlockInfo &Info = BlockInfoRecords.back();
62 // Free blockinfo abbrev info.
63 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
65 Info.Abbrevs[i]->dropRef();
66 BlockInfoRecords.pop_back();
70 const unsigned char *getFirstChar() const { return FirstChar; }
71 const unsigned char *getLastChar() const { return LastChar; }
73 //===--------------------------------------------------------------------===//
75 //===--------------------------------------------------------------------===//
77 /// hasBlockInfoRecords - Return true if we've already read and processed the
78 /// block info block for this Bitstream. We only process it for the first
79 /// cursor that walks over it.
80 bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
82 /// getBlockInfo - If there is block info for the specified ID, return it,
83 /// otherwise return null.
84 const BlockInfo *getBlockInfo(unsigned BlockID) const {
85 // Common case, the most recent entry matches BlockID.
86 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
87 return &BlockInfoRecords.back();
89 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
91 if (BlockInfoRecords[i].BlockID == BlockID)
92 return &BlockInfoRecords[i];
96 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
97 if (const BlockInfo *BI = getBlockInfo(BlockID))
98 return *const_cast<BlockInfo*>(BI);
100 // Otherwise, add a new record.
101 BlockInfoRecords.push_back(BlockInfo());
102 BlockInfoRecords.back().BlockID = BlockID;
103 return BlockInfoRecords.back();
108 class BitstreamCursor {
109 friend class Deserializer;
110 BitstreamReader *BitStream;
111 const unsigned char *NextChar;
113 /// CurWord - This is the current data we have pulled from the stream but have
114 /// not returned to the client.
117 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
118 /// is always from [0...31] inclusive.
119 unsigned BitsInCurWord;
121 // CurCodeSize - This is the declared size of code values used for the current
123 unsigned CurCodeSize;
125 /// CurAbbrevs - Abbrevs installed at in this block.
126 std::vector<BitCodeAbbrev*> CurAbbrevs;
129 unsigned PrevCodeSize;
130 std::vector<BitCodeAbbrev*> PrevAbbrevs;
131 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
134 /// BlockScope - This tracks the codesize of parent blocks.
135 SmallVector<Block, 8> BlockScope;
138 BitstreamCursor() : BitStream(0), NextChar(0) {
140 BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
144 explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
145 NextChar = R.getFirstChar();
146 assert(NextChar && "Bitstream not initialized yet");
152 void init(BitstreamReader &R) {
156 NextChar = R.getFirstChar();
157 assert(NextChar && "Bitstream not initialized yet");
167 void operator=(const BitstreamCursor &RHS) {
170 BitStream = RHS.BitStream;
171 NextChar = RHS.NextChar;
172 CurWord = RHS.CurWord;
173 BitsInCurWord = RHS.BitsInCurWord;
174 CurCodeSize = RHS.CurCodeSize;
176 // Copy abbreviations, and bump ref counts.
177 CurAbbrevs = RHS.CurAbbrevs;
178 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
180 CurAbbrevs[i]->addRef();
182 // Copy block scope and bump ref counts.
183 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
185 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
186 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
188 Abbrevs[i]->addRef();
193 // Free all the Abbrevs.
194 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
196 CurAbbrevs[i]->dropRef();
199 // Free all the Abbrevs in the block scope.
200 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
202 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
203 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
205 Abbrevs[i]->dropRef();
210 /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
211 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
213 bool AtEndOfStream() const {
214 return NextChar == BitStream->getLastChar() && BitsInCurWord == 0;
217 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
218 uint64_t GetCurrentBitNo() const {
219 return (NextChar-BitStream->getFirstChar())*CHAR_BIT - BitsInCurWord;
222 BitstreamReader *getBitStreamReader() {
225 const BitstreamReader *getBitStreamReader() const {
230 /// JumpToBit - Reset the stream to the specified bit number.
231 void JumpToBit(uint64_t BitNo) {
232 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
233 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
234 assert(ByteNo <= (uintptr_t)(BitStream->getLastChar()-
235 BitStream->getFirstChar()) &&
238 // Move the cursor to the right word.
239 NextChar = BitStream->getFirstChar()+ByteNo;
243 // Skip over any bits that are already consumed.
245 Read(static_cast<unsigned>(WordBitNo));
249 uint32_t Read(unsigned NumBits) {
250 // If the field is fully contained by CurWord, return it quickly.
251 if (BitsInCurWord >= NumBits) {
252 uint32_t R = CurWord & ((1U << NumBits)-1);
254 BitsInCurWord -= NumBits;
258 // If we run out of data, stop at the end of the stream.
259 if (NextChar == BitStream->getLastChar()) {
265 unsigned R = CurWord;
267 // Read the next word from the stream.
268 CurWord = (NextChar[0] << 0) | (NextChar[1] << 8) |
269 (NextChar[2] << 16) | (NextChar[3] << 24);
272 // Extract NumBits-BitsInCurWord from what we just read.
273 unsigned BitsLeft = NumBits-BitsInCurWord;
275 // Be careful here, BitsLeft is in the range [1..32] inclusive.
276 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
278 // BitsLeft bits have just been used up from CurWord.
280 CurWord >>= BitsLeft;
283 BitsInCurWord = 32-BitsLeft;
287 uint64_t Read64(unsigned NumBits) {
288 if (NumBits <= 32) return Read(NumBits);
290 uint64_t V = Read(32);
291 return V | (uint64_t)Read(NumBits-32) << 32;
294 uint32_t ReadVBR(unsigned NumBits) {
295 uint32_t Piece = Read(NumBits);
296 if ((Piece & (1U << (NumBits-1))) == 0)
300 unsigned NextBit = 0;
302 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
304 if ((Piece & (1U << (NumBits-1))) == 0)
307 NextBit += NumBits-1;
308 Piece = Read(NumBits);
312 uint64_t ReadVBR64(unsigned NumBits) {
313 uint64_t Piece = Read(NumBits);
314 if ((Piece & (1U << (NumBits-1))) == 0)
318 unsigned NextBit = 0;
320 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
322 if ((Piece & (1U << (NumBits-1))) == 0)
325 NextBit += NumBits-1;
326 Piece = Read(NumBits);
335 unsigned ReadCode() {
336 return Read(CurCodeSize);
341 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
343 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
345 unsigned ReadSubBlockID() {
346 return ReadVBR(bitc::BlockIDWidth);
349 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
350 /// over the body of this block. If the block record is malformed, return
353 // Read and ignore the codelen value. Since we are skipping this block, we
354 // don't care what code widths are used inside of it.
355 ReadVBR(bitc::CodeLenWidth);
357 unsigned NumWords = Read(bitc::BlockSizeWidth);
359 // Check that the block wasn't partially defined, and that the offset isn't
361 if (AtEndOfStream() || NextChar+NumWords*4 > BitStream->getLastChar())
364 NextChar += NumWords*4;
368 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
369 /// the block, and return true if the block is valid.
370 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
371 // Save the current block's state on BlockScope.
372 BlockScope.push_back(Block(CurCodeSize));
373 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
375 // Add the abbrevs specific to this block to the CurAbbrevs list.
376 if (const BitstreamReader::BlockInfo *Info =
377 BitStream->getBlockInfo(BlockID)) {
378 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
380 CurAbbrevs.push_back(Info->Abbrevs[i]);
381 CurAbbrevs.back()->addRef();
385 // Get the codesize of this block.
386 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
388 unsigned NumWords = Read(bitc::BlockSizeWidth);
389 if (NumWordsP) *NumWordsP = NumWords;
391 // Validate that this block is sane.
392 if (CurCodeSize == 0 || AtEndOfStream() ||
393 NextChar+NumWords*4 > BitStream->getLastChar())
399 bool ReadBlockEnd() {
400 if (BlockScope.empty()) return true;
403 // [END_BLOCK, <align4bytes>]
411 void PopBlockScope() {
412 CurCodeSize = BlockScope.back().PrevCodeSize;
414 // Delete abbrevs from popped scope.
415 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
417 CurAbbrevs[i]->dropRef();
419 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
420 BlockScope.pop_back();
423 //===--------------------------------------------------------------------===//
425 //===--------------------------------------------------------------------===//
428 void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
429 SmallVectorImpl<uint64_t> &Vals) {
430 assert(Op.isLiteral() && "Not a literal");
431 // If the abbrev specifies the literal value to use, use it.
432 Vals.push_back(Op.getLiteralValue());
435 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
436 SmallVectorImpl<uint64_t> &Vals) {
437 assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
439 // Decode the value as we are commanded.
440 switch (Op.getEncoding()) {
441 default: assert(0 && "Unknown encoding!");
442 case BitCodeAbbrevOp::Fixed:
443 Vals.push_back(Read((unsigned)Op.getEncodingData()));
445 case BitCodeAbbrevOp::VBR:
446 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
448 case BitCodeAbbrevOp::Char6:
449 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
455 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
456 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
457 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
458 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
459 return CurAbbrevs[AbbrevNo];
462 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
463 const char **BlobStart = 0, unsigned *BlobLen = 0) {
464 if (AbbrevID == bitc::UNABBREV_RECORD) {
465 unsigned Code = ReadVBR(6);
466 unsigned NumElts = ReadVBR(6);
467 for (unsigned i = 0; i != NumElts; ++i)
468 Vals.push_back(ReadVBR64(6));
472 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
474 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
475 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
476 if (Op.isLiteral()) {
477 ReadAbbreviatedLiteral(Op, Vals);
478 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
479 // Array case. Read the number of elements as a vbr6.
480 unsigned NumElts = ReadVBR(6);
482 // Get the element encoding.
483 assert(i+2 == e && "array op not second to last?");
484 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
486 // Read all the elements.
487 for (; NumElts; --NumElts)
488 ReadAbbreviatedField(EltEnc, Vals);
489 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
490 // Blob case. Read the number of bytes as a vbr6.
491 unsigned NumElts = ReadVBR(6);
492 SkipToWord(); // 32-bit alignment
494 // Figure out where the end of this blob will be including tail padding.
495 const unsigned char *NewEnd = NextChar+((NumElts+3)&~3);
497 // If this would read off the end of the bitcode file, just set the
498 // record to empty and return.
499 if (NewEnd > BitStream->getLastChar()) {
500 Vals.append(NumElts, 0);
501 NextChar = BitStream->getLastChar();
505 // Otherwise, read the number of bytes. If we can return a reference to
506 // the data, do so to avoid copying it.
508 *BlobStart = (const char*)NextChar;
511 for (; NumElts; ++NextChar, --NumElts)
512 Vals.push_back(*NextChar);
514 // Skip over tail padding.
517 ReadAbbreviatedField(Op, Vals);
521 unsigned Code = (unsigned)Vals[0];
522 Vals.erase(Vals.begin());
526 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
527 const char *&BlobStart, unsigned &BlobLen) {
528 return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
532 //===--------------------------------------------------------------------===//
534 //===--------------------------------------------------------------------===//
536 void ReadAbbrevRecord() {
537 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
538 unsigned NumOpInfo = ReadVBR(5);
539 for (unsigned i = 0; i != NumOpInfo; ++i) {
540 bool IsLiteral = Read(1) ? true : false;
542 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
546 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
547 if (BitCodeAbbrevOp::hasEncodingData(E))
548 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
550 Abbv->Add(BitCodeAbbrevOp(E));
552 CurAbbrevs.push_back(Abbv);
557 bool ReadBlockInfoBlock() {
558 // If this is the second stream to get to the block info block, skip it.
559 if (BitStream->hasBlockInfoRecords())
562 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
564 SmallVector<uint64_t, 64> Record;
565 BitstreamReader::BlockInfo *CurBlockInfo = 0;
567 // Read all the records for this module.
569 unsigned Code = ReadCode();
570 if (Code == bitc::END_BLOCK)
571 return ReadBlockEnd();
572 if (Code == bitc::ENTER_SUBBLOCK) {
574 if (SkipBlock()) return true;
578 // Read abbrev records, associate them with CurBID.
579 if (Code == bitc::DEFINE_ABBREV) {
580 if (!CurBlockInfo) return true;
583 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
584 // appropriate BlockInfo.
585 BitCodeAbbrev *Abbv = CurAbbrevs.back();
586 CurAbbrevs.pop_back();
587 CurBlockInfo->Abbrevs.push_back(Abbv);
593 switch (ReadRecord(Code, Record)) {
594 default: break; // Default behavior, ignore unknown content.
595 case bitc::BLOCKINFO_CODE_SETBID:
596 if (Record.size() < 1) return true;
597 CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
599 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
600 if (!CurBlockInfo) return true;
602 for (unsigned i = 0, e = Record.size(); i != e; ++i)
603 Name += (char)Record[i];
604 CurBlockInfo->Name = Name;
607 case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
608 if (!CurBlockInfo) return true;
610 for (unsigned i = 1, e = Record.size(); i != e; ++i)
611 Name += (char)Record[i];
612 CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
621 } // End llvm namespace