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"
27 class BitstreamReader {
29 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
30 /// These describe abbreviations that all blocks of the specified ID inherit.
33 std::vector<BitCodeAbbrev*> Abbrevs;
36 std::vector<std::pair<unsigned, std::string> > RecordNames;
39 /// FirstChar/LastChar - This remembers the first and last bytes of the
41 const unsigned char *FirstChar, *LastChar;
43 std::vector<BlockInfo> BlockInfoRecords;
45 /// IgnoreBlockInfoNames - This is set to true if we don't care about the
46 /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
48 bool IgnoreBlockInfoNames;
50 BitstreamReader(const BitstreamReader&); // NOT IMPLEMENTED
51 void operator=(const BitstreamReader&); // NOT IMPLEMENTED
53 BitstreamReader() : FirstChar(0), LastChar(0), IgnoreBlockInfoNames(true) {
56 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
57 IgnoreBlockInfoNames = true;
61 void init(const unsigned char *Start, const unsigned char *End) {
64 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
68 // Free the BlockInfoRecords.
69 while (!BlockInfoRecords.empty()) {
70 BlockInfo &Info = BlockInfoRecords.back();
71 // Free blockinfo abbrev info.
72 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
74 Info.Abbrevs[i]->dropRef();
75 BlockInfoRecords.pop_back();
79 const unsigned char *getFirstChar() const { return FirstChar; }
80 const unsigned char *getLastChar() const { return LastChar; }
82 /// CollectBlockInfoNames - This is called by clients that want block/record
84 void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
85 bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
87 //===--------------------------------------------------------------------===//
89 //===--------------------------------------------------------------------===//
91 /// hasBlockInfoRecords - Return true if we've already read and processed the
92 /// block info block for this Bitstream. We only process it for the first
93 /// cursor that walks over it.
94 bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
96 /// getBlockInfo - If there is block info for the specified ID, return it,
97 /// otherwise return null.
98 const BlockInfo *getBlockInfo(unsigned BlockID) const {
99 // Common case, the most recent entry matches BlockID.
100 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
101 return &BlockInfoRecords.back();
103 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
105 if (BlockInfoRecords[i].BlockID == BlockID)
106 return &BlockInfoRecords[i];
110 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
111 if (const BlockInfo *BI = getBlockInfo(BlockID))
112 return *const_cast<BlockInfo*>(BI);
114 // Otherwise, add a new record.
115 BlockInfoRecords.push_back(BlockInfo());
116 BlockInfoRecords.back().BlockID = BlockID;
117 return BlockInfoRecords.back();
122 class BitstreamCursor {
123 friend class Deserializer;
124 BitstreamReader *BitStream;
125 const unsigned char *NextChar;
127 /// CurWord - This is the current data we have pulled from the stream but have
128 /// not returned to the client.
131 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
132 /// is always from [0...31] inclusive.
133 unsigned BitsInCurWord;
135 // CurCodeSize - This is the declared size of code values used for the current
137 unsigned CurCodeSize;
139 /// CurAbbrevs - Abbrevs installed at in this block.
140 std::vector<BitCodeAbbrev*> CurAbbrevs;
143 unsigned PrevCodeSize;
144 std::vector<BitCodeAbbrev*> PrevAbbrevs;
145 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
148 /// BlockScope - This tracks the codesize of parent blocks.
149 SmallVector<Block, 8> BlockScope;
152 BitstreamCursor() : BitStream(0), NextChar(0) {
154 BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
158 explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
159 NextChar = R.getFirstChar();
160 assert(NextChar && "Bitstream not initialized yet");
166 void init(BitstreamReader &R) {
170 NextChar = R.getFirstChar();
171 assert(NextChar && "Bitstream not initialized yet");
181 void operator=(const BitstreamCursor &RHS) {
184 BitStream = RHS.BitStream;
185 NextChar = RHS.NextChar;
186 CurWord = RHS.CurWord;
187 BitsInCurWord = RHS.BitsInCurWord;
188 CurCodeSize = RHS.CurCodeSize;
190 // Copy abbreviations, and bump ref counts.
191 CurAbbrevs = RHS.CurAbbrevs;
192 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
194 CurAbbrevs[i]->addRef();
196 // Copy block scope and bump ref counts.
197 BlockScope = RHS.BlockScope;
198 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
200 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
201 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
203 Abbrevs[i]->addRef();
208 // Free all the Abbrevs.
209 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
211 CurAbbrevs[i]->dropRef();
214 // Free all the Abbrevs in the block scope.
215 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
217 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
218 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
220 Abbrevs[i]->dropRef();
225 /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
226 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
228 bool AtEndOfStream() const {
229 return NextChar == BitStream->getLastChar() && BitsInCurWord == 0;
232 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
233 uint64_t GetCurrentBitNo() const {
234 return (NextChar-BitStream->getFirstChar())*CHAR_BIT - BitsInCurWord;
237 BitstreamReader *getBitStreamReader() {
240 const BitstreamReader *getBitStreamReader() const {
245 /// JumpToBit - Reset the stream to the specified bit number.
246 void JumpToBit(uint64_t BitNo) {
247 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
248 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
249 assert(ByteNo <= (uintptr_t)(BitStream->getLastChar()-
250 BitStream->getFirstChar()) &&
253 // Move the cursor to the right word.
254 NextChar = BitStream->getFirstChar()+ByteNo;
258 // Skip over any bits that are already consumed.
260 Read(static_cast<unsigned>(WordBitNo));
264 uint32_t Read(unsigned NumBits) {
265 assert(NumBits <= 32 && "Cannot return more than 32 bits!");
266 // If the field is fully contained by CurWord, return it quickly.
267 if (BitsInCurWord >= NumBits) {
268 uint32_t R = CurWord & ((1U << NumBits)-1);
270 BitsInCurWord -= NumBits;
274 // If we run out of data, stop at the end of the stream.
275 if (NextChar == BitStream->getLastChar()) {
281 unsigned R = CurWord;
283 // Read the next word from the stream.
284 CurWord = (NextChar[0] << 0) | (NextChar[1] << 8) |
285 (NextChar[2] << 16) | (NextChar[3] << 24);
288 // Extract NumBits-BitsInCurWord from what we just read.
289 unsigned BitsLeft = NumBits-BitsInCurWord;
291 // Be careful here, BitsLeft is in the range [1..32] inclusive.
292 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
294 // BitsLeft bits have just been used up from CurWord.
296 CurWord >>= BitsLeft;
299 BitsInCurWord = 32-BitsLeft;
303 uint64_t Read64(unsigned NumBits) {
304 if (NumBits <= 32) return Read(NumBits);
306 uint64_t V = Read(32);
307 return V | (uint64_t)Read(NumBits-32) << 32;
310 uint32_t ReadVBR(unsigned NumBits) {
311 uint32_t Piece = Read(NumBits);
312 if ((Piece & (1U << (NumBits-1))) == 0)
316 unsigned NextBit = 0;
318 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
320 if ((Piece & (1U << (NumBits-1))) == 0)
323 NextBit += NumBits-1;
324 Piece = Read(NumBits);
328 // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size. The
329 // chunk size of the VBR must still be <= 32 bits though.
330 uint64_t ReadVBR64(unsigned NumBits) {
331 uint32_t Piece = Read(NumBits);
332 if ((Piece & (1U << (NumBits-1))) == 0)
333 return uint64_t(Piece);
336 unsigned NextBit = 0;
338 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
340 if ((Piece & (1U << (NumBits-1))) == 0)
343 NextBit += NumBits-1;
344 Piece = Read(NumBits);
353 unsigned ReadCode() {
354 return Read(CurCodeSize);
359 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
361 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
363 unsigned ReadSubBlockID() {
364 return ReadVBR(bitc::BlockIDWidth);
367 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
368 /// over the body of this block. If the block record is malformed, return
371 // Read and ignore the codelen value. Since we are skipping this block, we
372 // don't care what code widths are used inside of it.
373 ReadVBR(bitc::CodeLenWidth);
375 unsigned NumWords = Read(bitc::BlockSizeWidth);
377 // Check that the block wasn't partially defined, and that the offset isn't
379 const unsigned char *const SkipTo = NextChar + NumWords*4;
380 if (AtEndOfStream() || SkipTo > BitStream->getLastChar() ||
381 SkipTo < BitStream->getFirstChar())
388 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
389 /// the block, and return true if the block is valid.
390 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
391 // Save the current block's state on BlockScope.
392 BlockScope.push_back(Block(CurCodeSize));
393 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
395 // Add the abbrevs specific to this block to the CurAbbrevs list.
396 if (const BitstreamReader::BlockInfo *Info =
397 BitStream->getBlockInfo(BlockID)) {
398 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
400 CurAbbrevs.push_back(Info->Abbrevs[i]);
401 CurAbbrevs.back()->addRef();
405 // Get the codesize of this block.
406 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
408 unsigned NumWords = Read(bitc::BlockSizeWidth);
409 if (NumWordsP) *NumWordsP = NumWords;
411 // Validate that this block is sane.
412 if (CurCodeSize == 0 || AtEndOfStream() ||
413 NextChar+NumWords*4 > BitStream->getLastChar())
419 bool ReadBlockEnd() {
420 if (BlockScope.empty()) return true;
423 // [END_BLOCK, <align4bytes>]
431 void PopBlockScope() {
432 CurCodeSize = BlockScope.back().PrevCodeSize;
434 // Delete abbrevs from popped scope.
435 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
437 CurAbbrevs[i]->dropRef();
439 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
440 BlockScope.pop_back();
443 //===--------------------------------------------------------------------===//
445 //===--------------------------------------------------------------------===//
448 void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
449 SmallVectorImpl<uint64_t> &Vals) {
450 assert(Op.isLiteral() && "Not a literal");
451 // If the abbrev specifies the literal value to use, use it.
452 Vals.push_back(Op.getLiteralValue());
455 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
456 SmallVectorImpl<uint64_t> &Vals) {
457 assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
459 // Decode the value as we are commanded.
460 switch (Op.getEncoding()) {
461 default: assert(0 && "Unknown encoding!");
462 case BitCodeAbbrevOp::Fixed:
463 Vals.push_back(Read((unsigned)Op.getEncodingData()));
465 case BitCodeAbbrevOp::VBR:
466 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
468 case BitCodeAbbrevOp::Char6:
469 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
475 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
476 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
477 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
478 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
479 return CurAbbrevs[AbbrevNo];
482 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
483 const char **BlobStart = 0, unsigned *BlobLen = 0) {
484 if (AbbrevID == bitc::UNABBREV_RECORD) {
485 unsigned Code = ReadVBR(6);
486 unsigned NumElts = ReadVBR(6);
487 for (unsigned i = 0; i != NumElts; ++i)
488 Vals.push_back(ReadVBR64(6));
492 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
494 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
495 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
496 if (Op.isLiteral()) {
497 ReadAbbreviatedLiteral(Op, Vals);
498 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
499 // Array case. Read the number of elements as a vbr6.
500 unsigned NumElts = ReadVBR(6);
502 // Get the element encoding.
503 assert(i+2 == e && "array op not second to last?");
504 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
506 // Read all the elements.
507 for (; NumElts; --NumElts)
508 ReadAbbreviatedField(EltEnc, Vals);
509 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
510 // Blob case. Read the number of bytes as a vbr6.
511 unsigned NumElts = ReadVBR(6);
512 SkipToWord(); // 32-bit alignment
514 // Figure out where the end of this blob will be including tail padding.
515 const unsigned char *NewEnd = NextChar+((NumElts+3)&~3);
517 // If this would read off the end of the bitcode file, just set the
518 // record to empty and return.
519 if (NewEnd > BitStream->getLastChar()) {
520 Vals.append(NumElts, 0);
521 NextChar = BitStream->getLastChar();
525 // Otherwise, read the number of bytes. If we can return a reference to
526 // the data, do so to avoid copying it.
528 *BlobStart = (const char*)NextChar;
531 for (; NumElts; ++NextChar, --NumElts)
532 Vals.push_back(*NextChar);
534 // Skip over tail padding.
537 ReadAbbreviatedField(Op, Vals);
541 unsigned Code = (unsigned)Vals[0];
542 Vals.erase(Vals.begin());
546 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
547 const char *&BlobStart, unsigned &BlobLen) {
548 return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
552 //===--------------------------------------------------------------------===//
554 //===--------------------------------------------------------------------===//
556 void ReadAbbrevRecord() {
557 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
558 unsigned NumOpInfo = ReadVBR(5);
559 for (unsigned i = 0; i != NumOpInfo; ++i) {
560 bool IsLiteral = Read(1) ? true : false;
562 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
566 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
567 if (BitCodeAbbrevOp::hasEncodingData(E))
568 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
570 Abbv->Add(BitCodeAbbrevOp(E));
572 CurAbbrevs.push_back(Abbv);
577 bool ReadBlockInfoBlock() {
578 // If this is the second stream to get to the block info block, skip it.
579 if (BitStream->hasBlockInfoRecords())
582 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
584 SmallVector<uint64_t, 64> Record;
585 BitstreamReader::BlockInfo *CurBlockInfo = 0;
587 // Read all the records for this module.
589 unsigned Code = ReadCode();
590 if (Code == bitc::END_BLOCK)
591 return ReadBlockEnd();
592 if (Code == bitc::ENTER_SUBBLOCK) {
594 if (SkipBlock()) return true;
598 // Read abbrev records, associate them with CurBID.
599 if (Code == bitc::DEFINE_ABBREV) {
600 if (!CurBlockInfo) return true;
603 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
604 // appropriate BlockInfo.
605 BitCodeAbbrev *Abbv = CurAbbrevs.back();
606 CurAbbrevs.pop_back();
607 CurBlockInfo->Abbrevs.push_back(Abbv);
613 switch (ReadRecord(Code, Record)) {
614 default: break; // Default behavior, ignore unknown content.
615 case bitc::BLOCKINFO_CODE_SETBID:
616 if (Record.size() < 1) return true;
617 CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
619 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
620 if (!CurBlockInfo) return true;
621 if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
623 for (unsigned i = 0, e = Record.size(); i != e; ++i)
624 Name += (char)Record[i];
625 CurBlockInfo->Name = Name;
628 case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
629 if (!CurBlockInfo) return true;
630 if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
632 for (unsigned i = 1, e = Record.size(); i != e; ++i)
633 Name += (char)Record[i];
634 CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
643 } // End llvm namespace