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/ADT/OwningPtr.h"
19 #include "llvm/Bitcode/BitCodes.h"
23 #include "llvm/Support/StreamableMemoryObject.h"
29 class BitstreamReader {
31 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
32 /// These describe abbreviations that all blocks of the specified ID inherit.
35 std::vector<BitCodeAbbrev*> Abbrevs;
38 std::vector<std::pair<unsigned, std::string> > RecordNames;
41 OwningPtr<StreamableMemoryObject> BitcodeBytes;
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&); // DO NOT IMPLEMENT
51 void operator=(const BitstreamReader&); // DO NOT IMPLEMENT
53 BitstreamReader() : IgnoreBlockInfoNames(true) {
56 BitstreamReader(const unsigned char *Start, const unsigned char *End) {
57 IgnoreBlockInfoNames = true;
61 BitstreamReader(StreamableMemoryObject *bytes) {
62 BitcodeBytes.reset(bytes);
65 void init(const unsigned char *Start, const unsigned char *End) {
66 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
67 BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
70 StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
73 // Free the BlockInfoRecords.
74 while (!BlockInfoRecords.empty()) {
75 BlockInfo &Info = BlockInfoRecords.back();
76 // Free blockinfo abbrev info.
77 for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
79 Info.Abbrevs[i]->dropRef();
80 BlockInfoRecords.pop_back();
84 /// CollectBlockInfoNames - This is called by clients that want block/record
86 void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
87 bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
89 //===--------------------------------------------------------------------===//
91 //===--------------------------------------------------------------------===//
93 /// hasBlockInfoRecords - Return true if we've already read and processed the
94 /// block info block for this Bitstream. We only process it for the first
95 /// cursor that walks over it.
96 bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
98 /// getBlockInfo - If there is block info for the specified ID, return it,
99 /// otherwise return null.
100 const BlockInfo *getBlockInfo(unsigned BlockID) const {
101 // Common case, the most recent entry matches BlockID.
102 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
103 return &BlockInfoRecords.back();
105 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
107 if (BlockInfoRecords[i].BlockID == BlockID)
108 return &BlockInfoRecords[i];
112 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
113 if (const BlockInfo *BI = getBlockInfo(BlockID))
114 return *const_cast<BlockInfo*>(BI);
116 // Otherwise, add a new record.
117 BlockInfoRecords.push_back(BlockInfo());
118 BlockInfoRecords.back().BlockID = BlockID;
119 return BlockInfoRecords.back();
124 class BitstreamCursor {
125 friend class Deserializer;
126 BitstreamReader *BitStream;
129 /// CurWord - This is the current data we have pulled from the stream but have
130 /// not returned to the client.
133 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
134 /// is always from [0...31] inclusive.
135 unsigned BitsInCurWord;
137 // CurCodeSize - This is the declared size of code values used for the current
139 unsigned CurCodeSize;
141 /// CurAbbrevs - Abbrevs installed at in this block.
142 std::vector<BitCodeAbbrev*> CurAbbrevs;
145 unsigned PrevCodeSize;
146 std::vector<BitCodeAbbrev*> PrevAbbrevs;
147 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
150 /// BlockScope - This tracks the codesize of parent blocks.
151 SmallVector<Block, 8> BlockScope;
154 BitstreamCursor() : BitStream(0), NextChar(0) {
156 BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
160 explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
167 void init(BitstreamReader &R) {
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 isEndPos(size_t pos) {
229 return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
232 bool canSkipToPos(size_t pos) const {
233 // pos can be skipped to if it is a valid address or one byte past the end.
234 return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
235 static_cast<uint64_t>(pos - 1));
238 unsigned char getByte(size_t pos) {
240 BitStream->getBitcodeBytes().readByte(pos, &byte);
244 uint32_t getWord(size_t pos) {
246 BitStream->getBitcodeBytes().readBytes(pos,
248 reinterpret_cast<uint8_t *>(&word),
253 bool AtEndOfStream() {
254 return isEndPos(NextChar) && BitsInCurWord == 0;
257 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
258 uint64_t GetCurrentBitNo() const {
259 return NextChar*CHAR_BIT - BitsInCurWord;
262 BitstreamReader *getBitStreamReader() {
265 const BitstreamReader *getBitStreamReader() const {
270 /// JumpToBit - Reset the stream to the specified bit number.
271 void JumpToBit(uint64_t BitNo) {
272 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
273 uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
274 assert(canSkipToPos(ByteNo) && "Invalid location");
276 // Move the cursor to the right word.
281 // Skip over any bits that are already consumed.
283 Read(static_cast<unsigned>(WordBitNo));
287 uint32_t Read(unsigned NumBits) {
288 assert(NumBits <= 32 && "Cannot return more than 32 bits!");
289 // If the field is fully contained by CurWord, return it quickly.
290 if (BitsInCurWord >= NumBits) {
291 uint32_t R = CurWord & ((1U << NumBits)-1);
293 BitsInCurWord -= NumBits;
297 // If we run out of data, stop at the end of the stream.
298 if (isEndPos(NextChar)) {
304 unsigned R = CurWord;
306 // Read the next word from the stream.
307 CurWord = getWord(NextChar);
310 // Extract NumBits-BitsInCurWord from what we just read.
311 unsigned BitsLeft = NumBits-BitsInCurWord;
313 // Be careful here, BitsLeft is in the range [1..32] inclusive.
314 R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
316 // BitsLeft bits have just been used up from CurWord.
318 CurWord >>= BitsLeft;
321 BitsInCurWord = 32-BitsLeft;
325 uint64_t Read64(unsigned NumBits) {
326 if (NumBits <= 32) return Read(NumBits);
328 uint64_t V = Read(32);
329 return V | (uint64_t)Read(NumBits-32) << 32;
332 uint32_t ReadVBR(unsigned NumBits) {
333 uint32_t Piece = Read(NumBits);
334 if ((Piece & (1U << (NumBits-1))) == 0)
338 unsigned NextBit = 0;
340 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
342 if ((Piece & (1U << (NumBits-1))) == 0)
345 NextBit += NumBits-1;
346 Piece = Read(NumBits);
350 // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size. The
351 // chunk size of the VBR must still be <= 32 bits though.
352 uint64_t ReadVBR64(unsigned NumBits) {
353 uint32_t Piece = Read(NumBits);
354 if ((Piece & (1U << (NumBits-1))) == 0)
355 return uint64_t(Piece);
358 unsigned NextBit = 0;
360 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
362 if ((Piece & (1U << (NumBits-1))) == 0)
365 NextBit += NumBits-1;
366 Piece = Read(NumBits);
375 unsigned ReadCode() {
376 return Read(CurCodeSize);
381 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
383 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
385 unsigned ReadSubBlockID() {
386 return ReadVBR(bitc::BlockIDWidth);
389 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
390 /// over the body of this block. If the block record is malformed, return
393 // Read and ignore the codelen value. Since we are skipping this block, we
394 // don't care what code widths are used inside of it.
395 ReadVBR(bitc::CodeLenWidth);
397 unsigned NumWords = Read(bitc::BlockSizeWidth);
399 // Check that the block wasn't partially defined, and that the offset isn't
401 size_t SkipTo = NextChar + NumWords*4;
402 if (AtEndOfStream() || !canSkipToPos(SkipTo))
409 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
410 /// the block, and return true if the block is valid.
411 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
412 // Save the current block's state on BlockScope.
413 BlockScope.push_back(Block(CurCodeSize));
414 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
416 // Add the abbrevs specific to this block to the CurAbbrevs list.
417 if (const BitstreamReader::BlockInfo *Info =
418 BitStream->getBlockInfo(BlockID)) {
419 for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
421 CurAbbrevs.push_back(Info->Abbrevs[i]);
422 CurAbbrevs.back()->addRef();
426 // Get the codesize of this block.
427 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
429 unsigned NumWords = Read(bitc::BlockSizeWidth);
430 if (NumWordsP) *NumWordsP = NumWords;
432 // Validate that this block is sane.
433 if (CurCodeSize == 0 || AtEndOfStream())
439 bool ReadBlockEnd() {
440 if (BlockScope.empty()) return true;
443 // [END_BLOCK, <align4bytes>]
451 void PopBlockScope() {
452 CurCodeSize = BlockScope.back().PrevCodeSize;
454 // Delete abbrevs from popped scope.
455 for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
457 CurAbbrevs[i]->dropRef();
459 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
460 BlockScope.pop_back();
463 //===--------------------------------------------------------------------===//
465 //===--------------------------------------------------------------------===//
468 void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
469 SmallVectorImpl<uint64_t> &Vals) {
470 assert(Op.isLiteral() && "Not a literal");
471 // If the abbrev specifies the literal value to use, use it.
472 Vals.push_back(Op.getLiteralValue());
475 void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
476 SmallVectorImpl<uint64_t> &Vals) {
477 assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
479 // Decode the value as we are commanded.
480 switch (Op.getEncoding()) {
481 default: llvm_unreachable("Unknown encoding!");
482 case BitCodeAbbrevOp::Fixed:
483 Vals.push_back(Read((unsigned)Op.getEncodingData()));
485 case BitCodeAbbrevOp::VBR:
486 Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
488 case BitCodeAbbrevOp::Char6:
489 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
495 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
496 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
497 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
498 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
499 return CurAbbrevs[AbbrevNo];
502 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
503 const char **BlobStart = 0, unsigned *BlobLen = 0) {
504 if (AbbrevID == bitc::UNABBREV_RECORD) {
505 unsigned Code = ReadVBR(6);
506 unsigned NumElts = ReadVBR(6);
507 for (unsigned i = 0; i != NumElts; ++i)
508 Vals.push_back(ReadVBR64(6));
512 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
514 for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
515 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
516 if (Op.isLiteral()) {
517 ReadAbbreviatedLiteral(Op, Vals);
518 } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
519 // Array case. Read the number of elements as a vbr6.
520 unsigned NumElts = ReadVBR(6);
522 // Get the element encoding.
523 assert(i+2 == e && "array op not second to last?");
524 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
526 // Read all the elements.
527 for (; NumElts; --NumElts)
528 ReadAbbreviatedField(EltEnc, Vals);
529 } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
530 // Blob case. Read the number of bytes as a vbr6.
531 unsigned NumElts = ReadVBR(6);
532 SkipToWord(); // 32-bit alignment
534 // Figure out where the end of this blob will be including tail padding.
535 size_t NewEnd = NextChar+((NumElts+3)&~3);
537 // If this would read off the end of the bitcode file, just set the
538 // record to empty and return.
539 if (!canSkipToPos(NewEnd)) {
540 Vals.append(NumElts, 0);
541 NextChar = BitStream->getBitcodeBytes().getExtent();
545 // Otherwise, read the number of bytes. If we can return a reference to
546 // the data, do so to avoid copying it.
548 *BlobStart = (const char*)BitStream->getBitcodeBytes().getPointer(
552 for (; NumElts; ++NextChar, --NumElts)
553 Vals.push_back(getByte(NextChar));
555 // Skip over tail padding.
558 ReadAbbreviatedField(Op, Vals);
562 unsigned Code = (unsigned)Vals[0];
563 Vals.erase(Vals.begin());
567 unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
568 const char *&BlobStart, unsigned &BlobLen) {
569 return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
573 //===--------------------------------------------------------------------===//
575 //===--------------------------------------------------------------------===//
577 void ReadAbbrevRecord() {
578 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
579 unsigned NumOpInfo = ReadVBR(5);
580 for (unsigned i = 0; i != NumOpInfo; ++i) {
581 bool IsLiteral = Read(1) ? true : false;
583 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
587 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
588 if (BitCodeAbbrevOp::hasEncodingData(E))
589 Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
591 Abbv->Add(BitCodeAbbrevOp(E));
593 CurAbbrevs.push_back(Abbv);
598 bool ReadBlockInfoBlock() {
599 // If this is the second stream to get to the block info block, skip it.
600 if (BitStream->hasBlockInfoRecords())
603 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
605 SmallVector<uint64_t, 64> Record;
606 BitstreamReader::BlockInfo *CurBlockInfo = 0;
608 // Read all the records for this module.
610 unsigned Code = ReadCode();
611 if (Code == bitc::END_BLOCK)
612 return ReadBlockEnd();
613 if (Code == bitc::ENTER_SUBBLOCK) {
615 if (SkipBlock()) return true;
619 // Read abbrev records, associate them with CurBID.
620 if (Code == bitc::DEFINE_ABBREV) {
621 if (!CurBlockInfo) return true;
624 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
625 // appropriate BlockInfo.
626 BitCodeAbbrev *Abbv = CurAbbrevs.back();
627 CurAbbrevs.pop_back();
628 CurBlockInfo->Abbrevs.push_back(Abbv);
634 switch (ReadRecord(Code, Record)) {
635 default: break; // Default behavior, ignore unknown content.
636 case bitc::BLOCKINFO_CODE_SETBID:
637 if (Record.size() < 1) return true;
638 CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
640 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
641 if (!CurBlockInfo) return true;
642 if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
644 for (unsigned i = 0, e = Record.size(); i != e; ++i)
645 Name += (char)Record[i];
646 CurBlockInfo->Name = Name;
649 case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
650 if (!CurBlockInfo) return true;
651 if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
653 for (unsigned i = 1, e = Record.size(); i != e; ++i)
654 Name += (char)Record[i];
655 CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
664 } // End llvm namespace