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/StreamingMemoryObject.h"
29 /// This class is used to read from an LLVM bitcode stream, maintaining
30 /// information that is global to decoding the entire file. While a file is
31 /// being read, multiple cursors can be independently advanced or skipped around
32 /// within the file. These are represented by the BitstreamCursor class.
33 class BitstreamReader {
35 /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
36 /// describe abbreviations that all blocks of the specified ID inherit.
39 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
42 std::vector<std::pair<unsigned, std::string> > RecordNames;
45 std::unique_ptr<MemoryObject> BitcodeBytes;
47 std::vector<BlockInfo> BlockInfoRecords;
49 /// This is set to true if we don't care about the block/record name
50 /// information in the BlockInfo block. Only llvm-bcanalyzer uses this.
51 bool IgnoreBlockInfoNames;
53 BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
54 void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
56 BitstreamReader() : IgnoreBlockInfoNames(true) {
59 BitstreamReader(const unsigned char *Start, const unsigned char *End)
60 : IgnoreBlockInfoNames(true) {
64 BitstreamReader(MemoryObject *bytes) : IgnoreBlockInfoNames(true) {
65 BitcodeBytes.reset(bytes);
68 BitstreamReader(BitstreamReader &&Other) {
69 *this = std::move(Other);
72 BitstreamReader &operator=(BitstreamReader &&Other) {
73 BitcodeBytes = std::move(Other.BitcodeBytes);
74 // Explicitly swap block info, so that nothing gets destroyed twice.
75 std::swap(BlockInfoRecords, Other.BlockInfoRecords);
76 IgnoreBlockInfoNames = Other.IgnoreBlockInfoNames;
80 void init(const unsigned char *Start, const unsigned char *End) {
81 assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
82 BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
85 MemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
87 /// This is called by clients that want block/record name information.
88 void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
89 bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
91 //===--------------------------------------------------------------------===//
93 //===--------------------------------------------------------------------===//
95 /// Return true if we've already read and processed the block info block for
96 /// this Bitstream. We only process it for the first cursor that walks over
98 bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
100 /// If there is block info for the specified ID, return it, otherwise return
102 const BlockInfo *getBlockInfo(unsigned BlockID) const {
103 // Common case, the most recent entry matches BlockID.
104 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
105 return &BlockInfoRecords.back();
107 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
109 if (BlockInfoRecords[i].BlockID == BlockID)
110 return &BlockInfoRecords[i];
114 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
115 if (const BlockInfo *BI = getBlockInfo(BlockID))
116 return *const_cast<BlockInfo*>(BI);
118 // Otherwise, add a new record.
119 BlockInfoRecords.push_back(BlockInfo());
120 BlockInfoRecords.back().BlockID = BlockID;
121 return BlockInfoRecords.back();
124 /// Takes block info from the other bitstream reader.
126 /// This is a "take" operation because BlockInfo records are non-trivial, and
127 /// indeed rather expensive.
128 void takeBlockInfo(BitstreamReader &&Other) {
129 assert(!hasBlockInfoRecords());
130 BlockInfoRecords = std::move(Other.BlockInfoRecords);
134 /// When advancing through a bitstream cursor, each advance can discover a few
135 /// different kinds of entries:
136 struct BitstreamEntry {
138 Error, // Malformed bitcode was found.
139 EndBlock, // We've reached the end of the current block, (or the end of the
140 // file, which is treated like a series of EndBlock records.
141 SubBlock, // This is the start of a new subblock of a specific ID.
142 Record // This is a record with a specific AbbrevID.
147 static BitstreamEntry getError() {
148 BitstreamEntry E; E.Kind = Error; return E;
150 static BitstreamEntry getEndBlock() {
151 BitstreamEntry E; E.Kind = EndBlock; return E;
153 static BitstreamEntry getSubBlock(unsigned ID) {
154 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
156 static BitstreamEntry getRecord(unsigned AbbrevID) {
157 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
161 /// This represents a position within a bitcode file. There may be multiple
162 /// independent cursors reading within one bitstream, each maintaining their own
165 /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
166 /// be passed by value.
167 class BitstreamCursor {
168 friend class Deserializer;
169 BitstreamReader *BitStream;
172 // The size of the bicode. 0 if we don't know it yet.
175 /// This is the current data we have pulled from the stream but have not
176 /// returned to the client. This is specifically and intentionally defined to
177 /// follow the word size of the host machine for efficiency. We use word_t in
178 /// places that are aware of this to make it perfectly explicit what is going
180 typedef uint32_t word_t;
183 /// This is the number of bits in CurWord that are valid. This is always from
184 /// [0...31/63] inclusive (depending on word size).
185 unsigned BitsInCurWord;
187 // This is the declared size of code values used for the current block, in
189 unsigned CurCodeSize;
191 /// Abbrevs installed at in this block.
192 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
195 unsigned PrevCodeSize;
196 std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
197 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
200 /// This tracks the codesize of parent blocks.
201 SmallVector<Block, 8> BlockScope;
205 BitstreamCursor() { init(nullptr); }
207 explicit BitstreamCursor(BitstreamReader &R) { init(&R); }
209 void init(BitstreamReader *R) {
221 bool canSkipToPos(size_t pos) const {
222 // pos can be skipped to if it is a valid address or one byte past the end.
223 return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
224 static_cast<uint64_t>(pos - 1));
227 bool AtEndOfStream() {
228 if (BitsInCurWord != 0)
230 if (Size != 0 && Size == NextChar)
233 return BitsInCurWord == 0;
236 /// Return the number of bits used to encode an abbrev #.
237 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
239 /// Return the bit # of the bit we are reading.
240 uint64_t GetCurrentBitNo() const {
241 return NextChar*CHAR_BIT - BitsInCurWord;
244 BitstreamReader *getBitStreamReader() {
247 const BitstreamReader *getBitStreamReader() const {
251 /// Flags that modify the behavior of advance().
253 /// If this flag is used, the advance() method does not automatically pop
254 /// the block scope when the end of a block is reached.
255 AF_DontPopBlockAtEnd = 1,
257 /// If this flag is used, abbrev entries are returned just like normal
259 AF_DontAutoprocessAbbrevs = 2
262 /// Advance the current bitstream, returning the next entry in the stream.
263 BitstreamEntry advance(unsigned Flags = 0) {
265 unsigned Code = ReadCode();
266 if (Code == bitc::END_BLOCK) {
267 // Pop the end of the block unless Flags tells us not to.
268 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
269 return BitstreamEntry::getError();
270 return BitstreamEntry::getEndBlock();
273 if (Code == bitc::ENTER_SUBBLOCK)
274 return BitstreamEntry::getSubBlock(ReadSubBlockID());
276 if (Code == bitc::DEFINE_ABBREV &&
277 !(Flags & AF_DontAutoprocessAbbrevs)) {
278 // We read and accumulate abbrev's, the client can't do anything with
284 return BitstreamEntry::getRecord(Code);
288 /// This is a convenience function for clients that don't expect any
289 /// subblocks. This just skips over them automatically.
290 BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
292 // If we found a normal entry, return it.
293 BitstreamEntry Entry = advance(Flags);
294 if (Entry.Kind != BitstreamEntry::SubBlock)
297 // If we found a sub-block, just skip over it and check the next entry.
299 return BitstreamEntry::getError();
303 /// Reset the stream to the specified bit number.
304 void JumpToBit(uint64_t BitNo) {
305 uintptr_t ByteNo = uintptr_t(BitNo/8) & ~(sizeof(word_t)-1);
306 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
307 assert(canSkipToPos(ByteNo) && "Invalid location");
309 // Move the cursor to the right word.
313 // Skip over any bits that are already consumed.
315 if (sizeof(word_t) > 4)
323 assert(Size == 0 || NextChar < (unsigned)Size);
325 // Read the next word from the stream.
326 uint8_t Array[sizeof(word_t)] = {0};
329 BitStream->getBitcodeBytes().readBytes(Array, sizeof(Array), NextChar);
331 // If we run out of data, stop at the end of the stream.
332 if (BytesRead == 0) {
336 assert(BytesRead == sizeof(Array));
338 // Handle big-endian byte-swapping if necessary.
339 support::detail::packed_endian_specific_integral<
340 word_t, support::little, support::unaligned> EndianValue;
341 memcpy(&EndianValue, Array, sizeof(Array));
343 CurWord = EndianValue;
344 NextChar += sizeof(word_t);
345 BitsInCurWord = sizeof(word_t) * 8;
348 uint32_t Read(unsigned NumBits) {
349 assert(NumBits && NumBits <= 32 &&
350 "Cannot return zero or more than 32 bits!");
352 // If the field is fully contained by CurWord, return it quickly.
353 if (BitsInCurWord >= NumBits) {
354 uint32_t R = uint32_t(CurWord) & (~0U >> (32-NumBits));
356 // Use a mask to avoid undefined behavior.
357 CurWord >>= (NumBits & 0x1f);
359 BitsInCurWord -= NumBits;
363 uint32_t R = BitsInCurWord ? uint32_t(CurWord) : 0;
364 unsigned BitsLeft = NumBits - BitsInCurWord;
368 // If we run out of data, stop at the end of the stream.
369 if (BitsLeft > BitsInCurWord)
372 uint32_t R2 = uint32_t(CurWord) & (~0U >> (sizeof(word_t) * 8 - BitsLeft));
374 // Use a mask to avoid undefined behavior.
375 CurWord >>= (BitsLeft & 0x1f);
377 BitsInCurWord -= BitsLeft;
379 R |= uint32_t(R2 << (NumBits - BitsLeft));
384 uint64_t Read64(unsigned NumBits) {
385 if (NumBits <= 32) return Read(NumBits);
387 uint64_t V = Read(32);
388 return V | (uint64_t)Read(NumBits-32) << 32;
391 uint32_t ReadVBR(unsigned NumBits) {
392 uint32_t Piece = Read(NumBits);
393 if ((Piece & (1U << (NumBits-1))) == 0)
397 unsigned NextBit = 0;
399 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
401 if ((Piece & (1U << (NumBits-1))) == 0)
404 NextBit += NumBits-1;
405 Piece = Read(NumBits);
409 // Read a VBR that may have a value up to 64-bits in size. The chunk size of
410 // the VBR must still be <= 32 bits though.
411 uint64_t ReadVBR64(unsigned NumBits) {
412 uint32_t Piece = Read(NumBits);
413 if ((Piece & (1U << (NumBits-1))) == 0)
414 return uint64_t(Piece);
417 unsigned NextBit = 0;
419 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
421 if ((Piece & (1U << (NumBits-1))) == 0)
424 NextBit += NumBits-1;
425 Piece = Read(NumBits);
430 void SkipToFourByteBoundary() {
431 // If word_t is 64-bits and if we've read less than 32 bits, just dump
432 // the bits we have up to the next 32-bit boundary.
433 if (sizeof(word_t) > 4 &&
434 BitsInCurWord >= 32) {
435 CurWord >>= BitsInCurWord-32;
444 unsigned ReadCode() {
445 return Read(CurCodeSize);
450 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
452 /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
453 unsigned ReadSubBlockID() {
454 return ReadVBR(bitc::BlockIDWidth);
457 /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
458 /// of this block. If the block record is malformed, return true.
460 // Read and ignore the codelen value. Since we are skipping this block, we
461 // don't care what code widths are used inside of it.
462 ReadVBR(bitc::CodeLenWidth);
463 SkipToFourByteBoundary();
464 unsigned NumFourBytes = Read(bitc::BlockSizeWidth);
466 // Check that the block wasn't partially defined, and that the offset isn't
468 size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
469 if (AtEndOfStream() || !canSkipToPos(SkipTo/8))
476 /// Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true
477 /// if the block has an error.
478 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
480 bool ReadBlockEnd() {
481 if (BlockScope.empty()) return true;
484 // [END_BLOCK, <align4bytes>]
485 SkipToFourByteBoundary();
493 void popBlockScope() {
494 CurCodeSize = BlockScope.back().PrevCodeSize;
496 CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
497 BlockScope.pop_back();
500 //===--------------------------------------------------------------------===//
502 //===--------------------------------------------------------------------===//
505 void readAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
506 SmallVectorImpl<uint64_t> &Vals);
507 void readAbbreviatedField(const BitCodeAbbrevOp &Op,
508 SmallVectorImpl<uint64_t> &Vals);
509 void skipAbbreviatedField(const BitCodeAbbrevOp &Op);
513 /// Return the abbreviation for the specified AbbrevId.
514 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
515 unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
516 assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
517 return CurAbbrevs[AbbrevNo].get();
520 /// Read the current record and discard it.
521 void skipRecord(unsigned AbbrevID);
523 unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
524 StringRef *Blob = nullptr);
526 //===--------------------------------------------------------------------===//
528 //===--------------------------------------------------------------------===//
529 void ReadAbbrevRecord();
531 bool ReadBlockInfoBlock();
534 } // End llvm namespace