OSDN Git Service

fix some type confusion in ReadVBR64: "Piece" should be only 32 bits,
[android-x86/external-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 BITSTREAM_READER_H
16 #define BITSTREAM_READER_H
17
18 #include "llvm/Bitcode/BitCodes.h"
19 #include <climits>
20 #include <vector>
21
22 namespace llvm {
23
24   class Deserializer;
25
26 class BitstreamReader {
27 public:
28   /// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
29   /// These describe abbreviations that all blocks of the specified ID inherit.
30   struct BlockInfo {
31     unsigned BlockID;
32     std::vector<BitCodeAbbrev*> Abbrevs;
33     std::string Name;
34     
35     std::vector<std::pair<unsigned, std::string> > RecordNames;
36   };
37 private:
38   /// FirstChar/LastChar - This remembers the first and last bytes of the
39   /// stream.
40   const unsigned char *FirstChar, *LastChar;
41   
42   std::vector<BlockInfo> BlockInfoRecords;
43
44   /// IgnoreBlockInfoNames - This is set to true if we don't care about the
45   /// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
46   /// uses this.
47   bool IgnoreBlockInfoNames;
48   
49   BitstreamReader(const BitstreamReader&);  // NOT IMPLEMENTED
50   void operator=(const BitstreamReader&);  // NOT IMPLEMENTED
51 public:
52   BitstreamReader() : FirstChar(0), LastChar(0), IgnoreBlockInfoNames(true) {
53   }
54
55   BitstreamReader(const unsigned char *Start, const unsigned char *End) {
56     IgnoreBlockInfoNames = true;
57     init(Start, End);
58   }
59
60   void init(const unsigned char *Start, const unsigned char *End) {
61     FirstChar = Start;
62     LastChar = End;
63     assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
64   }
65
66   ~BitstreamReader() {
67     // Free the BlockInfoRecords.
68     while (!BlockInfoRecords.empty()) {
69       BlockInfo &Info = BlockInfoRecords.back();
70       // Free blockinfo abbrev info.
71       for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
72            i != e; ++i)
73         Info.Abbrevs[i]->dropRef();
74       BlockInfoRecords.pop_back();
75     }
76   }
77   
78   const unsigned char *getFirstChar() const { return FirstChar; }
79   const unsigned char *getLastChar() const { return LastChar; }
80
81   /// CollectBlockInfoNames - This is called by clients that want block/record
82   /// name information.
83   void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
84   bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
85   
86   //===--------------------------------------------------------------------===//
87   // Block Manipulation
88   //===--------------------------------------------------------------------===//
89
90   /// hasBlockInfoRecords - Return true if we've already read and processed the
91   /// block info block for this Bitstream.  We only process it for the first
92   /// cursor that walks over it.
93   bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
94   
95   /// getBlockInfo - If there is block info for the specified ID, return it,
96   /// otherwise return null.
97   const BlockInfo *getBlockInfo(unsigned BlockID) const {
98     // Common case, the most recent entry matches BlockID.
99     if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
100       return &BlockInfoRecords.back();
101
102     for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
103          i != e; ++i)
104       if (BlockInfoRecords[i].BlockID == BlockID)
105         return &BlockInfoRecords[i];
106     return 0;
107   }
108
109   BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
110     if (const BlockInfo *BI = getBlockInfo(BlockID))
111       return *const_cast<BlockInfo*>(BI);
112
113     // Otherwise, add a new record.
114     BlockInfoRecords.push_back(BlockInfo());
115     BlockInfoRecords.back().BlockID = BlockID;
116     return BlockInfoRecords.back();
117   }
118
119 };
120
121 class BitstreamCursor {
122   friend class Deserializer;
123   BitstreamReader *BitStream;
124   const unsigned char *NextChar;
125   
126   /// CurWord - This is the current data we have pulled from the stream but have
127   /// not returned to the client.
128   uint32_t CurWord;
129   
130   /// BitsInCurWord - This is the number of bits in CurWord that are valid. This
131   /// is always from [0...31] inclusive.
132   unsigned BitsInCurWord;
133   
134   // CurCodeSize - This is the declared size of code values used for the current
135   // block, in bits.
136   unsigned CurCodeSize;
137   
138   /// CurAbbrevs - Abbrevs installed at in this block.
139   std::vector<BitCodeAbbrev*> CurAbbrevs;
140   
141   struct Block {
142     unsigned PrevCodeSize;
143     std::vector<BitCodeAbbrev*> PrevAbbrevs;
144     explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
145   };
146   
147   /// BlockScope - This tracks the codesize of parent blocks.
148   SmallVector<Block, 8> BlockScope;
149   
150 public:
151   BitstreamCursor() : BitStream(0), NextChar(0) {
152   }
153   BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
154     operator=(RHS);
155   }
156   
157   explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
158     NextChar = R.getFirstChar();
159     assert(NextChar && "Bitstream not initialized yet");
160     CurWord = 0;
161     BitsInCurWord = 0;
162     CurCodeSize = 2;
163   }
164   
165   void init(BitstreamReader &R) {
166     freeState();
167     
168     BitStream = &R;
169     NextChar = R.getFirstChar();
170     assert(NextChar && "Bitstream not initialized yet");
171     CurWord = 0;
172     BitsInCurWord = 0;
173     CurCodeSize = 2;
174   }
175   
176   ~BitstreamCursor() {
177     freeState();
178   }
179   
180   void operator=(const BitstreamCursor &RHS) {
181     freeState();
182     
183     BitStream = RHS.BitStream;
184     NextChar = RHS.NextChar;
185     CurWord = RHS.CurWord;
186     BitsInCurWord = RHS.BitsInCurWord;
187     CurCodeSize = RHS.CurCodeSize;
188     
189     // Copy abbreviations, and bump ref counts.
190     CurAbbrevs = RHS.CurAbbrevs;
191     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
192          i != e; ++i)
193       CurAbbrevs[i]->addRef();
194     
195     // Copy block scope and bump ref counts.
196     for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
197          S != e; ++S) {
198       std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
199       for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
200            i != e; ++i)
201         Abbrevs[i]->addRef();
202     }
203   }
204   
205   void freeState() {
206     // Free all the Abbrevs.
207     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
208          i != e; ++i)
209       CurAbbrevs[i]->dropRef();
210     CurAbbrevs.clear();
211     
212     // Free all the Abbrevs in the block scope.
213     for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
214          S != e; ++S) {
215       std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
216       for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
217            i != e; ++i)
218         Abbrevs[i]->dropRef();
219     }
220     BlockScope.clear();
221   }
222   
223   /// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
224   unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
225   
226   bool AtEndOfStream() const {
227     return NextChar == BitStream->getLastChar() && BitsInCurWord == 0;
228   }
229   
230   /// GetCurrentBitNo - Return the bit # of the bit we are reading.
231   uint64_t GetCurrentBitNo() const {
232     return (NextChar-BitStream->getFirstChar())*CHAR_BIT - BitsInCurWord;
233   }
234   
235   BitstreamReader *getBitStreamReader() {
236     return BitStream;
237   }
238   const BitstreamReader *getBitStreamReader() const {
239     return BitStream;
240   }
241   
242   
243   /// JumpToBit - Reset the stream to the specified bit number.
244   void JumpToBit(uint64_t BitNo) {
245     uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
246     uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
247     assert(ByteNo <= (uintptr_t)(BitStream->getLastChar()-
248                                  BitStream->getFirstChar()) &&
249            "Invalid location");
250     
251     // Move the cursor to the right word.
252     NextChar = BitStream->getFirstChar()+ByteNo;
253     BitsInCurWord = 0;
254     CurWord = 0;
255     
256     // Skip over any bits that are already consumed.
257     if (WordBitNo)
258       Read(static_cast<unsigned>(WordBitNo));
259   }
260   
261   
262   uint32_t Read(unsigned NumBits) {
263     assert(NumBits <= 32 && "Cannot return more than 32 bits!");
264     // If the field is fully contained by CurWord, return it quickly.
265     if (BitsInCurWord >= NumBits) {
266       uint32_t R = CurWord & ((1U << NumBits)-1);
267       CurWord >>= NumBits;
268       BitsInCurWord -= NumBits;
269       return R;
270     }
271
272     // If we run out of data, stop at the end of the stream.
273     if (NextChar == BitStream->getLastChar()) {
274       CurWord = 0;
275       BitsInCurWord = 0;
276       return 0;
277     }
278
279     unsigned R = CurWord;
280
281     // Read the next word from the stream.
282     CurWord = (NextChar[0] <<  0) | (NextChar[1] << 8) |
283               (NextChar[2] << 16) | (NextChar[3] << 24);
284     NextChar += 4;
285
286     // Extract NumBits-BitsInCurWord from what we just read.
287     unsigned BitsLeft = NumBits-BitsInCurWord;
288
289     // Be careful here, BitsLeft is in the range [1..32] inclusive.
290     R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
291
292     // BitsLeft bits have just been used up from CurWord.
293     if (BitsLeft != 32)
294       CurWord >>= BitsLeft;
295     else
296       CurWord = 0;
297     BitsInCurWord = 32-BitsLeft;
298     return R;
299   }
300
301   uint64_t Read64(unsigned NumBits) {
302     if (NumBits <= 32) return Read(NumBits);
303
304     uint64_t V = Read(32);
305     return V | (uint64_t)Read(NumBits-32) << 32;
306   }
307
308   uint32_t ReadVBR(unsigned NumBits) {
309     uint32_t Piece = Read(NumBits);
310     if ((Piece & (1U << (NumBits-1))) == 0)
311       return Piece;
312
313     uint32_t Result = 0;
314     unsigned NextBit = 0;
315     while (1) {
316       Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
317
318       if ((Piece & (1U << (NumBits-1))) == 0)
319         return Result;
320
321       NextBit += NumBits-1;
322       Piece = Read(NumBits);
323     }
324   }
325
326   // ReadVBR64 - Read a VBR that may have a value up to 64-bits in size.  The
327   // chunk size of the VBR must still be <= 32 bits though.
328   uint64_t ReadVBR64(unsigned NumBits) {
329     uint32_t Piece = Read(NumBits);
330     if ((Piece & (1U << (NumBits-1))) == 0)
331       return uint64_t(Piece);
332
333     uint64_t Result = 0;
334     unsigned NextBit = 0;
335     while (1) {
336       Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
337
338       if ((Piece & (1U << (NumBits-1))) == 0)
339         return Result;
340
341       NextBit += NumBits-1;
342       Piece = Read(NumBits);
343     }
344   }
345
346   void SkipToWord() {
347     BitsInCurWord = 0;
348     CurWord = 0;
349   }
350
351   unsigned ReadCode() {
352     return Read(CurCodeSize);
353   }
354
355
356   // Block header:
357   //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
358
359   /// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
360   /// the block.
361   unsigned ReadSubBlockID() {
362     return ReadVBR(bitc::BlockIDWidth);
363   }
364
365   /// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
366   /// over the body of this block.  If the block record is malformed, return
367   /// true.
368   bool SkipBlock() {
369     // Read and ignore the codelen value.  Since we are skipping this block, we
370     // don't care what code widths are used inside of it.
371     ReadVBR(bitc::CodeLenWidth);
372     SkipToWord();
373     unsigned NumWords = Read(bitc::BlockSizeWidth);
374
375     // Check that the block wasn't partially defined, and that the offset isn't
376     // bogus.
377     if (AtEndOfStream() || NextChar+NumWords*4 > BitStream->getLastChar())
378       return true;
379
380     NextChar += NumWords*4;
381     return false;
382   }
383
384   /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
385   /// the block, and return true if the block is valid.
386   bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
387     // Save the current block's state on BlockScope.
388     BlockScope.push_back(Block(CurCodeSize));
389     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
390
391     // Add the abbrevs specific to this block to the CurAbbrevs list.
392     if (const BitstreamReader::BlockInfo *Info =
393           BitStream->getBlockInfo(BlockID)) {
394       for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
395            i != e; ++i) {
396         CurAbbrevs.push_back(Info->Abbrevs[i]);
397         CurAbbrevs.back()->addRef();
398       }
399     }
400
401     // Get the codesize of this block.
402     CurCodeSize = ReadVBR(bitc::CodeLenWidth);
403     SkipToWord();
404     unsigned NumWords = Read(bitc::BlockSizeWidth);
405     if (NumWordsP) *NumWordsP = NumWords;
406
407     // Validate that this block is sane.
408     if (CurCodeSize == 0 || AtEndOfStream() ||
409         NextChar+NumWords*4 > BitStream->getLastChar())
410       return true;
411
412     return false;
413   }
414
415   bool ReadBlockEnd() {
416     if (BlockScope.empty()) return true;
417
418     // Block tail:
419     //    [END_BLOCK, <align4bytes>]
420     SkipToWord();
421
422     PopBlockScope();
423     return false;
424   }
425
426 private:
427   void PopBlockScope() {
428     CurCodeSize = BlockScope.back().PrevCodeSize;
429
430     // Delete abbrevs from popped scope.
431     for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
432          i != e; ++i)
433       CurAbbrevs[i]->dropRef();
434
435     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
436     BlockScope.pop_back();
437   }
438
439  //===--------------------------------------------------------------------===//
440   // Record Processing
441   //===--------------------------------------------------------------------===//
442
443 private:
444   void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
445                               SmallVectorImpl<uint64_t> &Vals) {
446     assert(Op.isLiteral() && "Not a literal");
447     // If the abbrev specifies the literal value to use, use it.
448     Vals.push_back(Op.getLiteralValue());
449   }
450   
451   void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
452                             SmallVectorImpl<uint64_t> &Vals) {
453     assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
454     
455     // Decode the value as we are commanded.
456     switch (Op.getEncoding()) {
457     default: assert(0 && "Unknown encoding!");
458     case BitCodeAbbrevOp::Fixed:
459       Vals.push_back(Read((unsigned)Op.getEncodingData()));
460       break;
461     case BitCodeAbbrevOp::VBR:
462       Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
463       break;
464     case BitCodeAbbrevOp::Char6:
465       Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
466       break;
467     }
468   }
469 public:
470
471   /// getAbbrev - Return the abbreviation for the specified AbbrevId. 
472   const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
473     unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
474     assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
475     return CurAbbrevs[AbbrevNo];
476   }
477   
478   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
479                       const char **BlobStart = 0, unsigned *BlobLen = 0) {
480     if (AbbrevID == bitc::UNABBREV_RECORD) {
481       unsigned Code = ReadVBR(6);
482       unsigned NumElts = ReadVBR(6);
483       for (unsigned i = 0; i != NumElts; ++i)
484         Vals.push_back(ReadVBR64(6));
485       return Code;
486     }
487
488     const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
489
490     for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
491       const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
492       if (Op.isLiteral()) {
493         ReadAbbreviatedLiteral(Op, Vals); 
494       } else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
495         // Array case.  Read the number of elements as a vbr6.
496         unsigned NumElts = ReadVBR(6);
497
498         // Get the element encoding.
499         assert(i+2 == e && "array op not second to last?");
500         const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
501
502         // Read all the elements.
503         for (; NumElts; --NumElts)
504           ReadAbbreviatedField(EltEnc, Vals);
505       } else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
506         // Blob case.  Read the number of bytes as a vbr6.
507         unsigned NumElts = ReadVBR(6);
508         SkipToWord();  // 32-bit alignment
509
510         // Figure out where the end of this blob will be including tail padding.
511         const unsigned char *NewEnd = NextChar+((NumElts+3)&~3);
512         
513         // If this would read off the end of the bitcode file, just set the
514         // record to empty and return.
515         if (NewEnd > BitStream->getLastChar()) {
516           Vals.append(NumElts, 0);
517           NextChar = BitStream->getLastChar();
518           break;
519         }
520         
521         // Otherwise, read the number of bytes.  If we can return a reference to
522         // the data, do so to avoid copying it.
523         if (BlobStart) {
524           *BlobStart = (const char*)NextChar;
525           *BlobLen = NumElts;
526         } else {
527           for (; NumElts; ++NextChar, --NumElts)
528             Vals.push_back(*NextChar);
529         }
530         // Skip over tail padding.
531         NextChar = NewEnd;
532       } else {
533         ReadAbbreviatedField(Op, Vals);
534       }
535     }
536
537     unsigned Code = (unsigned)Vals[0];
538     Vals.erase(Vals.begin());
539     return Code;
540   }
541
542   unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
543                       const char *&BlobStart, unsigned &BlobLen) {
544     return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
545   }
546
547   
548   //===--------------------------------------------------------------------===//
549   // Abbrev Processing
550   //===--------------------------------------------------------------------===//
551
552   void ReadAbbrevRecord() {
553     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
554     unsigned NumOpInfo = ReadVBR(5);
555     for (unsigned i = 0; i != NumOpInfo; ++i) {
556       bool IsLiteral = Read(1) ? true : false;
557       if (IsLiteral) {
558         Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
559         continue;
560       }
561
562       BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
563       if (BitCodeAbbrevOp::hasEncodingData(E))
564         Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
565       else
566         Abbv->Add(BitCodeAbbrevOp(E));
567     }
568     CurAbbrevs.push_back(Abbv);
569   }
570   
571 public:
572
573   bool ReadBlockInfoBlock() {
574     // If this is the second stream to get to the block info block, skip it.
575     if (BitStream->hasBlockInfoRecords())
576       return SkipBlock();
577     
578     if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
579
580     SmallVector<uint64_t, 64> Record;
581     BitstreamReader::BlockInfo *CurBlockInfo = 0;
582
583     // Read all the records for this module.
584     while (1) {
585       unsigned Code = ReadCode();
586       if (Code == bitc::END_BLOCK)
587         return ReadBlockEnd();
588       if (Code == bitc::ENTER_SUBBLOCK) {
589         ReadSubBlockID();
590         if (SkipBlock()) return true;
591         continue;
592       }
593
594       // Read abbrev records, associate them with CurBID.
595       if (Code == bitc::DEFINE_ABBREV) {
596         if (!CurBlockInfo) return true;
597         ReadAbbrevRecord();
598
599         // ReadAbbrevRecord installs the abbrev in CurAbbrevs.  Move it to the
600         // appropriate BlockInfo.
601         BitCodeAbbrev *Abbv = CurAbbrevs.back();
602         CurAbbrevs.pop_back();
603         CurBlockInfo->Abbrevs.push_back(Abbv);
604         continue;
605       }
606
607       // Read a record.
608       Record.clear();
609       switch (ReadRecord(Code, Record)) {
610       default: break;  // Default behavior, ignore unknown content.
611       case bitc::BLOCKINFO_CODE_SETBID:
612         if (Record.size() < 1) return true;
613         CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
614         break;
615       case bitc::BLOCKINFO_CODE_BLOCKNAME: {
616         if (!CurBlockInfo) return true;
617         if (BitStream->isIgnoringBlockInfoNames()) break;  // Ignore name.
618         std::string Name;
619         for (unsigned i = 0, e = Record.size(); i != e; ++i)
620           Name += (char)Record[i];
621         CurBlockInfo->Name = Name;
622         break;
623       }
624       case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
625         if (!CurBlockInfo) return true;
626         if (BitStream->isIgnoringBlockInfoNames()) break;  // Ignore name.
627         std::string Name;
628         for (unsigned i = 1, e = Record.size(); i != e; ++i)
629           Name += (char)Record[i];
630         CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
631                                                            Name));
632         break;
633       }
634       }
635     }
636   }
637 };
638   
639 } // End llvm namespace
640
641 #endif