Coverage Report

Created: 2018-12-14 11:24

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/include/llvm/Bitcode/BitstreamReader.h
Line
Count
Source (jump to first uncovered line)
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/ADT/ArrayRef.h"
19
#include "llvm/ADT/SmallVector.h"
20
#include "llvm/Bitcode/BitCodes.h"
21
#include "llvm/Support/Endian.h"
22
#include "llvm/Support/ErrorHandling.h"
23
#include "llvm/Support/MathExtras.h"
24
#include "llvm/Support/MemoryBuffer.h"
25
#include <algorithm>
26
#include <cassert>
27
#include <climits>
28
#include <cstddef>
29
#include <cstdint>
30
#include <memory>
31
#include <string>
32
#include <utility>
33
#include <vector>
34
35
namespace llvm {
36
37
/// This class maintains the abbreviations read from a block info block.
38
class BitstreamBlockInfo {
39
public:
40
  /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
41
  /// describe abbreviations that all blocks of the specified ID inherit.
42
  struct BlockInfo {
43
    unsigned BlockID;
44
    std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
45
    std::string Name;
46
    std::vector<std::pair<unsigned, std::string>> RecordNames;
47
  };
48
49
private:
50
  std::vector<BlockInfo> BlockInfoRecords;
51
52
public:
53
  /// If there is block info for the specified ID, return it, otherwise return
54
  /// null.
55
1.11M
  const BlockInfo *getBlockInfo(unsigned BlockID) const {
56
1.11M
    // Common case, the most recent entry matches BlockID.
57
1.11M
    if (!BlockInfoRecords.empty() && 
BlockInfoRecords.back().BlockID == BlockID1.08M
)
58
338k
      return &BlockInfoRecords.back();
59
777k
60
777k
    for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
61
1.69M
         i != e; 
++i913k
)
62
1.41M
      if (BlockInfoRecords[i].BlockID == BlockID)
63
498k
        return &BlockInfoRecords[i];
64
777k
    
return nullptr279k
;
65
777k
  }
66
67
24.7k
  BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
68
24.7k
    if (const BlockInfo *BI = getBlockInfo(BlockID))
69
32
      return *const_cast<BlockInfo*>(BI);
70
24.6k
71
24.6k
    // Otherwise, add a new record.
72
24.6k
    BlockInfoRecords.emplace_back();
73
24.6k
    BlockInfoRecords.back().BlockID = BlockID;
74
24.6k
    return BlockInfoRecords.back();
75
24.6k
  }
76
};
77
78
/// This represents a position within a bitstream. There may be multiple
79
/// independent cursors reading within one bitstream, each maintaining their
80
/// own local state.
81
class SimpleBitstreamCursor {
82
  ArrayRef<uint8_t> BitcodeBytes;
83
  size_t NextChar = 0;
84
85
public:
86
  /// This is the current data we have pulled from the stream but have not
87
  /// returned to the client. This is specifically and intentionally defined to
88
  /// follow the word size of the host machine for efficiency. We use word_t in
89
  /// places that are aware of this to make it perfectly explicit what is going
90
  /// on.
91
  using word_t = size_t;
92
93
private:
94
  word_t CurWord = 0;
95
96
  /// This is the number of bits in CurWord that are valid. This is always from
97
  /// [0...bits_of(size_t)-1] inclusive.
98
  unsigned BitsInCurWord = 0;
99
100
public:
101
  static const size_t MaxChunkSize = sizeof(word_t) * 8;
102
103
44.4k
  SimpleBitstreamCursor() = default;
104
  explicit SimpleBitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
105
18.9k
      : BitcodeBytes(BitcodeBytes) {}
106
  explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
107
      : BitcodeBytes(reinterpret_cast<const uint8_t *>(BitcodeBytes.data()),
108
30.5k
                     BitcodeBytes.size()) {}
109
  explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
110
199
      : SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}
111
112
396k
  bool canSkipToPos(size_t pos) const {
113
396k
    // pos can be skipped to if it is a valid address or one byte past the end.
114
396k
    return pos <= BitcodeBytes.size();
115
396k
  }
