add JumpToBit, an explicit init method, and a default ctor.
[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 was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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 BITSTREAM_READER_H
16 #define BITSTREAM_READER_H
17
18 #include "llvm/Bitcode/BitCodes.h"
19 #include <vector>
20
21 namespace llvm {
22   
23 class BitstreamReader {
24   const unsigned char *NextChar;
25   const unsigned char *LastChar;
26   
27   /// CurWord - This is the current data we have pulled from the stream but have
28   /// not returned to the client.
29   uint32_t CurWord;
30   
31   /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
32   /// is always from [0...31] inclusive.
33   unsigned BitsInCurWord;
34   
35   // CurCodeSize - This is the declared size of code values used for the current
36   // block, in bits.
37   unsigned CurCodeSize;
38
39   /// CurAbbrevs - Abbrevs installed at in this block.
40   std::vector<BitCodeAbbrev*> CurAbbrevs;
41   
42   struct Block {
43     unsigned PrevCodeSize;
44     std::vector<BitCodeAbbrev*> PrevAbbrevs;
45     explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
46   };
47   
48   /// BlockScope - This tracks the codesize of parent blocks.
49   SmallVector<Block, 8> BlockScope;
50
51   /// FirstChar - This remembers the first byte of the stream.
52   const unsigned char *FirstChar;
53 public:
54   BitstreamReader() {
55     NextChar = FirstChar = LastChar = 0;
56     CurWord = 0;
57     BitsInCurWord = 0;
58     CurCodeSize = 0;
59   }
60
61   BitstreamReader(const unsigned char *Start, const unsigned char *End) {
62     init(Start, End);
63   }
64   
65   void init(const unsigned char *Start, const unsigned char *End) {
66     NextChar = FirstChar = Start;
67     LastChar = End;
68     assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
69     CurWord = 0;
70     BitsInCurWord = 0;
71     CurCodeSize = 2;
72   }
73   
74   ~BitstreamReader() {
75     // Abbrevs could still exist if the stream was broken.  If so, don't leak
76     // them.
77     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
78       delete CurAbbrevs[i];
79
80     for (unsigned S = 0, e = BlockScope.size(); S != e; ++S) {
81       std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
82       for (unsigned i = 0, e = Abbrevs.size(); i != e; ++i)
83         delete Abbrevs[i];
84     }
85   }
86   
87   bool AtEndOfStream() const { return NextChar == LastChar; }
88   
89   /// GetCurrentBitNo - Return the bit # of the bit we are reading.
90   uint64_t GetCurrentBitNo() const {
91     return (NextChar-FirstChar)*8 + (32-BitsInCurWord);
92   }
93   
94   /// JumpToBit - Reset the stream to the specified bit number.
95   void JumpToBit(uint64_t BitNo) {
96     unsigned WordNo = BitNo/32;
97     unsigned WordBitNo = BitNo & 31;
98     assert(WordNo < (unsigned)(LastChar-FirstChar) && "Invalid location");
99     
100     // Move the cursor to the right word.
101     NextChar = FirstChar+WordNo;
102     BitsInCurWord = 0;
103     
104     // Skip over any bits that are already consumed.
105     if (WordBitNo) Read(WordBitNo);
106   }
107   
108   /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
109   unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
110   
111   uint32_t Read(unsigned NumBits) {
112     // If the field is fully contained by CurWord, return it quickly.
113     if (BitsInCurWord >= NumBits) {
114       uint32_t R = CurWord & ((1U << NumBits)-1);
115       CurWord >>= NumBits;
116       BitsInCurWord -= NumBits;
117       return R;
118     }
119
120     // If we run out of data, stop at the end of the stream.
121     if (LastChar == NextChar) {
122       CurWord = 0;
123       BitsInCurWord = 0;
124       return 0;
125     }
126     
127     unsigned R = CurWord;
128
129     // Read the next word from the stream.
130     CurWord = (NextChar[0] <<  0) | (NextChar[1] << 8) |
131               (NextChar[2] << 16) | (NextChar[3] << 24);
132     NextChar += 4;
133     
134     // Extract NumBits-BitsInCurWord from what we just read.
135     unsigned BitsLeft = NumBits-BitsInCurWord;
136     
137     // Be careful here, BitsLeft is in the range [1..32] inclusive.
138     R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
139     
140     // BitsLeft bits have just been used up from CurWord.
141     if (BitsLeft != 32)
142       CurWord >>= BitsLeft;
143     else
144       CurWord = 0;
145     BitsInCurWord = 32-BitsLeft;
146     return R;
147   }
148   
149   uint64_t Read64(unsigned NumBits) {
150     if (NumBits <= 32) return Read(NumBits);
151     
152     uint64_t V = Read(32);
153     return V | (uint64_t)Read(NumBits-32) << 32;
154   }
155   
156   uint32_t ReadVBR(unsigned NumBits) {
157     uint32_t Piece = Read(NumBits);
158     if ((Piece & (1U << (NumBits-1))) == 0)
159       return Piece;
160
161     uint32_t Result = 0;
162     unsigned NextBit = 0;
163     while (1) {
164       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
165
166       if ((Piece & (1U << (NumBits-1))) == 0)
167         return Result;
168       
169       NextBit += NumBits-1;
170       Piece = Read(NumBits);
171     }
172   }
173   
174   uint64_t ReadVBR64(unsigned NumBits) {
175     uint64_t Piece = Read(NumBits);
176     if ((Piece & (1U << (NumBits-1))) == 0)
177       return Piece;
178     
179     uint64_t Result = 0;
180     unsigned NextBit = 0;
181     while (1) {
182       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
183       
184       if ((Piece & (1U << (NumBits-1))) == 0)
185         return Result;
186       
187       NextBit += NumBits-1;
188       Piece = Read(NumBits);
189     }
190   }
191
192   void SkipToWord() {
193     BitsInCurWord = 0;
194     CurWord = 0;
195   }
196
197   
198   unsigned ReadCode() {
199     return Read(CurCodeSize);
200   }
201
202   //===--------------------------------------------------------------------===//
203   // Block Manipulation
204   //===--------------------------------------------------------------------===//
205   
206   // Block header:
207   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
208
209   /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
210   /// the block.
211   unsigned ReadSubBlockID() {
212     return ReadVBR(bitc::BlockIDWidth);
213   }
214   
215   /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
216   /// over the body of this block.  If the block record is malformed, return
217   /// true.
218   bool SkipBlock() {
219     // Read and ignore the codelen value.  Since we are skipping this block, we
220     // don't care what code widths are used inside of it.
221     ReadVBR(bitc::CodeLenWidth);
222     SkipToWord();
223     unsigned NumWords = Read(bitc::BlockSizeWidth);
224     
225     // Check that the block wasn't partially defined, and that the offset isn't
226     // bogus.
227     if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
228       return true;
229     
230     NextChar += NumWords*4;
231     return false;
232   }
233   
234   /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, read and enter
235   /// the block, returning the BlockID of the block we just entered.
236   bool EnterSubBlock(unsigned *NumWordsP = 0) {
237     BlockScope.push_back(Block(CurCodeSize));
238     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
239     
240     // Get the codesize of this block.
241     CurCodeSize = ReadVBR(bitc::CodeLenWidth);
242     SkipToWord();
243     unsigned NumWords = Read(bitc::BlockSizeWidth);
244     if (NumWordsP) *NumWordsP = NumWords;
245     
246     // Validate that this block is sane.
247     if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
248       return true;
249     
250     return false;
251   }
252   
253   bool ReadBlockEnd() {
254     if (BlockScope.empty()) return true;
255     
256     // Block tail:
257     //    [END_BLOCK, <align4bytes>]
258     SkipToWord();
259     CurCodeSize = BlockScope.back().PrevCodeSize;
260     
261     // Delete abbrevs from popped scope.
262     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
263       delete CurAbbrevs[i];
264     
265     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
266     BlockScope.pop_back();
267     return false;
268   }
269   
270   //===--------------------------------------------------------------------===//
271   // Record Processing
272   //===--------------------------------------------------------------------===//
273   
274   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals) {
275     if (AbbrevID == bitc::UNABBREV_RECORD) {
276       unsigned Code = ReadVBR(6);
277       unsigned NumElts = ReadVBR(6);
278       for (unsigned i = 0; i != NumElts; ++i)
279         Vals.push_back(ReadVBR64(6));
280       return Code;
281     }
282     
283     unsigned AbbrevNo = AbbrevID-bitc::FIRST_ABBREV;
284     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
285     BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
286
287     for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
288       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
289       if (Op.isLiteral()) {
290         // If the abbrev specifies the literal value to use, use it.
291         Vals.push_back(Op.getLiteralValue());
292       } else {
293         // Decode the value as we are commanded.
294         switch (Op.getEncoding()) {
295         default: assert(0 && "Unknown encoding!");
296         case BitCodeAbbrevOp::FixedWidth:
297           Vals.push_back(Read(Op.getEncodingData()));
298           break;
299         case BitCodeAbbrevOp::VBR:
300           Vals.push_back(ReadVBR64(Op.getEncodingData()));
301           break;
302         }
303       }
304     }
305     
306     unsigned Code = Vals[0];
307     Vals.erase(Vals.begin());
308     return Code;
309   }
310   
311   //===--------------------------------------------------------------------===//
312   // Abbrev Processing
313   //===--------------------------------------------------------------------===//
314   
315   void ReadAbbrevRecord() {
316     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
317     unsigned NumOpInfo = ReadVBR(5);
318     for (unsigned i = 0; i != NumOpInfo; ++i) {
319       bool IsLiteral = Read(1);
320       if (IsLiteral) {
321         Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
322         continue;
323       }
324
325       BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
326       if (BitCodeAbbrevOp::hasEncodingData(E)) {
327         Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
328       } else {
329         assert(0 && "unimp");
330       }
331     }
332     CurAbbrevs.push_back(Abbv);
333   }
334 };
335
336 } // End llvm namespace
337
338 #endif