Don't repeat names in comments. NFC.
[oota-llvm.git] / include / llvm / Bitcode / BitstreamReader.h
1 //===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the BitstreamReader class.  This class can be used to
11 // read an arbitrary bitstream, regardless of its contents.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_BITCODE_BITSTREAMREADER_H
16 #define LLVM_BITCODE_BITSTREAMREADER_H
17
18 #include "llvm/Bitcode/BitCodes.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/StreamableMemoryObject.h"
21 #include <climits>
22 #include <string>
23 #include <vector>
24
25 namespace llvm {
26
27 class Deserializer;
28
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 {
34 public:
35   /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
36   /// describe abbreviations that all blocks of the specified ID inherit.
37   struct BlockInfo {
38     unsigned BlockID;
39     std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> Abbrevs;
40     std::string Name;
41
42     std::vector<std::pair<unsigned, std::string> > RecordNames;
43   };
44 private:
45   std::unique_ptr<StreamableMemoryObject> BitcodeBytes;
46
47   std::vector<BlockInfo> BlockInfoRecords;
48
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;
52
53   BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
54   void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
55 public:
56   BitstreamReader() : IgnoreBlockInfoNames(true) {
57   }
58
59   BitstreamReader(const unsigned char *Start, const unsigned char *End)
60       : IgnoreBlockInfoNames(true) {
61     init(Start, End);
62   }
63
64   BitstreamReader(StreamableMemoryObject *bytes) : IgnoreBlockInfoNames(true) {
65     BitcodeBytes.reset(bytes);
66   }
67
68   BitstreamReader(BitstreamReader &&Other) {
69     *this = std::move(Other);
70   }
71
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;
77     return *this;
78   }
79
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));
83   }
84
85   StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
86
87   /// This is called by clients that want block/record name information.
88   void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
89   bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
90
91   //===--------------------------------------------------------------------===//
92   // Block Manipulation
93   //===--------------------------------------------------------------------===//
94
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
97   /// it.
98   bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
99
100   /// If there is block info for the specified ID, return it, otherwise return
101   /// null.
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();
106
107     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
108          i != e; ++i)
109       if (BlockInfoRecords[i].BlockID == BlockID)
110         return &BlockInfoRecords[i];
111     return nullptr;
112   }
113
114   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
115     if (const BlockInfo *BI = getBlockInfo(BlockID))
116       return *const_cast<BlockInfo*>(BI);
117
118     // Otherwise, add a new record.
119     BlockInfoRecords.push_back(BlockInfo());
120     BlockInfoRecords.back().BlockID = BlockID;
121     return BlockInfoRecords.back();
122   }
123
124   /// Takes block info from the other bitstream reader.
125   ///
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);
131   }
132 };
133
134 /// When advancing through a bitstream cursor, each advance can discover a few
135 /// different kinds of entries:
136 struct BitstreamEntry {
137   enum {
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.
143   } Kind;
144
145   unsigned ID;
146
147   static BitstreamEntry getError() {
148     BitstreamEntry E; E.Kind = Error; return E;
149   }
150   static BitstreamEntry getEndBlock() {
151     BitstreamEntry E; E.Kind = EndBlock; return E;
152   }
153   static BitstreamEntry getSubBlock(unsigned ID) {
154     BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
155   }
156   static BitstreamEntry getRecord(unsigned AbbrevID) {
157     BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
158   }
159 };
160
161 /// This represents a position within a bitcode file. There may be multiple
162 /// independent cursors reading within one bitstream, each maintaining their own
163 /// local state.
164 ///
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;
170   size_t NextChar;
171
172   /// This is the current data we have pulled from the stream but have not
173   /// returned to the client. This is specifically and intentionally defined to
174   /// follow the word size of the host machine for efficiency. We use word_t in
175   /// places that are aware of this to make it perfectly explicit what is going
176   /// on.
177   typedef uint32_t word_t;
178   word_t CurWord;
179
180   /// This is the number of bits in CurWord that are valid. This is always from
181   /// [0...31/63] inclusive (depending on word size).
182   unsigned BitsInCurWord;
183
184   // This is the declared size of code values used for the current block, in
185   // bits.
186   unsigned CurCodeSize;
187
188   /// Abbrevs installed at in this block.
189   std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> CurAbbrevs;
190
191   struct Block {
192     unsigned PrevCodeSize;
193     std::vector<IntrusiveRefCntPtr<BitCodeAbbrev>> PrevAbbrevs;
194     explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
195   };
196
197   /// This tracks the codesize of parent blocks.
198   SmallVector<Block, 8> BlockScope;
199
200
201 public:
202   BitstreamCursor() : BitStream(nullptr), NextChar(0) {}
203
204   explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
205     NextChar = 0;
206     CurWord = 0;
207     BitsInCurWord = 0;
208     CurCodeSize = 2;
209   }
210
211   void init(BitstreamReader &R) {
212     freeState();
213
214     BitStream = &R;
215     NextChar = 0;
216     CurWord = 0;
217     BitsInCurWord = 0;
218     CurCodeSize = 2;
219   }
220
221   void freeState();
222
223   bool isEndPos(size_t pos) {
224     return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
225   }
226
227   bool canSkipToPos(size_t pos) const {
228     // pos can be skipped to if it is a valid address or one byte past the end.
229     return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
230         static_cast<uint64_t>(pos - 1));
231   }
232
233   uint32_t getWord(size_t pos) {
234     uint8_t buf[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
235     BitStream->getBitcodeBytes().readBytes(pos, sizeof(buf), buf);
236     return *reinterpret_cast<support::ulittle32_t *>(buf);
237   }
238
239   bool AtEndOfStream() {
240     return BitsInCurWord == 0 && isEndPos(NextChar);
241   }
242
243   /// Return the number of bits used to encode an abbrev #.
244   unsigned getAbbrevIDWidth() const { return CurCodeSize; }
245
246   /// Return the bit # of the bit we are reading.
247   uint64_t GetCurrentBitNo() const {
248     return NextChar*CHAR_BIT - BitsInCurWord;
249   }
250
251   BitstreamReader *getBitStreamReader() {
252     return BitStream;
253   }
254   const BitstreamReader *getBitStreamReader() const {
255     return BitStream;
256   }
257
258   /// Flags that modify the behavior of advance().
259   enum {
260     /// If this flag is used, the advance() method does not automatically pop
261     /// the block scope when the end of a block is reached.
262     AF_DontPopBlockAtEnd = 1,
263
264     /// If this flag is used, abbrev entries are returned just like normal
265     /// records.
266     AF_DontAutoprocessAbbrevs = 2
267   };
268
269       /// Advance the current bitstream, returning the next entry in the stream.
270       BitstreamEntry advance(unsigned Flags = 0) {
271     while (1) {
272       unsigned Code = ReadCode();
273       if (Code == bitc::END_BLOCK) {
274         // Pop the end of the block unless Flags tells us not to.
275         if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
276           return BitstreamEntry::getError();
277         return BitstreamEntry::getEndBlock();
278       }
279
280       if (Code == bitc::ENTER_SUBBLOCK)
281         return BitstreamEntry::getSubBlock(ReadSubBlockID());
282
283       if (Code == bitc::DEFINE_ABBREV &&
284           !(Flags & AF_DontAutoprocessAbbrevs)) {
285         // We read and accumulate abbrev's, the client can't do anything with
286         // them anyway.
287         ReadAbbrevRecord();
288         continue;
289       }
290
291       return BitstreamEntry::getRecord(Code);
292     }
293   }
294
295   /// This is a convenience function for clients that don't expect any
296   /// subblocks. This just skips over them automatically.
297   BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
298     while (1) {
299       // If we found a normal entry, return it.
300       BitstreamEntry Entry = advance(Flags);
301       if (Entry.Kind != BitstreamEntry::SubBlock)
302         return Entry;
303
304       // If we found a sub-block, just skip over it and check the next entry.
305       if (SkipBlock())
306         return BitstreamEntry::getError();
307     }
308   }
309
310   /// Reset the stream to the specified bit number.
311   void JumpToBit(uint64_t BitNo) {
312     uintptr_t ByteNo = uintptr_t(BitNo/8) & ~(sizeof(word_t)-1);
313     unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
314     assert(canSkipToPos(ByteNo) && "Invalid location");
315
316     // Move the cursor to the right word.
317     NextChar = ByteNo;
318     BitsInCurWord = 0;
319     CurWord = 0;
320
321     // Skip over any bits that are already consumed.
322     if (WordBitNo) {
323       if (sizeof(word_t) > 4)
324         Read64(WordBitNo);
325       else
326         Read(WordBitNo);
327     }
328   }
329
330
331   uint32_t Read(unsigned NumBits) {
332     assert(NumBits && NumBits <= 32 &&
333            "Cannot return zero or more than 32 bits!");
334
335     // If the field is fully contained by CurWord, return it quickly.
336     if (BitsInCurWord >= NumBits) {
337       uint32_t R = uint32_t(CurWord) & (~0U >> (32-NumBits));
338       CurWord >>= NumBits;
339       BitsInCurWord -= NumBits;
340       return R;
341     }
342
343     // If we run out of data, stop at the end of the stream.
344     if (isEndPos(NextChar)) {
345       CurWord = 0;
346       BitsInCurWord = 0;
347       return 0;
348     }
349
350     uint32_t R = uint32_t(CurWord);
351
352     // Read the next word from the stream.
353     uint8_t Array[sizeof(word_t)] = {0};
354
355     BitStream->getBitcodeBytes().readBytes(NextChar, sizeof(Array), Array);
356
357     // Handle big-endian byte-swapping if necessary.
358     support::detail::packed_endian_specific_integral
359       <word_t, support::little, support::unaligned> EndianValue;
360     memcpy(&EndianValue, Array, sizeof(Array));
361
362     CurWord = EndianValue;
363
364     NextChar += sizeof(word_t);
365
366     // Extract NumBits-BitsInCurWord from what we just read.
367     unsigned BitsLeft = NumBits-BitsInCurWord;
368
369     // Be careful here, BitsLeft is in the range [1..32]/[1..64] inclusive.
370     R |= uint32_t((CurWord & (word_t(~0ULL) >> (sizeof(word_t)*8-BitsLeft)))
371                     << BitsInCurWord);
372
373     // BitsLeft bits have just been used up from CurWord.  BitsLeft is in the
374     // range [1..32]/[1..64] so be careful how we shift.
375     if (BitsLeft != sizeof(word_t)*8)
376       CurWord >>= BitsLeft;
377     else
378       CurWord = 0;
379     BitsInCurWord = sizeof(word_t)*8-BitsLeft;
380     return R;
381   }
382
383   uint64_t Read64(unsigned NumBits) {
384     if (NumBits <= 32) return Read(NumBits);
385
386     uint64_t V = Read(32);
387     return V | (uint64_t)Read(NumBits-32) << 32;
388   }
389
390   uint32_t ReadVBR(unsigned NumBits) {
391     uint32_t Piece = Read(NumBits);
392     if ((Piece & (1U << (NumBits-1))) == 0)
393       return Piece;
394
395     uint32_t Result = 0;
396     unsigned NextBit = 0;
397     while (1) {
398       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
399
400       if ((Piece & (1U << (NumBits-1))) == 0)
401         return Result;
402
403       NextBit += NumBits-1;
404       Piece = Read(NumBits);
405     }
406   }
407
408   // Read a VBR that may have a value up to 64-bits in size. The chunk size of
409   // the VBR must still be <= 32 bits though.
410   uint64_t ReadVBR64(unsigned NumBits) {
411     uint32_t Piece = Read(NumBits);
412     if ((Piece & (1U << (NumBits-1))) == 0)
413       return uint64_t(Piece);
414
415     uint64_t Result = 0;
416     unsigned NextBit = 0;
417     while (1) {
418       Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
419
420       if ((Piece & (1U << (NumBits-1))) == 0)
421         return Result;
422
423       NextBit += NumBits-1;
424       Piece = Read(NumBits);
425     }
426   }
427
428 private:
429   void SkipToFourByteBoundary() {
430     // If word_t is 64-bits and if we've read less than 32 bits, just dump
431     // the bits we have up to the next 32-bit boundary.
432     if (sizeof(word_t) > 4 &&
433         BitsInCurWord >= 32) {
434       CurWord >>= BitsInCurWord-32;
435       BitsInCurWord = 32;
436       return;
437     }
438
439     BitsInCurWord = 0;
440     CurWord = 0;
441   }
442 public:
443
444   unsigned ReadCode() {
445     return Read(CurCodeSize);
446   }
447
448
449   // Block header:
450   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
451
452   /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
453   unsigned ReadSubBlockID() {
454     return ReadVBR(bitc::BlockIDWidth);
455   }
456
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.
459   bool SkipBlock() {
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);
465
466     // Check that the block wasn't partially defined, and that the offset isn't
467     // bogus.
468     size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
469     if (AtEndOfStream() || !canSkipToPos(SkipTo/8))
470       return true;
471
472     JumpToBit(SkipTo);
473     return false;
474   }
475
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);
479
480   bool ReadBlockEnd() {
481     if (BlockScope.empty()) return true;
482
483     // Block tail:
484     //    [END_BLOCK, <align4bytes>]
485     SkipToFourByteBoundary();
486
487     popBlockScope();
488     return false;
489   }
490
491 private:
492
493   void popBlockScope() {
494     CurCodeSize = BlockScope.back().PrevCodeSize;
495
496     CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
497     BlockScope.pop_back();
498   }
499
500   //===--------------------------------------------------------------------===//
501   // Record Processing
502   //===--------------------------------------------------------------------===//
503
504 private:
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);
510
511 public:
512
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();
518   }
519
520   /// Read the current record and discard it.
521   void skipRecord(unsigned AbbrevID);
522
523   unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
524                       StringRef *Blob = nullptr);
525
526   //===--------------------------------------------------------------------===//
527   // Abbrev Processing
528   //===--------------------------------------------------------------------===//
529   void ReadAbbrevRecord();
530
531   bool ReadBlockInfoBlock();
532 };
533
534 } // End llvm namespace
535
536 #endif