116
117
31.2M
  bool AtEndOfStream() {
118
31.2M
    return BitsInCurWord == 0 && 
BitcodeBytes.size() <= NextChar2.54M
;
119
31.2M
  }
120
121
  /// Return the bit # of the bit we are reading.
122
1.81M
  uint64_t GetCurrentBitNo() const {
123
1.81M
    return NextChar*CHAR_BIT - BitsInCurWord;
124
1.81M
  }
125
126
  // Return the byte # of the current bit.
127
34.5k
  uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }
128
129
33.3k
  ArrayRef<uint8_t> getBitcodeBytes() const { return BitcodeBytes; }
130
131
  /// Reset the stream to the specified bit number.
132
1.97M
  void JumpToBit(uint64_t BitNo) {
133
1.97M
    size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
134
1.97M
    unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
135
1.97M
    assert(canSkipToPos(ByteNo) && "Invalid location");
136
1.97M
137
1.97M
    // Move the cursor to the right word.
138
1.97M
    NextChar = ByteNo;
139
1.97M
    BitsInCurWord = 0;
140
1.97M
141
1.97M
    // Skip over any bits that are already consumed.
142
1.97M
    if (WordBitNo)
143
1.70M
      Read(WordBitNo);
144
1.97M
  }
145
146
  /// Get a pointer into the bitstream at the specified byte offset.
147
237k
  const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
148
237k
    return BitcodeBytes.data() + ByteNo;
149
237k
  }
150
151
  /// Get a pointer into the bitstream at the specified bit offset.
152
  ///
153
  /// The bit offset must be on a byte boundary.
154
237k
  const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
155
237k
    assert(!(BitNo % 8) && "Expected bit on byte boundary");
156
237k
    return getPointerToByte(BitNo / 8, NumBytes);
157
237k
  }
158
159
35.7M
  void fillCurWord() {
160
35.7M
    if (NextChar >= BitcodeBytes.size())
161
0
      report_fatal_error("Unexpected end of file");
162
35.7M
163
35.7M
    // Read the next word from the stream.
164
35.7M
    const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
165
35.7M
    unsigned BytesRead;
166
35.7M
    if (BitcodeBytes.size() >= NextChar + sizeof(word_t)) {
167
35.7M
      BytesRead = sizeof(word_t);
168
35.7M
      CurWord =
169
35.7M
          support::endian::read<word_t, support::little, support::unaligned>(
170
35.7M
              NextCharPtr);
171
35.7M
    } else {
172
24.8k
      // Short read.
173
24.8k
      BytesRead = BitcodeBytes.size() - NextChar;
174
24.8k
      CurWord = 0;
175
124k
      for (unsigned B = 0; B != BytesRead; 
++B99.4k
)
176
99.4k
        CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
177
24.8k
    }
178
35.7M
    NextChar += BytesRead;
179
35.7M
    BitsInCurWord = BytesRead * 8;
180
35.7M
  }
181
182
361M
  word_t Read(unsigned NumBits) {
183
361M
    static const unsigned BitsInWord = MaxChunkSize;
184
361M
185
361M
    assert(NumBits && NumBits <= BitsInWord &&
186
361M
           "Cannot return zero or more than BitsInWord bits!");
187
361M
188
361M
    static const unsigned Mask = sizeof(word_t) > 4 ? 
0x3f0
: 0x1f;
189
361M
190
361M
    // If the field is fully contained by CurWord, return it quickly.
191
361M
    if (BitsInCurWord >= NumBits) {
192
325M
      word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));
193
325M
194
325M
      // Use a mask to avoid undefined behavior.
195
325M
      CurWord >>= (NumBits & Mask);
196
325M
197
325M
      BitsInCurWord -= NumBits;
198
325M
      return R;
199
325M
    }
200
35.7M
201
35.7M
    word_t R = BitsInCurWord ? 
CurWord25.1M
:
010.6M
;
202
35.7M
    unsigned BitsLeft = NumBits - BitsInCurWord;
203
35.7M
204
35.7M
    fillCurWord();
205
35.7M
206
35.7M
    // If we run out of data, abort.
