move some private methods out of line, add a skipRecord() method.
[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/ADT/OwningPtr.h"
19 #include "llvm/Bitcode/BitCodes.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/StreamableMemoryObject.h"
22 #include <climits>
23 #include <string>
24 #include <vector>
25
26 namespace llvm {
27
28   class Deserializer;
29
30 /// BitstreamReader - This class is used to read from an LLVM bitcode stream,
31 /// maintaining information that is global to decoding the entire file.  While
32 /// a file is being read, multiple cursors can be independently advanced or
33 /// skipped around within the file.  These are represented by the
34 /// BitstreamCursor class.
35 class BitstreamReader {
36 public:
37   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
38   /// These describe abbreviations that all blocks of the specified ID inherit.
39   struct BlockInfo {
40     unsigned BlockID;
41     std::vector<BitCodeAbbrev*> Abbrevs;
42     std::string Name;
43
44     std::vector<std::pair<unsigned, std::string> > RecordNames;
45   };
46 private:
47   OwningPtr<StreamableMemoryObject> BitcodeBytes;
48
49   std::vector<BlockInfo> BlockInfoRecords;
50
51   /// IgnoreBlockInfoNames - This is set to true if we don't care about the
52   /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
53   /// uses this.
54   bool IgnoreBlockInfoNames;
55
56   BitstreamReader(const BitstreamReader&) LLVM_DELETED_FUNCTION;
57   void operator=(const BitstreamReader&) LLVM_DELETED_FUNCTION;
58 public:
59   BitstreamReader() : IgnoreBlockInfoNames(true) {
60   }
61
62   BitstreamReader(const unsigned char *Start, const unsigned char *End) {
63     IgnoreBlockInfoNames = true;
64     init(Start, End);
65   }
66
67   BitstreamReader(StreamableMemoryObject *bytes) {
68     BitcodeBytes.reset(bytes);
69   }
70
71   void init(const unsigned char *Start, const unsigned char *End) {
72     assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
73     BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
74   }
75
76   StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
77
78   ~BitstreamReader() {
79     // Free the BlockInfoRecords.
80     while (!BlockInfoRecords.empty()) {
81       BlockInfo &Info = BlockInfoRecords.back();
82       // Free blockinfo abbrev info.
83       for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
84            i != e; ++i)
85         Info.Abbrevs[i]->dropRef();
86       BlockInfoRecords.pop_back();
87     }
88   }
89
90   /// CollectBlockInfoNames - This is called by clients that want block/record
91   /// name information.
92   void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
93   bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
94
95   //===--------------------------------------------------------------------===//
96   // Block Manipulation
97   //===--------------------------------------------------------------------===//
98
99   /// hasBlockInfoRecords - Return true if we've already read and processed the
100   /// block info block for this Bitstream.  We only process it for the first
101   /// cursor that walks over it.
102   bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
103
104   /// getBlockInfo - If there is block info for the specified ID, return it,
105   /// otherwise return null.
106   const BlockInfo *getBlockInfo(unsigned BlockID) const {
107     // Common case, the most recent entry matches BlockID.
108     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
109       return &BlockInfoRecords.back();
110
111     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
112          i != e; ++i)
113       if (BlockInfoRecords[i].BlockID == BlockID)
114         return &BlockInfoRecords[i];
115     return 0;
116   }
117
118   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
119     if (const BlockInfo *BI = getBlockInfo(BlockID))
120       return *const_cast<BlockInfo*>(BI);
121
122     // Otherwise, add a new record.
123     BlockInfoRecords.push_back(BlockInfo());
124     BlockInfoRecords.back().BlockID = BlockID;
125     return BlockInfoRecords.back();
126   }
127 };
128
129   
130 /// BitstreamEntry - When advancing through a bitstream cursor, each advance can
131 /// discover a few different kinds of entries:
132 ///   Error    - Malformed bitcode was found.
133 ///   EndBlock - We've reached the end of the current block, (or the end of the
134 ///              file, which is treated like a series of EndBlock records.
135 ///   SubBlock - This is the start of a new subblock of a specific ID.
136 ///   Record   - This is a record with a specific AbbrevID.
137 ///
138 struct BitstreamEntry {
139   enum {
140     Error,
141     EndBlock,
142     SubBlock,
143     Record
144   } Kind;
145   
146   unsigned ID;
147
148   static BitstreamEntry getError() {
149     BitstreamEntry E; E.Kind = Error; return E;
150   }
151   static BitstreamEntry getEndBlock() {
152     BitstreamEntry E; E.Kind = EndBlock; return E;
153   }
154   static BitstreamEntry getSubBlock(unsigned ID) {
155     BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
156   }
157   static BitstreamEntry getRecord(unsigned AbbrevID) {
158     BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
159   }
160 };
161
162
163 /// BitstreamCursor - This represents a position within a bitcode file.  There
164 /// may be multiple independent cursors reading within one bitstream, each
165 /// maintaining their own local state.
166 ///
167 /// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
168 /// be passed by value.
169 class BitstreamCursor {
170   friend class Deserializer;
171   BitstreamReader *BitStream;
172   size_t NextChar;
173
174   /// CurWord - This is the current data we have pulled from the stream but have
175   /// not returned to the client.
176   uint32_t CurWord;
177
178   /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
179   /// is always from [0...31] inclusive.
180   unsigned BitsInCurWord;
181
182   // CurCodeSize - This is the declared size of code values used for the current
183   // block, in bits.
184   unsigned CurCodeSize;
185
186   /// CurAbbrevs - Abbrevs installed at in this block.
187   std::vector<BitCodeAbbrev*> CurAbbrevs;
188
189   struct Block {
190     unsigned PrevCodeSize;
191     std::vector<BitCodeAbbrev*> PrevAbbrevs;
192     explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
193   };
194
195   /// BlockScope - This tracks the codesize of parent blocks.
196   SmallVector<Block, 8> BlockScope;
197
198   
199 public:
200   BitstreamCursor() : BitStream(0), NextChar(0) {
201   }
202   BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
203     operator=(RHS);
204   }
205
206   explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
207     NextChar = 0;
208     CurWord = 0;
209     BitsInCurWord = 0;
210     CurCodeSize = 2;
211   }
212
213   void init(BitstreamReader &R) {
214     freeState();
215
216     BitStream = &R;
217     NextChar = 0;
218     CurWord = 0;
219     BitsInCurWord = 0;
220     CurCodeSize = 2;
221   }
222
223   ~BitstreamCursor() {
224     freeState();
225   }
226
227   void operator=(const BitstreamCursor &RHS);
228
229   void freeState();
230   
231   bool isEndPos(size_t pos) {
232     return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
233   }
234
235   bool canSkipToPos(size_t pos) const {
236     // pos can be skipped to if it is a valid address or one byte past the end.
237     return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
238         static_cast<uint64_t>(pos - 1));
239   }
240
241   unsigned char getByte(size_t pos) {
242     uint8_t byte = -1;
243     BitStream->getBitcodeBytes().readByte(pos, &byte);
244     return byte;
245   }
246
247   uint32_t getWord(size_t pos) {
248     uint8_t buf[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
249     BitStream->getBitcodeBytes().readBytes(pos, sizeof(buf), buf, NULL);
250     return *reinterpret_cast<support::ulittle32_t *>(buf);
251   }
252
253   bool AtEndOfStream() {
254     return isEndPos(NextChar) && BitsInCurWord == 0;
255   }
256
257   /// getAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
258   unsigned getAbbrevIDWidth() const { return CurCodeSize; }
259
260   /// GetCurrentBitNo - Return the bit # of the bit we are reading.
261   uint64_t GetCurrentBitNo() const {
262     return NextChar*CHAR_BIT - BitsInCurWord;
263   }
264
265   BitstreamReader *getBitStreamReader() {
266     return BitStream;
267   }
268   const BitstreamReader *getBitStreamReader() const {
269     return BitStream;
270   }
271
272   /// Flags that modify the behavior of advance().
273   enum {
274     AF_DontPopBlockAtEnd = 1
275   };
276   
277   /// advance - Advance the current bitstream, returning the next entry in the
278   /// stream.
279   BitstreamEntry advance(unsigned Flags = 0) {
280     while (1) {
281       unsigned Code = ReadCode();
282       if (Code == bitc::END_BLOCK) {
283         // Pop the end of the block unless Flags tells us not to.
284         if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
285           return BitstreamEntry::getError();
286         return BitstreamEntry::getEndBlock();
287       }
288       
289       if (Code == bitc::ENTER_SUBBLOCK)
290         return BitstreamEntry::getSubBlock(ReadSubBlockID());
291       
292       if (Code == bitc::DEFINE_ABBREV) {
293         // We read and accumulate abbrev's, the client can't do anything with
294         // them anyway.
295         ReadAbbrevRecord();
296         continue;
297       }
298
299       return BitstreamEntry::getRecord(Code);
300     }
301   }
302
303   /// advanceSkippingSubblocks - This is a convenience function for clients that
304   /// don't expect any subblocks.  This just skips over them automatically.
305   BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
306     while (1) {
307       // If we found a normal entry, return it.
308       BitstreamEntry Entry = advance(Flags);
309       if (Entry.Kind != BitstreamEntry::SubBlock)
310         return Entry;
311       
312       // If we found a sub-block, just skip over it and check the next entry.
313       if (SkipBlock())
314         return BitstreamEntry::getError();
315     }
316   }
317
318   /// JumpToBit - Reset the stream to the specified bit number.
319   void JumpToBit(uint64_t BitNo) {
320     uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
321     uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
322     assert(canSkipToPos(ByteNo) && "Invalid location");
323
324     // Move the cursor to the right word.
325     NextChar = ByteNo;
326     BitsInCurWord = 0;
327     CurWord = 0;
328
329     // Skip over any bits that are already consumed.
330     if (WordBitNo)
331       Read(static_cast<unsigned>(WordBitNo));
332   }
333
334
335   uint32_t Read(unsigned NumBits) {
336     assert(NumBits <= 32 && "Cannot return more than 32 bits!");
337     // If the field is fully contained by CurWord, return it quickly.
338     if (BitsInCurWord >= NumBits) {
339       uint32_t R = CurWord & ((1U << NumBits)-1);
340       CurWord >>= NumBits;
341       BitsInCurWord -= NumBits;
342       return R;
343     }
344
345     // If we run out of data, stop at the end of the stream.
346     if (isEndPos(NextChar)) {
347       CurWord = 0;
348       BitsInCurWord = 0;
349       return 0;
350     }
351
352     unsigned R = CurWord;
353
354     // Read the next word from the stream.
355     CurWord = getWord(NextChar);
356     NextChar += 4;
357
358     // Extract NumBits-BitsInCurWord from what we just read.
359     unsigned BitsLeft = NumBits-BitsInCurWord;
360
361     // Be careful here, BitsLeft is in the range [1..32] inclusive.
362     R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
363
364     // BitsLeft bits have just been used up from CurWord.
365     if (BitsLeft != 32)
366       CurWord >>= BitsLeft;
367     else
368       CurWord = 0;
369     BitsInCurWord = 32-BitsLeft;
370     return R;
371   }
372
373   uint64_t Read64(unsigned NumBits) {
374     if (NumBits <= 32) return Read(NumBits);
375
376     uint64_t V = Read(32);
377     return V | (uint64_t)Read(NumBits-32) << 32;
378   }
379
380   uint32_t ReadVBR(unsigned NumBits) {
381     uint32_t Piece = Read(NumBits);
382     if ((Piece & (1U << (NumBits-1))) == 0)
383       return Piece;
384
385     uint32_t Result = 0;
386     unsigned NextBit = 0;
387     while (1) {
388       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
389
390       if ((Piece & (1U << (NumBits-1))) == 0)
391         return Result;
392
393       NextBit += NumBits-1;
394       Piece = Read(NumBits);
395     }
396   }
397
398   // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size.  The
399   // chunk size of the VBR must still be <= 32 bits though.
400   uint64_t ReadVBR64(unsigned NumBits) {
401     uint32_t Piece = Read(NumBits);
402     if ((Piece & (1U << (NumBits-1))) == 0)
403       return uint64_t(Piece);
404
405     uint64_t Result = 0;
406     unsigned NextBit = 0;
407     while (1) {
408       Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
409
410       if ((Piece & (1U << (NumBits-1))) == 0)
411         return Result;
412
413       NextBit += NumBits-1;
414       Piece = Read(NumBits);
415     }
416   }
417
418   void SkipToWord() {
419     BitsInCurWord = 0;
420     CurWord = 0;
421   }
422
423   unsigned ReadCode() {
424     return Read(CurCodeSize);
425   }
426
427
428   // Block header:
429   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
430
431   /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
432   /// the block.
433   unsigned ReadSubBlockID() {
434     return ReadVBR(bitc::BlockIDWidth);
435   }
436
437   /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
438   /// over the body of this block.  If the block record is malformed, return
439   /// true.
440   bool SkipBlock() {
441     // Read and ignore the codelen value.  Since we are skipping this block, we
442     // don't care what code widths are used inside of it.
443     ReadVBR(bitc::CodeLenWidth);
444     SkipToWord();
445     unsigned NumWords = Read(bitc::BlockSizeWidth);
446
447     // Check that the block wasn't partially defined, and that the offset isn't
448     // bogus.
449     size_t SkipTo = NextChar + NumWords*4;
450     if (AtEndOfStream() || !canSkipToPos(SkipTo))
451       return true;
452
453     NextChar = SkipTo;
454     return false;
455   }
456
457   /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
458   /// the block, and return true if the block has an error.
459   bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0);
460   
461   bool ReadBlockEnd() {
462     if (BlockScope.empty()) return true;
463
464     // Block tail:
465     //    [END_BLOCK, <align4bytes>]
466     SkipToWord();
467
468     popBlockScope();
469     return false;
470   }
471
472 private:
473
474   void popBlockScope() {
475     CurCodeSize = BlockScope.back().PrevCodeSize;
476
477     // Delete abbrevs from popped scope.
478     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
479          i != e; ++i)
480       CurAbbrevs[i]->dropRef();
481
482     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
483     BlockScope.pop_back();
484   }
485
486  //===--------------------------------------------------------------------===//
487   // Record Processing
488   //===--------------------------------------------------------------------===//
489
490 private:
491   void readAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
492                               SmallVectorImpl<uint64_t> &Vals);
493   void readAbbreviatedField(const BitCodeAbbrevOp &Op,
494                             SmallVectorImpl<uint64_t> &Vals);
495   void skipAbbreviatedField(const BitCodeAbbrevOp &Op);
496   
497 public:
498
499   /// getAbbrev - Return the abbreviation for the specified AbbrevId.
500   const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
501     unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
502     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
503     return CurAbbrevs[AbbrevNo];
504   }
505
506   /// skipRecord - Read the current record and discard it.
507   void skipRecord(unsigned AbbrevID);
508   
509   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
510                       const char **BlobStart = 0, unsigned *BlobLen = 0);
511   
512   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
513                       const char *&BlobStart, unsigned &BlobLen) {
514     return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
515   }
516
517   //===--------------------------------------------------------------------===//
518   // Abbrev Processing
519   //===--------------------------------------------------------------------===//
520   void ReadAbbrevRecord();
521   
522   bool ReadBlockInfoBlock();
523 };
524
525 } // End llvm namespace
526
527 #endif