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