207
35.7M
    if (BitsLeft > BitsInCurWord)
208
0
      report_fatal_error("Unexpected end of file");
209
35.7M
210
35.7M
    word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
211
35.7M
212
35.7M
    // Use a mask to avoid undefined behavior.
213
35.7M
    CurWord >>= (BitsLeft & Mask);
214
35.7M
215
35.7M
    BitsInCurWord -= BitsLeft;
216
35.7M
217
35.7M
    R |= R2 << (NumBits - BitsLeft);
218
35.7M
219
35.7M
    return R;
220
35.7M
  }
221
222
34.6M
  uint32_t ReadVBR(unsigned NumBits) {
223
34.6M
    uint32_t Piece = Read(NumBits);
224
34.6M
    if ((Piece & (1U << (NumBits-1))) == 0)
225
31.1M
      return Piece;
226
3.49M
227
3.49M
    uint32_t Result = 0;
228
3.49M
    unsigned NextBit = 0;
229
6.99M
    while (
true6.99M
) {
230
6.99M
      Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
231
6.99M
232
6.99M
      if ((Piece & (1U << (NumBits-1))) == 0)
233
3.49M
        return Result;
234
3.50M
235
3.50M
      NextBit += NumBits-1;
236
3.50M
      Piece = Read(NumBits);
237
3.50M
    }
238
3.49M
  }
239
240
  // Read a VBR that may have a value up to 64-bits in size. The chunk size of
241
  // the VBR must still be <= 32 bits though.
242
100M
  uint64_t ReadVBR64(unsigned NumBits) {
243
100M
    uint32_t Piece = Read(NumBits);
244
100M
    if ((Piece & (1U << (NumBits-1))) == 0)
245
58.5M
      return uint64_t(Piece);
246
41.4M
247
41.4M
    uint64_t Result = 0;
248
41.4M
    unsigned NextBit = 0;
249
88.7M
    while (
true88.7M
) {
250
88.7M
      Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
251
88.7M
252
88.7M
      if ((Piece & (1U << (NumBits-1))) == 0)
253
41.4M
        return Result;
254
47.3M
255
47.3M
      NextBit += NumBits-1;
256
47.3M
      Piece = Read(NumBits);
257
47.3M
    }
258
41.4M
  }
259
260
2.65M
  void SkipToFourByteBoundary() {
261
2.65M
    // If word_t is 64-bits and if we've read less than 32 bits, just dump
262
2.65M
    // the bits we have up to the next 32-bit boundary.
263
2.65M
    if (sizeof(word_t) > 4 &&
264
2.65M
        BitsInCurWord >= 32) {
265
1.38M
      CurWord >>= BitsInCurWord-32;
266
1.38M
      BitsInCurWord = 32;
267
1.38M
      return;
268
1.38M
    }
269
1.26M
270
1.26M
    BitsInCurWord = 0;
271
1.26M
  }
272
273
  /// Skip to the end of the file.
274
0
  void skipToEnd() { NextChar = BitcodeBytes.size(); }
