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 LLVM_BITCODE_BITSTREAMREADER_H
16 #define LLVM_BITCODE_BITSTREAMREADER_H
18 #include "llvm/Bitcode/BitCodes.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/StreamableMemoryObject.h"
29 /// BitstreamReader - This class is used to read from an LLVM bitcode stream,
30 /// maintaining information that is global to decoding the entire file. While
31 /// a file is being read, multiple cursors can be independently advanced or
32 /// skipped around within the file. These are represented by the
33 /// BitstreamCursor class.
34 class BitstreamReader {
36 /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
37 /// These describe abbreviations that all blocks of the specified ID inherit.
40 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
43 std::vector<std::pair<unsigned, std::string> > RecordNames;
46 std::unique_ptr<StreamableMemoryObject> BitcodeBytes;
48 std::vector<BlockInfo> BlockInfoRecords;
50 /// IgnoreBlockInfoNames - This is set to true if we don't care about the
51 /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
53 bool IgnoreBlockInfoNames;
55 BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
56 void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
58 BitstreamReader() : IgnoreBlockInfoNames(true) {
61 BitstreamReader(const unsigned char *Start, const unsigned char *End)
62 : IgnoreBlockInfoNames(true) {
66 BitstreamReader(StreamableMemoryObject *bytes) : IgnoreBlockInfoNames(true) {
67 BitcodeBytes.reset(bytes);
70 BitstreamReader(BitstreamReader &&Other) {
71 *this = std::move(Other);
74 BitstreamReader &operator=(BitstreamReader &&Other) {
75 BitcodeBytes = std::move(Other.BitcodeBytes);
76 // Explicitly swap block info, so that nothing gets destroyed twice.
77 std::swap(BlockInfoRecords, Other.BlockInfoRecords);
78 IgnoreBlockInfoNames = Other.IgnoreBlockInfoNames;
82 void init(const unsigned char *Start, const unsigned char *End) {
83 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
84 BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
87 StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
89 /// CollectBlockInfoNames - This is called by clients that want block/record
91 void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
92 bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
94 //===--------------------------------------------------------------------===//
96 //===--------------------------------------------------------------------===//
98 /// hasBlockInfoRecords - Return true if we've already read and processed the
99 /// block info block for this Bitstream. We only process it for the first
100 /// cursor that walks over it.
101 bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
103 /// getBlockInfo - If there is block info for the specified ID, return it,
104 /// otherwise return null.
105 const BlockInfo *getBlockInfo(unsigned BlockID) const {
106 // Common case, the most recent entry matches BlockID.
107 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
108 return &BlockInfoRecords.back();
110 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
112 if (BlockInfoRecords[i].BlockID == BlockID)
113 return &BlockInfoRecords[i];
117 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
118 if (const BlockInfo *BI = getBlockInfo(BlockID))
119 return *const_cast<BlockInfo*>(BI);
121 // Otherwise, add a new record.
122 BlockInfoRecords.push_back(BlockInfo());
123 BlockInfoRecords.back().BlockID = BlockID;
124 return BlockInfoRecords.back();
127 /// Takes block info from the other bitstream reader.
129 /// This is a "take" operation because BlockInfo records are non-trivial, and
130 /// indeed rather expensive.
131 void takeBlockInfo(BitstreamReader &&Other) {
132 assert(!hasBlockInfoRecords());
133 BlockInfoRecords = std::move(Other.BlockInfoRecords);
138 /// BitstreamEntry - When advancing through a bitstream cursor, each advance can
139 /// discover a few different kinds of entries:
140 /// Error - Malformed bitcode was found.
141 /// EndBlock - We've reached the end of the current block, (or the end of the
142 /// file, which is treated like a series of EndBlock records.
143 /// SubBlock - This is the start of a new subblock of a specific ID.
144 /// Record - This is a record with a specific AbbrevID.
146 struct BitstreamEntry {
156 static BitstreamEntry getError() {
157 BitstreamEntry E; E.Kind = Error; return E;
159 static BitstreamEntry getEndBlock() {
160 BitstreamEntry E; E.Kind = EndBlock; return E;
162 static BitstreamEntry getSubBlock(unsigned ID) {
163 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
165 static BitstreamEntry getRecord(unsigned AbbrevID) {
166 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
170 /// BitstreamCursor - This represents a position within a bitcode file. There
171 /// may be multiple independent cursors reading within one bitstream, each
172 /// maintaining their own local state.
174 /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
175 /// be passed by value.
176 class BitstreamCursor {
177 friend class Deserializer;
178 BitstreamReader *BitStream;
182 /// CurWord/word_t - This is the current data we have pulled from the stream
183 /// but have not returned to the client. This is specifically and
184 /// intentionally defined to follow the word size of the host machine for
185 /// efficiency. We use word_t in places that are aware of this to make it
186 /// perfectly explicit what is going on.
187 typedef uint32_t word_t;
190 /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
191 /// is always from [0...31/63] inclusive (depending on word size).
192 unsigned BitsInCurWord;
194 // CurCodeSize - This is the declared size of code values used for the current
196 unsigned CurCodeSize;
198 /// CurAbbrevs - Abbrevs installed at in this block.
199 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
202 unsigned PrevCodeSize;
203 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
204 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
207 /// BlockScope - This tracks the codesize of parent blocks.
208 SmallVector<Block, 8> BlockScope;
212 BitstreamCursor() : BitStream(nullptr), NextChar(0) {}
214 explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
221 void init(BitstreamReader &R) {
233 bool isEndPos(size_t pos) {
234 return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
237 bool canSkipToPos(size_t pos) const {
238 // pos can be skipped to if it is a valid address or one byte past the end.
239 return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
240 static_cast<uint64_t>(pos - 1));
243 uint32_t getWord(size_t pos) {
244 uint8_t buf[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
245 BitStream->getBitcodeBytes().readBytes(pos, sizeof(buf), buf);
246 return *reinterpret_cast<support::ulittle32_t *>(buf);
249 bool AtEndOfStream() {
250 return BitsInCurWord == 0 && isEndPos(NextChar);
253 /// getAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
254 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
256 /// GetCurrentBitNo - Return the bit # of the bit we are reading.
257 uint64_t GetCurrentBitNo() const {
258 return NextChar*CHAR_BIT - BitsInCurWord;
261 BitstreamReader *getBitStreamReader() {
264 const BitstreamReader *getBitStreamReader() const {
268 /// Flags that modify the behavior of advance().
270 /// AF_DontPopBlockAtEnd - If this flag is used, the advance() method does
271 /// not automatically pop the block scope when the end of a block is
273 AF_DontPopBlockAtEnd = 1,
275 /// AF_DontAutoprocessAbbrevs - If this flag is used, abbrev entries are
276 /// returned just like normal records.
277 AF_DontAutoprocessAbbrevs = 2
280 /// advance - Advance the current bitstream, returning the next entry in the
282 BitstreamEntry advance(unsigned Flags = 0) {
284 unsigned Code = ReadCode();
285 if (Code == bitc::END_BLOCK) {
286 // Pop the end of the block unless Flags tells us not to.
287 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
288 return BitstreamEntry::getError();
289 return BitstreamEntry::getEndBlock();
292 if (Code == bitc::ENTER_SUBBLOCK)
293 return BitstreamEntry::getSubBlock(ReadSubBlockID());
295 if (Code == bitc::DEFINE_ABBREV &&
296 !(Flags & AF_DontAutoprocessAbbrevs)) {
297 // We read and accumulate abbrev's, the client can't do anything with
303 return BitstreamEntry::getRecord(Code);
307 /// advanceSkippingSubblocks - This is a convenience function for clients that
308 /// don't expect any subblocks. This just skips over them automatically.
309 BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
311 // If we found a normal entry, return it.
312 BitstreamEntry Entry = advance(Flags);
313 if (Entry.Kind != BitstreamEntry::SubBlock)
316 // If we found a sub-block, just skip over it and check the next entry.
318 return BitstreamEntry::getError();
322 /// JumpToBit - Reset the stream to the specified bit number.
323 void JumpToBit(uint64_t BitNo) {
324 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~(sizeof(word_t)-1);
325 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
326 assert(canSkipToPos(ByteNo) && "Invalid location");
328 // Move the cursor to the right word.
333 // Skip over any bits that are already consumed.
335 if (sizeof(word_t) > 4)
343 uint32_t Read(unsigned NumBits) {
344 assert(NumBits && NumBits <= 32 &&
345 "Cannot return zero or more than 32 bits!");
347 // If the field is fully contained by CurWord, return it quickly.
348 if (BitsInCurWord >= NumBits) {
349 uint32_t R = uint32_t(CurWord) & (~0U >> (32-NumBits));
351 BitsInCurWord -= NumBits;
355 // If we run out of data, stop at the end of the stream.
356 if (isEndPos(NextChar)) {
362 uint32_t R = uint32_t(CurWord);
364 // Read the next word from the stream.
365 uint8_t Array[sizeof(word_t)] = {0};
367 BitStream->getBitcodeBytes().readBytes(NextChar, sizeof(Array), Array);
369 // Handle big-endian byte-swapping if necessary.
370 support::detail::packed_endian_specific_integral
371 <word_t, support::little, support::unaligned> EndianValue;
372 memcpy(&EndianValue, Array, sizeof(Array));
374 CurWord = EndianValue;
376 NextChar += sizeof(word_t);
378 // Extract NumBits-BitsInCurWord from what we just read.
379 unsigned BitsLeft = NumBits-BitsInCurWord;
381 // Be careful here, BitsLeft is in the range [1..32]/[1..64] inclusive.
382 R |= uint32_t((CurWord & (word_t(~0ULL) >> (sizeof(word_t)*8-BitsLeft)))
385 // BitsLeft bits have just been used up from CurWord. BitsLeft is in the
386 // range [1..32]/[1..64] so be careful how we shift.
387 if (BitsLeft != sizeof(word_t)*8)
388 CurWord >>= BitsLeft;
391 BitsInCurWord = sizeof(word_t)*8-BitsLeft;
395 uint64_t Read64(unsigned NumBits) {
396 if (NumBits <= 32) return Read(NumBits);
398 uint64_t V = Read(32);
399 return V | (uint64_t)Read(NumBits-32) << 32;
402 uint32_t ReadVBR(unsigned NumBits) {
403 uint32_t Piece = Read(NumBits);
404 if ((Piece & (1U << (NumBits-1))) == 0)
408 unsigned NextBit = 0;
410 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
412 if ((Piece & (1U << (NumBits-1))) == 0)
415 NextBit += NumBits-1;
416 Piece = Read(NumBits);
420 // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size. The
421 // chunk size of the VBR must still be <= 32 bits though.
422 uint64_t ReadVBR64(unsigned NumBits) {
423 uint32_t Piece = Read(NumBits);
424 if ((Piece & (1U << (NumBits-1))) == 0)
425 return uint64_t(Piece);
428 unsigned NextBit = 0;
430 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
432 if ((Piece & (1U << (NumBits-1))) == 0)
435 NextBit += NumBits-1;
436 Piece = Read(NumBits);
441 void SkipToFourByteBoundary() {
442 // If word_t is 64-bits and if we've read less than 32 bits, just dump
443 // the bits we have up to the next 32-bit boundary.
444 if (sizeof(word_t) > 4 &&
445 BitsInCurWord >= 32) {
446 CurWord >>= BitsInCurWord-32;
456 unsigned ReadCode() {
457 return Read(CurCodeSize);
462 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
464 /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
466 unsigned ReadSubBlockID() {
467 return ReadVBR(bitc::BlockIDWidth);
470 /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
471 /// over the body of this block. If the block record is malformed, return
474 // Read and ignore the codelen value. Since we are skipping this block, we
475 // don't care what code widths are used inside of it.
476 ReadVBR(bitc::CodeLenWidth);
477 SkipToFourByteBoundary();
478 unsigned NumFourBytes = Read(bitc::BlockSizeWidth);
480 // Check that the block wasn't partially defined, and that the offset isn't
482 size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
483 if (AtEndOfStream() || !canSkipToPos(SkipTo/8))
490 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
491 /// the block, and return true if the block has an error.
492 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
494 bool ReadBlockEnd() {
495 if (BlockScope.empty()) return true;
498 // [END_BLOCK, <align4bytes>]
499 SkipToFourByteBoundary();
507 void popBlockScope() {
508 CurCodeSize = BlockScope.back().PrevCodeSize;
510 CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
511 BlockScope.pop_back();
514 //===--------------------------------------------------------------------===//
516 //===--------------------------------------------------------------------===//
519 void readAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
520 SmallVectorImpl<uint64_t> &Vals);
521 void readAbbreviatedField(const BitCodeAbbrevOp &Op,
522 SmallVectorImpl<uint64_t> &Vals);
523 void skipAbbreviatedField(const BitCodeAbbrevOp &Op);
527 /// getAbbrev - Return the abbreviation for the specified AbbrevId.
528 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
529 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
530 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
531 return CurAbbrevs[AbbrevNo].get();
534 /// skipRecord - Read the current record and discard it.
535 void skipRecord(unsigned AbbrevID);
537 unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
538 StringRef *Blob = nullptr);
540 //===--------------------------------------------------------------------===//
542 //===--------------------------------------------------------------------===//
543 void ReadAbbrevRecord();
545 bool ReadBlockInfoBlock();
548 } // End llvm namespace