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;
44 /// IgnoreBlockInfoNames - This is set to true if we don't care about the
45 /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
47 bool IgnoreBlockInfoNames;
49 BitstreamReader(const BitstreamReader&); // NOT IMPLEMENTED
50 void operator=(const BitstreamReader&); // NOT IMPLEMENTED
52 BitstreamReader() : FirstChar(0), LastChar(0), IgnoreBlockInfoNames(true) {
55 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
56 IgnoreBlockInfoNames = true;
60 void init(const unsigned char *Start, const unsigned char *End) {
63 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
67 // Free the BlockInfoRecords.
68 while (!BlockInfoRecords.empty()) {
69 BlockInfo &Info = BlockInfoRecords.back();
70 // Free blockinfo abbrev info.
71 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
73 Info.Abbrevs[i]->dropRef();
74 BlockInfoRecords.pop_back();
78 const unsigned char *getFirstChar() const { return FirstChar; }
79 const unsigned char *getLastChar() const { return LastChar; }
81 /// CollectBlockInfoNames - This is called by clients that want block/record
83 void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
84 bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
86 //===--------------------------------------------------------------------===//
88 //===--------------------------------------------------------------------===//
90 /// hasBlockInfoRecords - Return true if we've already read and processed the
91 /// block info block for this Bitstream. We only process it for the first
92 /// cursor that walks over it.
93 bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
95 /// getBlockInfo - If there is block info for the specified ID, return it,
96 /// otherwise return null.
97 const BlockInfo *getBlockInfo(unsigned BlockID) const {
98 // Common case, the most recent entry matches BlockID.
99 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
100 return &BlockInfoRecords.back();
102 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
104 if (BlockInfoRecords[i].BlockID == BlockID)
105 return &BlockInfoRecords[i];
109 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
110 if (const BlockInfo *BI = getBlockInfo(BlockID))
111 return *const_cast<BlockInfo*>(BI);
113 // Otherwise, add a new record.
114 BlockInfoRecords.push_back(BlockInfo());
115 BlockInfoRecords.back().BlockID = BlockID;
116 return BlockInfoRecords.back();
121 class BitstreamCursor {
122 friend class Deserializer;
123 BitstreamReader *BitStream;
124 const unsigned char *NextChar;
126 /// CurWord - This is the current data we have pulled from the stream but have
127 /// not returned to the client.
130 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
131 /// is always from [0...31] inclusive.
132 unsigned BitsInCurWord;
134 // CurCodeSize - This is the declared size of code values used for the current
136 unsigned CurCodeSize;
138 /// CurAbbrevs - Abbrevs installed at in this block.
139 std::vector<BitCodeAbbrev*> CurAbbrevs;
142 unsigned PrevCodeSize;
143 std::vector<BitCodeAbbrev*> PrevAbbrevs;
144 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
147 /// BlockScope - This tracks the codesize of parent blocks.
148 SmallVector<Block, 8> BlockScope;
151 BitstreamCursor() : BitStream(0), NextChar(0) {
153 BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
157 explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
158 NextChar = R.getFirstChar();
159 assert(NextChar && "Bitstream not initialized yet");
165 void init(BitstreamReader &R) {
169 NextChar = R.getFirstChar();
170 assert(NextChar && "Bitstream not initialized yet");
180 void operator=(const BitstreamCursor &RHS) {
183 BitStream = RHS.BitStream;
184 NextChar = RHS.NextChar;
185 CurWord = RHS.CurWord;
186 BitsInCurWord = RHS.BitsInCurWord;
187 CurCodeSize = RHS.CurCodeSize;
189 // Copy abbreviations, and bump ref counts.
190 CurAbbrevs = RHS.CurAbbrevs;
191 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
193 CurAbbrevs[i]->addRef();
195 // Copy block scope and bump ref counts.
196 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
198 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
199 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
201 Abbrevs[i]->addRef();
206 // Free all the Abbrevs.
207 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
209 CurAbbrevs[i]->dropRef();
212 // Free all the Abbrevs in the block scope.
213 for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
215 std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
216 for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
218 Abbrevs[i]->dropRef();
223 /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
224 unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
226 bool AtEndOfStream() const {
227 return NextChar == BitStream->getLastChar() && BitsInCurWord == 0;
230 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
231 uint64_t GetCurrentBitNo() const {
232 return (NextChar-BitStream->getFirstChar())*CHAR_BIT - BitsInCurWord;
235 BitstreamReader *getBitStreamReader() {
238 const BitstreamReader *getBitStreamReader() const {
243 /// JumpToBit - Reset the stream to the specified bit number.
244 void JumpToBit(uint64_t BitNo) {
245 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
246 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
247 assert(ByteNo <= (uintptr_t)(BitStream->getLastChar()-
248 BitStream->getFirstChar()) &&
251 // Move the cursor to the right word.
252 NextChar = BitStream->getFirstChar()+ByteNo;
256 // Skip over any bits that are already consumed.
258 Read(static_cast<unsigned>(WordBitNo));
262 uint32_t Read(unsigned NumBits) {
263 // If the field is fully contained by CurWord, return it quickly.
264 if (BitsInCurWord >= NumBits) {
265 uint32_t R = CurWord & ((1U << NumBits)-1);
267 BitsInCurWord -= NumBits;
271 // If we run out of data, stop at the end of the stream.
272 if (NextChar == BitStream->getLastChar()) {
278 unsigned R = CurWord;
280 // Read the next word from the stream.
281 CurWord = (NextChar[0] << 0) | (NextChar[1] << 8) |
282 (NextChar[2] << 16) | (NextChar[3] << 24);
285 // Extract NumBits-BitsInCurWord from what we just read.
286 unsigned BitsLeft = NumBits-BitsInCurWord;
288 // Be careful here, BitsLeft is in the range [1..32] inclusive.
289 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
291 // BitsLeft bits have just been used up from CurWord.
293 CurWord >>= BitsLeft;
296 BitsInCurWord = 32-BitsLeft;
300 uint64_t Read64(unsigned NumBits) {
301 if (NumBits <= 32) return Read(NumBits);
303 uint64_t V = Read(32);
304 return V | (uint64_t)Read(NumBits-32) << 32;
307 uint32_t ReadVBR(unsigned NumBits) {
308 uint32_t Piece = Read(NumBits);
309 if ((Piece & (1U << (NumBits-1))) == 0)
313 unsigned NextBit = 0;
315 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
317 if ((Piece & (1U << (NumBits-1))) == 0)
320 NextBit += NumBits-1;
321 Piece = Read(NumBits);
325 uint64_t ReadVBR64(unsigned NumBits) {
326 uint64_t Piece = Read(NumBits);
327 if ((Piece & (1U << (NumBits-1))) == 0)
331 unsigned NextBit = 0;
333 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
335 if ((Piece & (1U << (NumBits-1))) == 0)
338 NextBit += NumBits-1;
339 Piece = Read(NumBits);
348 unsigned ReadCode() {
349 return Read(CurCodeSize);
354 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
356 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
358 unsigned ReadSubBlockID() {
359 return ReadVBR(bitc::BlockIDWidth);
362 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
363 /// over the body of this block. If the block record is malformed, return
366 // Read and ignore the codelen value. Since we are skipping this block, we
367 // don't care what code widths are used inside of it.
368 ReadVBR(bitc::CodeLenWidth);
370 unsigned NumWords = Read(bitc::BlockSizeWidth);
372 // Check that the block wasn't partially defined, and that the offset isn't
374 if (AtEndOfStream() || NextChar+NumWords*4 > BitStream->getLastChar())
377 NextChar += NumWords*4;
381 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
382 /// the block, and return true if the block is valid.
383 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
384 // Save the current block's state on BlockScope.
385 BlockScope.push_back(Block(CurCodeSize));
386 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
388 // Add the abbrevs specific to this block to the CurAbbrevs list.
389 if (const BitstreamReader::BlockInfo *Info =
390 BitStream->getBlockInfo(BlockID)) {
391 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
393 CurAbbrevs.push_back(Info->Abbrevs[i]);
394 CurAbbrevs.back()->addRef();
398 // Get the codesize of this block.
399 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
401 unsigned NumWords = Read(bitc::BlockSizeWidth);
402 if (NumWordsP) *NumWordsP = NumWords;
404 // Validate that this block is sane.
405 if (CurCodeSize == 0 || AtEndOfStream() ||
406 NextChar+NumWords*4 > BitStream->getLastChar())
412 bool ReadBlockEnd() {
413 if (BlockScope.empty()) return true;
416 // [END_BLOCK, <align4bytes>]
424 void PopBlockScope() {
425 CurCodeSize = BlockScope.back().PrevCodeSize;
427 // Delete abbrevs from popped scope.
428 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
430 CurAbbrevs[i]->dropRef();
432 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
433 BlockScope.pop_back();
436 //===--------------------------------------------------------------------===//
438 //===--------------------------------------------------------------------===//
441 void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
442 SmallVectorImpl<uint64_t> &Vals) {
443 assert(Op.isLiteral() && "Not a literal");
444 // If the abbrev specifies the literal value to use, use it.
445 Vals.push_back(Op.getLiteralValue());
448 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
449 SmallVectorImpl<uint64_t> &Vals) {
450 assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
452 // Decode the value as we are commanded.
453 switch (Op.getEncoding()) {
454 default: assert(0 && "Unknown encoding!");
455 case BitCodeAbbrevOp::Fixed:
456 Vals.push_back(Read((unsigned)Op.getEncodingData()));
458 case BitCodeAbbrevOp::VBR:
459 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
461 case BitCodeAbbrevOp::Char6:
462 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
468 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
469 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
470 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
471 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
472 return CurAbbrevs[AbbrevNo];
475 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
476 const char **BlobStart = 0, unsigned *BlobLen = 0) {
477 if (AbbrevID == bitc::UNABBREV_RECORD) {
478 unsigned Code = ReadVBR(6);
479 unsigned NumElts = ReadVBR(6);
480 for (unsigned i = 0; i != NumElts; ++i)
481 Vals.push_back(ReadVBR64(6));
485 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
487 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
488 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
489 if (Op.isLiteral()) {
490 ReadAbbreviatedLiteral(Op, Vals);
491 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
492 // Array case. Read the number of elements as a vbr6.
493 unsigned NumElts = ReadVBR(6);
495 // Get the element encoding.
496 assert(i+2 == e && "array op not second to last?");
497 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
499 // Read all the elements.
500 for (; NumElts; --NumElts)
501 ReadAbbreviatedField(EltEnc, Vals);
502 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
503 // Blob case. Read the number of bytes as a vbr6.
504 unsigned NumElts = ReadVBR(6);
505 SkipToWord(); // 32-bit alignment
507 // Figure out where the end of this blob will be including tail padding.
508 const unsigned char *NewEnd = NextChar+((NumElts+3)&~3);
510 // If this would read off the end of the bitcode file, just set the
511 // record to empty and return.
512 if (NewEnd > BitStream->getLastChar()) {
513 Vals.append(NumElts, 0);
514 NextChar = BitStream->getLastChar();
518 // Otherwise, read the number of bytes. If we can return a reference to
519 // the data, do so to avoid copying it.
521 *BlobStart = (const char*)NextChar;
524 for (; NumElts; ++NextChar, --NumElts)
525 Vals.push_back(*NextChar);
527 // Skip over tail padding.
530 ReadAbbreviatedField(Op, Vals);
534 unsigned Code = (unsigned)Vals[0];
535 Vals.erase(Vals.begin());
539 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
540 const char *&BlobStart, unsigned &BlobLen) {
541 return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
545 //===--------------------------------------------------------------------===//
547 //===--------------------------------------------------------------------===//
549 void ReadAbbrevRecord() {
550 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
551 unsigned NumOpInfo = ReadVBR(5);
552 for (unsigned i = 0; i != NumOpInfo; ++i) {
553 bool IsLiteral = Read(1) ? true : false;
555 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
559 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
560 if (BitCodeAbbrevOp::hasEncodingData(E))
561 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
563 Abbv->Add(BitCodeAbbrevOp(E));
565 CurAbbrevs.push_back(Abbv);
570 bool ReadBlockInfoBlock() {
571 // If this is the second stream to get to the block info block, skip it.
572 if (BitStream->hasBlockInfoRecords())
575 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
577 SmallVector<uint64_t, 64> Record;
578 BitstreamReader::BlockInfo *CurBlockInfo = 0;
580 // Read all the records for this module.
582 unsigned Code = ReadCode();
583 if (Code == bitc::END_BLOCK)
584 return ReadBlockEnd();
585 if (Code == bitc::ENTER_SUBBLOCK) {
587 if (SkipBlock()) return true;
591 // Read abbrev records, associate them with CurBID.
592 if (Code == bitc::DEFINE_ABBREV) {
593 if (!CurBlockInfo) return true;
596 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
597 // appropriate BlockInfo.
598 BitCodeAbbrev *Abbv = CurAbbrevs.back();
599 CurAbbrevs.pop_back();
600 CurBlockInfo->Abbrevs.push_back(Abbv);
606 switch (ReadRecord(Code, Record)) {
607 default: break; // Default behavior, ignore unknown content.
608 case bitc::BLOCKINFO_CODE_SETBID:
609 if (Record.size() < 1) return true;
610 CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
612 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
613 if (!CurBlockInfo) return true;
614 if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
616 for (unsigned i = 0, e = Record.size(); i != e; ++i)
617 Name += (char)Record[i];
618 CurBlockInfo->Name = Name;
621 case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
622 if (!CurBlockInfo) return true;
623 if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
625 for (unsigned i = 1, e = Record.size(); i != e; ++i)
626 Name += (char)Record[i];
627 CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
636 } // End llvm namespace