275
};
276
277
/// When advancing through a bitstream cursor, each advance can discover a few
278
/// different kinds of entries:
279
struct BitstreamEntry {
280
  enum {
281
    Error,    // Malformed bitcode was found.
282
    EndBlock, // We've reached the end of the current block, (or the end of the
283
              // file, which is treated like a series of EndBlock records.
284
    SubBlock, // This is the start of a new subblock of a specific ID.
285
    Record    // This is a record with a specific AbbrevID.
286
  } Kind;
287
288
  unsigned ID;
289
290
7.24k
  static BitstreamEntry getError() {
291
7.24k
    BitstreamEntry E; E.Kind = Error; return E;
292
7.24k
  }
293
294
1.12M
  static BitstreamEntry getEndBlock() {
295
1.12M
    BitstreamEntry E; E.Kind = EndBlock; return E;
296
1.12M
  }
297
298
905k
  static BitstreamEntry getSubBlock(unsigned ID) {
299
905k
    BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
300
905k
  }
301
302
27.4M
  static BitstreamEntry getRecord(unsigned AbbrevID) {
303
27.4M
    BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
304
27.4M
  }
305
};
306
307
/// This represents a position within a bitcode file, implemented on top of a
308
/// SimpleBitstreamCursor.
309
///
310
/// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
311
/// be passed by value.
312
class BitstreamCursor : SimpleBitstreamCursor {
313
  // This is the declared size of code values used for the current block, in
314
  // bits.
315
  unsigned CurCodeSize = 2;
316
317
  /// Abbrevs installed at in this block.
318
  std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
319
320
  struct Block {
321
    unsigned PrevCodeSize;
322
    std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
323
324
1.15M
    explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
325
  };
326
327
  /// This tracks the codesize of parent blocks.
328
  SmallVector<Block, 8> BlockScope;
329
330
  BitstreamBlockInfo *BlockInfo = nullptr;
331
332
public:
333
  static const size_t MaxChunkSize = sizeof(word_t) * 8;
334
335
44.4k
  BitstreamCursor() = default;
336
  explicit BitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
337
18.9k
      : SimpleBitstreamCursor(BitcodeBytes) {}
338
  explicit BitstreamCursor(StringRef BitcodeBytes)
339
16.4k
      : SimpleBitstreamCursor(BitcodeBytes) {}
340
  explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
341
199
      : SimpleBitstreamCursor(BitcodeBytes) {}
342
343
  using SimpleBitstreamCursor::canSkipToPos;
344
  using SimpleBitstreamCursor::AtEndOfStream;
345
  using SimpleBitstreamCursor::getBitcodeBytes;
346
  using SimpleBitstreamCursor::GetCurrentBitNo;
347
  using SimpleBitstreamCursor::getCurrentByteNo;
348
  using SimpleBitstreamCursor::getPointerToByte;
349
  using SimpleBitstreamCursor::JumpToBit;
350
  using SimpleBitstreamCursor::fillCurWord;
351
  using SimpleBitstreamCursor::Read;
352
  using SimpleBitstreamCursor::ReadVBR;
353
  using SimpleBitstreamCursor::ReadVBR64;
354
355
  /// Return the number of bits used to encode an abbrev #.
356
335k
  unsigned getAbbrevIDWidth() const { return CurCodeSize; }
357
358
  /// Flags that modify the behavior of advance().
359
  enum {
360
    /// If this flag is used, the advance() method does not automatically pop
361
    /// the block scope when the end of a block is reached.
362
    AF_DontPopBlockAtEnd = 1,
363
364
    /// If this flag is used, abbrev entries are returned just like normal
365
    /// records.
366
    AF_DontAutoprocessAbbrevs = 2
367
  };
368
369
  /// Advance the current bitstream, returning the next entry in the stream.
370
29.5M
  BitstreamEntry advance(unsigned Flags = 0) {
371
29.8M
    while (
true29.8M
) {
372
29.8M
      if (AtEndOfStream())
373
7.23k
        return BitstreamEntry::getError();
374
29.8M
375
29.8M
      unsigned Code = ReadCode();
376
29.8M
      if (Code == bitc::END_BLOCK) {
377
1.12M
        // Pop the end of the block unless Flags tells us not to.
378
1.12M
        if (!(Flags & AF_DontPopBlockAtEnd) && 
ReadBlockEnd()1.12M
)
379
6
          return BitstreamEntry::getError();
380
1.12M
        return BitstreamEntry::getEndBlock();
381
1.12M
      }
382
28.7M
383
28.7M
      if (Code == bitc::ENTER_SUBBLOCK)
384
905k
        return BitstreamEntry::getSubBlock(ReadSubBlockID());
385
27.8M
386
27.8M
      if (Code == bitc::DEFINE_ABBREV &&
387
27.8M
          
!(Flags & AF_DontAutoprocessAbbrevs)501k
) {
388
359k
        // We read and accumulate abbrev's, the client can't do anything with
389
359k
        // them anyway.
390
359k
        ReadAbbrevRecord();
391
359k
        continue;
392
359k
      }
393
27.4M
394
27.4M
      return BitstreamEntry::getRecord(Code);
395
27.4M
    }
396
29.5M
  }
397
398
  /// This is a convenience function for clients that don't expect any
399
  /// subblocks. This just skips over them automatically.
400
16.4M
  BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
401
16.4M
    while (
true16.4M
) {
402
16.4M
      // If we found a normal entry, return it.
403
16.4M
      BitstreamEntry Entry = advance(Flags);
404
16.4M
      if (Entry.Kind != BitstreamEntry::SubBlock)
405
16.4M
        return Entry;
406
3.91k
407
3.91k
      // If we found a sub-block, just skip over it and check the next entry.
408
3.91k
      if (SkipBlock())
409
0
        return BitstreamEntry::getError();
410
3.91k
    }
411
16.4M
  }
