550459e15f36cb4ae9819aed8cd7d20447815911
[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 public:
52   BitstreamReader(const unsigned char *Start, const unsigned char *End)
53     : NextChar(Start), LastChar(End) {
54     assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
55     CurWord = 0;
56     BitsInCurWord = 0;
57     CurCodeSize = 2;
58   }
59   
60   ~BitstreamReader() {
61     // Abbrevs could still exist if the stream was broken.  If so, don't leak
62     // them.
63     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
64       delete CurAbbrevs[i];
65
66     for (unsigned S = 0, e = BlockScope.size(); S != e; ++S) {
67       std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
68       for (unsigned i = 0, e = Abbrevs.size(); i != e; ++i)
69         delete Abbrevs[i];
70     }
71   }
72   
73   bool AtEndOfStream() const { return NextChar == LastChar; }
74   
75   uint32_t Read(unsigned NumBits) {
76     // If the field is fully contained by CurWord, return it quickly.
77     if (BitsInCurWord >= NumBits) {
78       uint32_t R = CurWord & ((1U << NumBits)-1);
79       CurWord >>= NumBits;
80       BitsInCurWord -= NumBits;
81       return R;
82     }
83
84     // If we run out of data, stop at the end of the stream.
85     if (LastChar == NextChar) {
86       CurWord = 0;
87       BitsInCurWord = 0;
88       return 0;
89     }
90     
91     unsigned R = CurWord;
92
93     // Read the next word from the stream.
94     CurWord = (NextChar[0] <<  0) | (NextChar[1] << 8) |
95               (NextChar[2] << 16) | (NextChar[3] << 24);
96     NextChar += 4;
97     
98     // Extract NumBits-BitsInCurWord from what we just read.
99     unsigned BitsLeft = NumBits-BitsInCurWord;
100     
101     // Be careful here, BitsLeft is in the range [1..32] inclusive.
102     R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
103     
104     // BitsLeft bits have just been used up from CurWord.
105     if (BitsLeft != 32)
106       CurWord >>= BitsLeft;
107     else
108       CurWord = 0;
109     BitsInCurWord = 32-BitsLeft;
110     return R;
111   }
112   
113   uint64_t Read64(unsigned NumBits) {
114     if (NumBits <= 32) return Read(NumBits);
115     
116     uint64_t V = Read(32);
117     return V | (uint64_t)Read(NumBits-32) << 32;
118   }
119   
120   uint32_t ReadVBR(unsigned NumBits) {
121     uint32_t Piece = Read(NumBits);
122     if ((Piece & (1U << (NumBits-1))) == 0)
123       return Piece;
124
125     uint32_t Result = 0;
126     unsigned NextBit = 0;
127     while (1) {
128       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
129
130       if ((Piece & (1U << (NumBits-1))) == 0)
131         return Result;
132       
133       NextBit += NumBits-1;
134       Piece = Read(NumBits);
135     }
136   }
137   
138   uint64_t ReadVBR64(unsigned NumBits) {
139     uint64_t Piece = Read(NumBits);
140     if ((Piece & (1U << (NumBits-1))) == 0)
141       return Piece;
142     
143     uint64_t Result = 0;
144     unsigned NextBit = 0;
145     while (1) {
146       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
147       
148       if ((Piece & (1U << (NumBits-1))) == 0)
149         return Result;
150       
151       NextBit += NumBits-1;
152       Piece = Read(NumBits);
153     }
154   }
155
156   void SkipToWord() {
157     BitsInCurWord = 0;
158     CurWord = 0;
159   }
160
161   
162   unsigned ReadCode() {
163     return Read(CurCodeSize);
164   }
165
166   //===--------------------------------------------------------------------===//
167   // Block Manipulation
168   //===--------------------------------------------------------------------===//
169   
170   // Block header:
171   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
172
173   /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
174   /// the block.
175   unsigned ReadSubBlockID() {
176     return ReadVBR(bitc::BlockIDWidth);
177   }
178   
179   /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
180   /// over the body of this block.  If the block record is malformed, return
181   /// true.
182   bool SkipBlock() {
183     // Read and ignore the codelen value.  Since we are skipping this block, we
184     // don't care what code widths are used inside of it.
185     ReadVBR(bitc::CodeLenWidth);
186     SkipToWord();
187     unsigned NumWords = Read(bitc::BlockSizeWidth);
188     
189     // Check that the block wasn't partially defined, and that the offset isn't
190     // bogus.
191     if (AtEndOfStream() || NextChar+NumWords*4 > LastChar)
192       return true;
193     
194     NextChar += NumWords*4;
195     return false;
196   }
197   
198   /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, read and enter
199   /// the block, returning the BlockID of the block we just entered.
200   bool EnterSubBlock() {
201     BlockScope.push_back(Block(CurCodeSize));
202     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
203     
204     // Get the codesize of this block.
205     CurCodeSize = ReadVBR(bitc::CodeLenWidth);
206     SkipToWord();
207     unsigned NumWords = Read(bitc::BlockSizeWidth);
208     
209     // Validate that this block is sane.
210     if (CurCodeSize == 0 || AtEndOfStream() || NextChar+NumWords*4 > LastChar)
211       return true;
212     
213     return false;
214   }
215   
216   bool ReadBlockEnd() {
217     if (BlockScope.empty()) return true;
218     
219     // Block tail:
220     //    [END_BLOCK, <align4bytes>]
221     SkipToWord();
222     CurCodeSize = BlockScope.back().PrevCodeSize;
223     
224     // Delete abbrevs from popped scope.
225     for (unsigned i = 0, e = CurAbbrevs.size(); i != e; ++i)
226       delete CurAbbrevs[i];
227     
228     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
229     BlockScope.pop_back();
230     return false;
231   }
232   
233   //===--------------------------------------------------------------------===//
234   // Record Processing
235   //===--------------------------------------------------------------------===//
236   
237   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals) {
238     if (AbbrevID == bitc::UNABBREV_RECORD) {
239       unsigned Code = ReadVBR(6);
240       unsigned NumElts = ReadVBR(6);
241       for (unsigned i = 0; i != NumElts; ++i)
242         Vals.push_back(ReadVBR64(6));
243       return Code;
244     }
245     
246     unsigned AbbrevNo = AbbrevID-bitc::FIRST_ABBREV;
247     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
248     BitCodeAbbrev *Abbv = CurAbbrevs[AbbrevNo];
249
250     for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
251       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
252       if (Op.isLiteral()) {
253         // If the abbrev specifies the literal value to use, use it.
254         Vals.push_back(Op.getLiteralValue());
255       } else {
256         // Decode the value as we are commanded.
257         switch (Op.getEncoding()) {
258         default: assert(0 && "Unknown encoding!");
259         case BitCodeAbbrevOp::FixedWidth:
260           Vals.push_back(Read(Op.getEncodingData()));
261           break;
262         case BitCodeAbbrevOp::VBR:
263           Vals.push_back(ReadVBR64(Op.getEncodingData()));
264           break;
265         }
266       }
267     }
268     
269     unsigned Code = Vals[0];
270     Vals.erase(Vals.begin());
271     return Code;
272   }
273   
274   //===--------------------------------------------------------------------===//
275   // Abbrev Processing
276   //===--------------------------------------------------------------------===//
277   
278   void ReadAbbrevRecord() {
279     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
280     unsigned NumOpInfo = ReadVBR(5);
281     for (unsigned i = 0; i != NumOpInfo; ++i) {
282       bool IsLiteral = Read(1);
283       if (IsLiteral) {
284         Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
285         continue;
286       }
287
288       BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
289       if (BitCodeAbbrevOp::hasEncodingData(E)) {
290         Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
291       } else {
292         assert(0 && "unimp");
293       }
294     }
295     CurAbbrevs.push_back(Abbv);
296   }
297 };
298
299 } // End llvm namespace
300
301 #endif