eac9ab0b607ad82f5bdbca5cc4e4e6c5dd3d25e6
[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       CurAbbrevs[i]->dropRef();
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         Abbrevs[i]->dropRef();
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 ByteNo = (BitNo/8) & ~3;
97     unsigned WordBitNo = BitNo & 31;
98     assert(ByteNo < (unsigned)(LastChar-FirstChar) && "Invalid location");
99     
100     // Move the cursor to the right word.
101     NextChar = FirstChar+ByteNo;
102     BitsInCurWord = 0;
103     
104     // Skip over any bits that are already consumed.
105     if (WordBitNo) {
106       NextChar -= 4;
107       Read(WordBitNo);
108     }
109   }
110   
111   /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
112   unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
113   
114   uint32_t Read(unsigned NumBits) {
115     // If the field is fully contained by CurWord, return it quickly.
116     if (BitsInCurWord >= NumBits) {
117       uint32_t R = CurWord & ((1U << NumBits)-1);
118       CurWord >>= NumBits;
119       BitsInCurWord -= NumBits;
120       return R;
121     }
122
123     // If we run out of data, stop at the end of the stream.
124     if (LastChar == NextChar) {
125       CurWord = 0;
126       BitsInCurWord = 0;
127       return 0;
128     }
129     
130     unsigned R = CurWord;
131
132     // Read the next word from the stream.
133     CurWord = (NextChar[0] <<  0) | (NextChar[1] << 8) |
134               (NextChar[2] << 16) | (NextChar[3] << 24);
135     NextChar += 4;
136     
137     // Extract NumBits-BitsInCurWord from what we just read.
138     unsigned BitsLeft = NumBits-BitsInCurWord;
139     
140     // Be careful here, BitsLeft is in the range [1..32] inclusive.
141     R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
142     
143     // BitsLeft bits have just been used up from CurWord.
144     if (BitsLeft != 32)
145       CurWord >>= BitsLeft;
146     else
147       CurWord = 0;
148     BitsInCurWord = 32-BitsLeft;
149     return R;
150   }
151   
152   uint64_t Read64(unsigned NumBits) {
153     if (NumBits <= 32) return Read(NumBits);
154     
155     uint64_t V = Read(32);
156     return V | (uint64_t)Read(NumBits-32) << 32;
157   }
158   
159   uint32_t ReadVBR(unsigned NumBits) {
160     uint32_t Piece = Read(NumBits);
161     if ((Piece & (1U << (NumBits-1))) == 0)
162       return Piece;
163
164     uint32_t Result = 0;
165     unsigned NextBit = 0;
166     while (1) {
167       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
168
169       if ((Piece & (1U << (NumBits-1))) == 0)
170         return Result;
171       
172       NextBit += NumBits-1;
173       Piece = Read(NumBits);
174     }
175   }
176   
177   uint64_t ReadVBR64(unsigned NumBits) {
178     uint64_t Piece = Read(NumBits);
179     if ((Piece & (1U << (NumBits-1))) == 0)
180       return Piece;
181     
182     uint64_t Result = 0;
183     unsigned NextBit = 0;
184     while (1) {
185       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
186       
187       if ((Piece & (1U << (NumBits-1))) == 0)
188         return Result;
189       
190       NextBit += NumBits-1;
191       Piece = Read(NumBits);
192     }
193   }
194
195   void SkipToWord() {
196     BitsInCurWord = 0;
197     CurWord = 0;
198   }
199
200   
201   unsigned ReadCode() {
202     return Read(CurCodeSize);
203   }
204
205   //===--------------------------------------------------------------------===//
206   // Block Manipulation
207   //===--------------------------------------------------------------------===//
208   
209   // Block header:
210   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
211
212   /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
213   /// the block.
214   unsigned ReadSubBlockID() {
215     return ReadVBR(bitc::BlockIDWidth);
216   }
217   
218   /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
219   /// over the body of this block.  If the block record is malformed, return
220   /// true.
221   bool SkipBlock() {
222     // Read and ignore the codelen value.  Since we are skipping this block, we
223     // don't care what code widths are used inside of it.
224     ReadVBR(bitc::CodeLenWidth);
225     SkipToWord();
226     unsigned NumWords = Read(bitc::BlockSizeWidth);
227     
228     // Check that the block wasn't partially defined, and that the offset isn't
229     // bogus.
230     if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
231       return true;
232     
233     NextChar += NumWords*4;
234     return false;
235   }
236   
237   /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, read and enter
238   /// the block, returning the BlockID of the block we just entered.
239   bool EnterSubBlock(unsigned *NumWordsP = 0) {
240     BlockScope.push_back(Block(CurCodeSize));
241     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
242     
243     // Get the codesize of this block.
244     CurCodeSize = ReadVBR(bitc::CodeLenWidth);
245     SkipToWord();
246     unsigned NumWords = Read(bitc::BlockSizeWidth);
247     if (NumWordsP) *NumWordsP = NumWords;
248     
249     // Validate that this block is sane.
250     if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
251       return true;
252     
253     return false;
254   }
255   
256   bool ReadBlockEnd() {
257     if (BlockScope.empty()) return true;
258     
259     // Block tail:
260     //    [END_BLOCK, <align4bytes>]
261     SkipToWord();
262     CurCodeSize = BlockScope.back().PrevCodeSize;
263     
264     // Delete abbrevs from popped scope.
265     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
266       CurAbbrevs[i]->dropRef();
267     
268     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
269     BlockScope.pop_back();
270     return false;
271   }
272   
273   //===--------------------------------------------------------------------===//
274   // Record Processing
275   //===--------------------------------------------------------------------===//
276   
277   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals) {
278     if (AbbrevID == bitc::UNABBREV_RECORD) {
279       unsigned Code = ReadVBR(6);
280       unsigned NumElts = ReadVBR(6);
281       for (unsigned i = 0; i != NumElts; ++i)
282         Vals.push_back(ReadVBR64(6));
283       return Code;
284     }
285     
286     unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
287     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
288     BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
289
290     for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
291       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
292       if (Op.isLiteral()) {
293         // If the abbrev specifies the literal value to use, use it.
294         Vals.push_back(Op.getLiteralValue());
295       } else {
296         // Decode the value as we are commanded.
297         switch (Op.getEncoding()) {
298         default: assert(0 && "Unknown encoding!");
299         case BitCodeAbbrevOp::FixedWidth:
300           Vals.push_back(Read(Op.getEncodingData()));
301           break;
302         case BitCodeAbbrevOp::VBR:
303           Vals.push_back(ReadVBR64(Op.getEncodingData()));
304           break;
305         }
306       }
307     }
308     
309     unsigned Code = Vals[0];
310     Vals.erase(Vals.begin());
311     return Code;
312   }
313   
314   //===--------------------------------------------------------------------===//
315   // Abbrev Processing
316   //===--------------------------------------------------------------------===//
317   
318   void ReadAbbrevRecord() {
319     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
320     unsigned NumOpInfo = ReadVBR(5);
321     for (unsigned i = 0; i != NumOpInfo; ++i) {
322       bool IsLiteral = Read(1);
323       if (IsLiteral) {
324         Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
325         continue;
326       }
327
328       BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
329       if (BitCodeAbbrevOp::hasEncodingData(E)) {
330         Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
331       } else {
332         assert(0 && "unimp");
333       }
334     }
335     CurAbbrevs.push_back(Abbv);
336   }
337 };
338
339 } // End llvm namespace
340
341 #endif