412
413
30.4M
  unsigned ReadCode() {
414
30.4M
    return Read(CurCodeSize);
415
30.4M
  }
416
417
  // Block header:
418
  //    [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
419
420
  /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
421
905k
  unsigned ReadSubBlockID() {
422
905k
    return ReadVBR(bitc::BlockIDWidth);
423
905k
  }
424
425
  /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
426
  /// of this block. If the block record is malformed, return true.
427
134k
  bool SkipBlock() {
428
134k
    // Read and ignore the codelen value.  Since we are skipping this block, we
429
134k
    // don't care what code widths are used inside of it.
430
134k
    ReadVBR(bitc::CodeLenWidth);
431
134k
    SkipToFourByteBoundary();
432
134k
    size_t NumFourBytes = Read(bitc::BlockSizeWidth);
433
134k
434
134k
    // Check that the block wasn't partially defined, and that the offset isn't
435
134k
    // bogus.
436
134k
    size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
437
134k
    if (AtEndOfStream() || 
!canSkipToPos(SkipTo/8)134k
)
438
6
      return true;
439
134k
440
134k
    JumpToBit(SkipTo);
441
134k
    return false;
442
134k
  }
443
444
  /// Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true
445
  /// if the block has an error.
446
  bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
447
448
1.12M
  bool ReadBlockEnd() {
449
1.12M
    if (BlockScope.empty()) 
return true6
;
450
1.12M
451
1.12M
    // Block tail:
452
1.12M
    //    [END_BLOCK, <align4bytes>]
453
1.12M
    SkipToFourByteBoundary();
454
1.12M
455
1.12M
    popBlockScope();
456
1.12M
    return false;
457
1.12M
  }
458
459
private:
460
1.12M
  void popBlockScope() {
461
1.12M
    CurCodeSize = BlockScope.back().PrevCodeSize;
462
1.12M
463
1.12M
    CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
464
1.12M
    BlockScope.pop_back();
465
1.12M
  }
466
467
  //===--------------------------------------------------------------------===//
468
  // Record Processing
469
  //===--------------------------------------------------------------------===//
470
471
public:
472
  /// Return the abbreviation for the specified AbbrevId.
473
17.9M
  const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
474
17.9M
    unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
475
17.9M
    if (AbbrevNo >= CurAbbrevs.size())
476
0
      report_fatal_error("Invalid abbrev number");
477
17.9M
    return CurAbbrevs[AbbrevNo].get();
478
17.9M
  }
479
480
  /// Read the current record and discard it, returning the code for the record.
481
  unsigned skipRecord(unsigned AbbrevID);
482
483
  unsigned readRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
484
                      StringRef *Blob = nullptr);
485
486
  //===--------------------------------------------------------------------===//
487
  // Abbrev Processing
488
  //===--------------------------------------------------------------------===//
489
  void ReadAbbrevRecord();
490
491
  /// Read and return a block info block from the bitstream. If an error was
492
  /// encountered, return None.
493
  ///
494
  /// \param ReadBlockInfoNames Whether to read block/record name information in
495
  /// the BlockInfo block. Only llvm-bcanalyzer uses this.
496
  Optional<BitstreamBlockInfo>
497
  ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
498
499
  /// Set the block info to be used by this BitstreamCursor to interpret
500
  /// abbreviated records.
501
8.42k
  void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
502
};
503
504
} // end llvm namespace
505
506
#endif // LLVM_BITCODE_BITSTREAMREADER_H