Bug Summary

File:llvm/include/llvm/Bitstream/BitstreamReader.h
Warning:line 221, column 39
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::SimpleBitstreamCursor::word_t'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name BitstreamReader.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Bitstream/Reader -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Bitstream/Reader -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp

1//===- BitstreamReader.cpp - BitstreamReader implementation ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Bitstream/BitstreamReader.h"
10#include "llvm/ADT/StringRef.h"
11#include <cassert>
12#include <string>
13
14using namespace llvm;
15
16//===----------------------------------------------------------------------===//
17// BitstreamCursor implementation
18//===----------------------------------------------------------------------===//
19
20/// Having read the ENTER_SUBBLOCK abbrevid, enter the block.
21Error BitstreamCursor::EnterSubBlock(unsigned BlockID, unsigned *NumWordsP) {
22 // Save the current block's state on BlockScope.
23 BlockScope.push_back(Block(CurCodeSize));
24 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
25
26 // Add the abbrevs specific to this block to the CurAbbrevs list.
27 if (BlockInfo) {
28 if (const BitstreamBlockInfo::BlockInfo *Info =
29 BlockInfo->getBlockInfo(BlockID)) {
30 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
31 Info->Abbrevs.end());
32 }
33 }
34
35 // Get the codesize of this block.
36 Expected<uint32_t> MaybeVBR = ReadVBR(bitc::CodeLenWidth);
37 if (!MaybeVBR)
38 return MaybeVBR.takeError();
39 CurCodeSize = MaybeVBR.get();
40
41 if (CurCodeSize > MaxChunkSize)
42 return llvm::createStringError(
43 std::errc::illegal_byte_sequence,
44 "can't read more than %zu at a time, trying to read %u", +MaxChunkSize,
45 CurCodeSize);
46
47 SkipToFourByteBoundary();
48 Expected<word_t> MaybeNum = Read(bitc::BlockSizeWidth);
49 if (!MaybeNum)
50 return MaybeNum.takeError();
51 word_t NumWords = MaybeNum.get();
52 if (NumWordsP)
53 *NumWordsP = NumWords;
54
55 if (CurCodeSize == 0)
56 return llvm::createStringError(
57 std::errc::illegal_byte_sequence,
58 "can't enter sub-block: current code size is 0");
59 if (AtEndOfStream())
60 return llvm::createStringError(
61 std::errc::illegal_byte_sequence,
62 "can't enter sub block: already at end of stream");
63
64 return Error::success();
65}
66
67static Expected<uint64_t> readAbbreviatedField(BitstreamCursor &Cursor,
68 const BitCodeAbbrevOp &Op) {
69 assert(!Op.isLiteral() && "Not to be used with literals!")((!Op.isLiteral() && "Not to be used with literals!")
? static_cast<void> (0) : __assert_fail ("!Op.isLiteral() && \"Not to be used with literals!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 69, __PRETTY_FUNCTION__))
;
70
71 // Decode the value as we are commanded.
72 switch (Op.getEncoding()) {
73 case BitCodeAbbrevOp::Array:
74 case BitCodeAbbrevOp::Blob:
75 llvm_unreachable("Should not reach here")::llvm::llvm_unreachable_internal("Should not reach here", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 75)
;
76 case BitCodeAbbrevOp::Fixed:
77 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize)(((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize) ?
static_cast<void> (0) : __assert_fail ("(unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 77, __PRETTY_FUNCTION__))
;
78 return Cursor.Read((unsigned)Op.getEncodingData());
79 case BitCodeAbbrevOp::VBR:
80 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize)(((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize) ?
static_cast<void> (0) : __assert_fail ("(unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 80, __PRETTY_FUNCTION__))
;
81 return Cursor.ReadVBR64((unsigned)Op.getEncodingData());
82 case BitCodeAbbrevOp::Char6:
83 if (Expected<unsigned> Res = Cursor.Read(6))
84 return BitCodeAbbrevOp::DecodeChar6(Res.get());
85 else
86 return Res.takeError();
87 }
88 llvm_unreachable("invalid abbreviation encoding")::llvm::llvm_unreachable_internal("invalid abbreviation encoding"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 88)
;
89}
90
91/// skipRecord - Read the current record and discard it.
92Expected<unsigned> BitstreamCursor::skipRecord(unsigned AbbrevID) {
93 // Skip unabbreviated records by reading past their entries.
94 if (AbbrevID == bitc::UNABBREV_RECORD) {
95 Expected<uint32_t> MaybeCode = ReadVBR(6);
96 if (!MaybeCode)
97 return MaybeCode.takeError();
98 unsigned Code = MaybeCode.get();
99 Expected<uint32_t> MaybeVBR = ReadVBR(6);
100 if (!MaybeVBR)
101 return MaybeVBR.get();
102 unsigned NumElts = MaybeVBR.get();
103 for (unsigned i = 0; i != NumElts; ++i)
104 if (Expected<uint64_t> Res = ReadVBR64(6))
105 ; // Skip!
106 else
107 return Res.takeError();
108 return Code;
109 }
110
111 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
112 const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
113 unsigned Code;
114 if (CodeOp.isLiteral())
115 Code = CodeOp.getLiteralValue();
116 else {
117 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
118 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
119 return llvm::createStringError(
120 std::errc::illegal_byte_sequence,
121 "Abbreviation starts with an Array or a Blob");
122 Expected<uint64_t> MaybeCode = readAbbreviatedField(*this, CodeOp);
123 if (!MaybeCode)
124 return MaybeCode.takeError();
125 Code = MaybeCode.get();
126 }
127
128 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i < e; ++i) {
129 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
130 if (Op.isLiteral())
131 continue;
132
133 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
134 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
135 if (Expected<uint64_t> MaybeField = readAbbreviatedField(*this, Op))
136 continue;
137 else
138 return MaybeField.takeError();
139 }
140
141 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
142 // Array case. Read the number of elements as a vbr6.
143 Expected<uint32_t> MaybeNum = ReadVBR(6);
144 if (!MaybeNum)
145 return MaybeNum.takeError();
146 unsigned NumElts = MaybeNum.get();
147
148 // Get the element encoding.
149 assert(i+2 == e && "array op not second to last?")((i+2 == e && "array op not second to last?") ? static_cast
<void> (0) : __assert_fail ("i+2 == e && \"array op not second to last?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 149, __PRETTY_FUNCTION__))
;
150 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
151
152 // Read all the elements.
153 // Decode the value as we are commanded.
154 switch (EltEnc.getEncoding()) {
155 default:
156 report_fatal_error("Array element type can't be an Array or a Blob");
157 case BitCodeAbbrevOp::Fixed:
158 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize)(((unsigned)EltEnc.getEncodingData() <= MaxChunkSize) ? static_cast
<void> (0) : __assert_fail ("(unsigned)EltEnc.getEncodingData() <= MaxChunkSize"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 158, __PRETTY_FUNCTION__))
;
159 if (Error Err = JumpToBit(GetCurrentBitNo() +
160 NumElts * EltEnc.getEncodingData()))
161 return std::move(Err);
162 break;
163 case BitCodeAbbrevOp::VBR:
164 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize)(((unsigned)EltEnc.getEncodingData() <= MaxChunkSize) ? static_cast
<void> (0) : __assert_fail ("(unsigned)EltEnc.getEncodingData() <= MaxChunkSize"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 164, __PRETTY_FUNCTION__))
;
165 for (; NumElts; --NumElts)
166 if (Expected<uint64_t> Res =
167 ReadVBR64((unsigned)EltEnc.getEncodingData()))
168 ; // Skip!
169 else
170 return Res.takeError();
171 break;
172 case BitCodeAbbrevOp::Char6:
173 if (Error Err = JumpToBit(GetCurrentBitNo() + NumElts * 6))
174 return std::move(Err);
175 break;
176 }
177 continue;
178 }
179
180 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob)((Op.getEncoding() == BitCodeAbbrevOp::Blob) ? static_cast<
void> (0) : __assert_fail ("Op.getEncoding() == BitCodeAbbrevOp::Blob"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 180, __PRETTY_FUNCTION__))
;
181 // Blob case. Read the number of bytes as a vbr6.
182 Expected<uint32_t> MaybeNum = ReadVBR(6);
183 if (!MaybeNum)
184 return MaybeNum.takeError();
185 unsigned NumElts = MaybeNum.get();
186 SkipToFourByteBoundary(); // 32-bit alignment
187
188 // Figure out where the end of this blob will be including tail padding.
189 size_t NewEnd = GetCurrentBitNo()+((NumElts+3)&~3)*8;
190
191 // If this would read off the end of the bitcode file, just set the
192 // record to empty and return.
193 if (!canSkipToPos(NewEnd/8)) {
194 skipToEnd();
195 break;
196 }
197
198 // Skip over the blob.
199 if (Error Err = JumpToBit(NewEnd))
200 return std::move(Err);
201 }
202 return Code;
203}
204
205Expected<unsigned> BitstreamCursor::readRecord(unsigned AbbrevID,
206 SmallVectorImpl<uint64_t> &Vals,
207 StringRef *Blob) {
208 if (AbbrevID == bitc::UNABBREV_RECORD) {
209 Expected<uint32_t> MaybeCode = ReadVBR(6);
210 if (!MaybeCode)
211 return MaybeCode.takeError();
212 uint32_t Code = MaybeCode.get();
213 Expected<uint32_t> MaybeNumElts = ReadVBR(6);
214 if (!MaybeNumElts)
215 return MaybeNumElts.takeError();
216 uint32_t NumElts = MaybeNumElts.get();
217
218 for (unsigned i = 0; i != NumElts; ++i)
219 if (Expected<uint64_t> MaybeVal = ReadVBR64(6))
220 Vals.push_back(MaybeVal.get());
221 else
222 return MaybeVal.takeError();
223 return Code;
224 }
225
226 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
227
228 // Read the record code first.
229 assert(Abbv->getNumOperandInfos() != 0 && "no record code in abbreviation?")((Abbv->getNumOperandInfos() != 0 && "no record code in abbreviation?"
) ? static_cast<void> (0) : __assert_fail ("Abbv->getNumOperandInfos() != 0 && \"no record code in abbreviation?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 229, __PRETTY_FUNCTION__))
;
230 const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
231 unsigned Code;
232 if (CodeOp.isLiteral())
233 Code = CodeOp.getLiteralValue();
234 else {
235 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
236 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
237 report_fatal_error("Abbreviation starts with an Array or a Blob");
238 if (Expected<uint64_t> MaybeCode = readAbbreviatedField(*this, CodeOp))
239 Code = MaybeCode.get();
240 else
241 return MaybeCode.takeError();
242 }
243
244 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
245 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
246 if (Op.isLiteral()) {
247 Vals.push_back(Op.getLiteralValue());
248 continue;
249 }
250
251 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
252 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
253 if (Expected<uint64_t> MaybeVal = readAbbreviatedField(*this, Op))
254 Vals.push_back(MaybeVal.get());
255 else
256 return MaybeVal.takeError();
257 continue;
258 }
259
260 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
261 // Array case. Read the number of elements as a vbr6.
262 Expected<uint32_t> MaybeNumElts = ReadVBR(6);
263 if (!MaybeNumElts)
264 return MaybeNumElts.takeError();
265 uint32_t NumElts = MaybeNumElts.get();
266
267 // Get the element encoding.
268 if (i + 2 != e)
269 report_fatal_error("Array op not second to last");
270 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
271 if (!EltEnc.isEncoding())
272 report_fatal_error(
273 "Array element type has to be an encoding of a type");
274
275 // Read all the elements.
276 switch (EltEnc.getEncoding()) {
277 default:
278 report_fatal_error("Array element type can't be an Array or a Blob");
279 case BitCodeAbbrevOp::Fixed:
280 for (; NumElts; --NumElts)
281 if (Expected<SimpleBitstreamCursor::word_t> MaybeVal =
282 Read((unsigned)EltEnc.getEncodingData()))
283 Vals.push_back(MaybeVal.get());
284 else
285 return MaybeVal.takeError();
286 break;
287 case BitCodeAbbrevOp::VBR:
288 for (; NumElts; --NumElts)
289 if (Expected<uint64_t> MaybeVal =
290 ReadVBR64((unsigned)EltEnc.getEncodingData()))
291 Vals.push_back(MaybeVal.get());
292 else
293 return MaybeVal.takeError();
294 break;
295 case BitCodeAbbrevOp::Char6:
296 for (; NumElts; --NumElts)
297 if (Expected<SimpleBitstreamCursor::word_t> MaybeVal = Read(6))
298 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(MaybeVal.get()));
299 else
300 return MaybeVal.takeError();
301 }
302 continue;
303 }
304
305 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob)((Op.getEncoding() == BitCodeAbbrevOp::Blob) ? static_cast<
void> (0) : __assert_fail ("Op.getEncoding() == BitCodeAbbrevOp::Blob"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 305, __PRETTY_FUNCTION__))
;
306 // Blob case. Read the number of bytes as a vbr6.
307 Expected<uint32_t> MaybeNumElts = ReadVBR(6);
308 if (!MaybeNumElts)
309 return MaybeNumElts.takeError();
310 uint32_t NumElts = MaybeNumElts.get();
311 SkipToFourByteBoundary(); // 32-bit alignment
312
313 // Figure out where the end of this blob will be including tail padding.
314 size_t CurBitPos = GetCurrentBitNo();
315 size_t NewEnd = CurBitPos+((NumElts+3)&~3)*8;
316
317 // If this would read off the end of the bitcode file, just set the
318 // record to empty and return.
319 if (!canSkipToPos(NewEnd/8)) {
320 Vals.append(NumElts, 0);
321 skipToEnd();
322 break;
323 }
324
325 // Otherwise, inform the streamer that we need these bytes in memory. Skip
326 // over tail padding first, in case jumping to NewEnd invalidates the Blob
327 // pointer.
328 if (Error Err = JumpToBit(NewEnd))
329 return std::move(Err);
330 const char *Ptr = (const char *)getPointerToBit(CurBitPos, NumElts);
331
332 // If we can return a reference to the data, do so to avoid copying it.
333 if (Blob) {
334 *Blob = StringRef(Ptr, NumElts);
335 } else {
336 // Otherwise, unpack into Vals with zero extension.
337 for (; NumElts; --NumElts)
338 Vals.push_back((unsigned char)*Ptr++);
339 }
340 }
341
342 return Code;
343}
344
345Error BitstreamCursor::ReadAbbrevRecord() {
346 auto Abbv = std::make_shared<BitCodeAbbrev>();
347 Expected<uint32_t> MaybeNumOpInfo = ReadVBR(5);
348 if (!MaybeNumOpInfo)
349 return MaybeNumOpInfo.takeError();
350 unsigned NumOpInfo = MaybeNumOpInfo.get();
351 for (unsigned i = 0; i != NumOpInfo; ++i) {
352 Expected<word_t> MaybeIsLiteral = Read(1);
353 if (!MaybeIsLiteral)
354 return MaybeIsLiteral.takeError();
355 bool IsLiteral = MaybeIsLiteral.get();
356 if (IsLiteral) {
357 Expected<uint64_t> MaybeOp = ReadVBR64(8);
358 if (!MaybeOp)
359 return MaybeOp.takeError();
360 Abbv->Add(BitCodeAbbrevOp(MaybeOp.get()));
361 continue;
362 }
363
364 Expected<word_t> MaybeEncoding = Read(3);
365 if (!MaybeEncoding)
366 return MaybeEncoding.takeError();
367 BitCodeAbbrevOp::Encoding E =
368 (BitCodeAbbrevOp::Encoding)MaybeEncoding.get();
369 if (BitCodeAbbrevOp::hasEncodingData(E)) {
370 Expected<uint64_t> MaybeData = ReadVBR64(5);
371 if (!MaybeData)
372 return MaybeData.takeError();
373 uint64_t Data = MaybeData.get();
374
375 // As a special case, handle fixed(0) (i.e., a fixed field with zero bits)
376 // and vbr(0) as a literal zero. This is decoded the same way, and avoids
377 // a slow path in Read() to have to handle reading zero bits.
378 if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
379 Data == 0) {
380 Abbv->Add(BitCodeAbbrevOp(0));
381 continue;
382 }
383
384 if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
385 Data > MaxChunkSize)
386 report_fatal_error(
387 "Fixed or VBR abbrev record with size > MaxChunkData");
388
389 Abbv->Add(BitCodeAbbrevOp(E, Data));
390 } else
391 Abbv->Add(BitCodeAbbrevOp(E));
392 }
393
394 if (Abbv->getNumOperandInfos() == 0)
395 report_fatal_error("Abbrev record with no operands");
396 CurAbbrevs.push_back(std::move(Abbv));
397
398 return Error::success();
399}
400
401Expected<Optional<BitstreamBlockInfo>>
402BitstreamCursor::ReadBlockInfoBlock(bool ReadBlockInfoNames) {
403 if (llvm::Error Err = EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID))
1
Assuming the condition is false
2
Taking false branch
404 return std::move(Err);
405
406 BitstreamBlockInfo NewBlockInfo;
407
408 SmallVector<uint64_t, 64> Record;
409 BitstreamBlockInfo::BlockInfo *CurBlockInfo = nullptr;
410
411 // Read all the records for this module.
412 while (true) {
3
Loop condition is true. Entering loop body
11
Loop condition is true. Entering loop body
413 Expected<BitstreamEntry> MaybeEntry =
414 advanceSkippingSubblocks(AF_DontAutoprocessAbbrevs);
12
Calling 'BitstreamCursor::advanceSkippingSubblocks'
415 if (!MaybeEntry)
4
Taking false branch
416 return MaybeEntry.takeError();
417 BitstreamEntry Entry = MaybeEntry.get();
418
419 switch (Entry.Kind) {
5
Control jumps to 'case Record:' at line 425
420 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
421 case llvm::BitstreamEntry::Error:
422 return None;
423 case llvm::BitstreamEntry::EndBlock:
424 return std::move(NewBlockInfo);
425 case llvm::BitstreamEntry::Record:
426 // The interesting case.
427 break;
6
Execution continues on line 431
428 }
429
430 // Read abbrev records, associate them with CurBID.
431 if (Entry.ID
6.1
Field 'ID' is not equal to DEFINE_ABBREV
6.1
Field 'ID' is not equal to DEFINE_ABBREV
== bitc::DEFINE_ABBREV) {
7
Taking false branch
432 if (!CurBlockInfo) return None;
433 if (Error Err = ReadAbbrevRecord())
434 return std::move(Err);
435
436 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
437 // appropriate BlockInfo.
438 CurBlockInfo->Abbrevs.push_back(std::move(CurAbbrevs.back()));
439 CurAbbrevs.pop_back();
440 continue;
441 }
442
443 // Read a record.
444 Record.clear();
445 Expected<unsigned> MaybeBlockInfo = readRecord(Entry.ID, Record);
446 if (!MaybeBlockInfo)
8
Taking false branch
447 return MaybeBlockInfo.takeError();
448 switch (MaybeBlockInfo.get()) {
9
Control jumps to the 'default' case at line 449
449 default:
450 break; // Default behavior, ignore unknown content.
10
Execution continues on line 515
451 case bitc::BLOCKINFO_CODE_SETBID:
452 if (Record.size() < 1)
453 return None;
454 CurBlockInfo = &NewBlockInfo.getOrCreateBlockInfo((unsigned)Record[0]);
455 break;
456 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
457 if (!CurBlockInfo)
458 return None;
459 if (!ReadBlockInfoNames)
460 break; // Ignore name.
461 std::string Name;
462 for (unsigned i = 0, e = Record.size(); i != e; ++i)
463 Name += (char)Record[i];
464 CurBlockInfo->Name = Name;
465 break;
466 }
467 case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
468 if (!CurBlockInfo) return None;
469 if (!ReadBlockInfoNames)
470 break; // Ignore name.
471 std::string Name;
472 for (unsigned i = 1, e = Record.size(); i != e; ++i)
473 Name += (char)Record[i];
474 CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
475 Name));
476 break;
477 }
478 }
479 }
480}

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Bitstream/BitstreamReader.h

1//===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This header defines the BitstreamReader class. This class can be used to
10// read an arbitrary bitstream, regardless of its contents.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_BITSTREAM_BITSTREAMREADER_H
15#define LLVM_BITSTREAM_BITSTREAMREADER_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/Bitstream/BitCodes.h"
20#include "llvm/Support/Endian.h"
21#include "llvm/Support/Error.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
35namespace llvm {
36
37/// This class maintains the abbreviations read from a block info block.
38class BitstreamBlockInfo {
39public:
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 = 0;
44 std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
45 std::string Name;
46 std::vector<std::pair<unsigned, std::string>> RecordNames;
47 };
48
49private:
50 std::vector<BlockInfo> BlockInfoRecords;
51
52public:
53 /// If there is block info for the specified ID, return it, otherwise return
54 /// null.
55 const BlockInfo *getBlockInfo(unsigned BlockID) const {
56 // Common case, the most recent entry matches BlockID.
57 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
58 return &BlockInfoRecords.back();
59
60 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
61 i != e; ++i)
62 if (BlockInfoRecords[i].BlockID == BlockID)
63 return &BlockInfoRecords[i];
64 return nullptr;
65 }
66
67 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
68 if (const BlockInfo *BI = getBlockInfo(BlockID))
69 return *const_cast<BlockInfo*>(BI);
70
71 // Otherwise, add a new record.
72 BlockInfoRecords.emplace_back();
73 BlockInfoRecords.back().BlockID = BlockID;
74 return BlockInfoRecords.back();
75 }
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.
81class SimpleBitstreamCursor {
82 ArrayRef<uint8_t> BitcodeBytes;
83 size_t NextChar = 0;
84
85public:
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
93private:
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
100public:
101 static const constexpr size_t MaxChunkSize = sizeof(word_t) * 8;
102
103 SimpleBitstreamCursor() = default;
104 explicit SimpleBitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
105 : BitcodeBytes(BitcodeBytes) {}
106 explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
107 : BitcodeBytes(arrayRefFromStringRef(BitcodeBytes)) {}
108 explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
109 : SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}
110
111 bool canSkipToPos(size_t pos) const {
112 // pos can be skipped to if it is a valid address or one byte past the end.
113 return pos <= BitcodeBytes.size();
114 }
115
116 bool AtEndOfStream() {
117 return BitsInCurWord == 0 && BitcodeBytes.size() <= NextChar;
118 }
119
120 /// Return the bit # of the bit we are reading.
121 uint64_t GetCurrentBitNo() const {
122 return NextChar*CHAR_BIT8 - BitsInCurWord;
123 }
124
125 // Return the byte # of the current bit.
126 uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }
127
128 ArrayRef<uint8_t> getBitcodeBytes() const { return BitcodeBytes; }
129
130 /// Reset the stream to the specified bit number.
131 Error JumpToBit(uint64_t BitNo) {
132 size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
133 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
134 assert(canSkipToPos(ByteNo) && "Invalid location")((canSkipToPos(ByteNo) && "Invalid location") ? static_cast
<void> (0) : __assert_fail ("canSkipToPos(ByteNo) && \"Invalid location\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Bitstream/BitstreamReader.h"
, 134, __PRETTY_FUNCTION__))
;
135
136 // Move the cursor to the right word.
137 NextChar = ByteNo;
138 BitsInCurWord = 0;
139
140 // Skip over any bits that are already consumed.
141 if (WordBitNo) {
142 if (Expected<word_t> Res = Read(WordBitNo))
143 return Error::success();
144 else
145 return Res.takeError();
146 }
147
148 return Error::success();
149 }
150
151 /// Get a pointer into the bitstream at the specified byte offset.
152 const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
153 return BitcodeBytes.data() + ByteNo;
154 }
155
156 /// Get a pointer into the bitstream at the specified bit offset.
157 ///
158 /// The bit offset must be on a byte boundary.
159 const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
160 assert(!(BitNo % 8) && "Expected bit on byte boundary")((!(BitNo % 8) && "Expected bit on byte boundary") ? static_cast
<void> (0) : __assert_fail ("!(BitNo % 8) && \"Expected bit on byte boundary\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Bitstream/BitstreamReader.h"
, 160, __PRETTY_FUNCTION__))
;
161 return getPointerToByte(BitNo / 8, NumBytes);
162 }
163
164 Error fillCurWord() {
165 if (NextChar >= BitcodeBytes.size())
166 return createStringError(std::errc::io_error,
167 "Unexpected end of file reading %u of %u bytes",
168 NextChar, BitcodeBytes.size());
169
170 // Read the next word from the stream.
171 const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
172 unsigned BytesRead;
173 if (BitcodeBytes.size() >= NextChar + sizeof(word_t)) {
174 BytesRead = sizeof(word_t);
175 CurWord =
176 support::endian::read<word_t, support::little, support::unaligned>(
177 NextCharPtr);
178 } else {
179 // Short read.
180 BytesRead = BitcodeBytes.size() - NextChar;
181 CurWord = 0;
182 for (unsigned B = 0; B != BytesRead; ++B)
183 CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
184 }
185 NextChar += BytesRead;
186 BitsInCurWord = BytesRead * 8;
187 return Error::success();
188 }
189
190 Expected<word_t> Read(unsigned NumBits) {
191 static const unsigned BitsInWord = MaxChunkSize;
192
193 assert(NumBits && NumBits <= BitsInWord &&((NumBits && NumBits <= BitsInWord && "Cannot return zero or more than BitsInWord bits!"
) ? static_cast<void> (0) : __assert_fail ("NumBits && NumBits <= BitsInWord && \"Cannot return zero or more than BitsInWord bits!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Bitstream/BitstreamReader.h"
, 194, __PRETTY_FUNCTION__))
19
Assuming 'NumBits' is not equal to 0
20
Assuming 'NumBits' is <= 'BitsInWord'
21
'?' condition is true
194 "Cannot return zero or more than BitsInWord bits!")((NumBits && NumBits <= BitsInWord && "Cannot return zero or more than BitsInWord bits!"
) ? static_cast<void> (0) : __assert_fail ("NumBits && NumBits <= BitsInWord && \"Cannot return zero or more than BitsInWord bits!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Bitstream/BitstreamReader.h"
, 194, __PRETTY_FUNCTION__))
;
195
196 static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f;
197
198 // If the field is fully contained by CurWord, return it quickly.
199 if (BitsInCurWord >= NumBits) {
22
Assuming 'NumBits' is > field 'BitsInCurWord'
23
Taking false branch
200 word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));
201
202 // Use a mask to avoid undefined behavior.
203 CurWord >>= (NumBits & Mask);
204
205 BitsInCurWord -= NumBits;
206 return R;
207 }
208
209 word_t R = BitsInCurWord
23.1
Field 'BitsInCurWord' is not equal to 0
23.1
Field 'BitsInCurWord' is not equal to 0
? CurWord : 0;
24
'?' condition is true
210 unsigned BitsLeft = NumBits - BitsInCurWord;
211
212 if (Error fillResult = fillCurWord())
25
Assuming the condition is false
26
Taking false branch
213 return std::move(fillResult);
214
215 // If we run out of data, abort.
216 if (BitsLeft > BitsInCurWord)
27
Assuming 'BitsLeft' is <= field 'BitsInCurWord'
28
Taking false branch
217 return createStringError(std::errc::io_error,
218 "Unexpected end of file reading %u of %u bits",
219 BitsInCurWord, BitsLeft);
220
221 word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
29
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::SimpleBitstreamCursor::word_t'
222
223 // Use a mask to avoid undefined behavior.
224 CurWord >>= (BitsLeft & Mask);
225
226 BitsInCurWord -= BitsLeft;
227
228 R |= R2 << (NumBits - BitsLeft);
229
230 return R;
231 }
232
233 Expected<uint32_t> ReadVBR(unsigned NumBits) {
234 Expected<unsigned> MaybeRead = Read(NumBits);
235 if (!MaybeRead)
236 return MaybeRead;
237 uint32_t Piece = MaybeRead.get();
238
239 if ((Piece & (1U << (NumBits-1))) == 0)
240 return Piece;
241
242 uint32_t Result = 0;
243 unsigned NextBit = 0;
244 while (true) {
245 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
246
247 if ((Piece & (1U << (NumBits-1))) == 0)
248 return Result;
249
250 NextBit += NumBits-1;
251 MaybeRead = Read(NumBits);
252 if (!MaybeRead)
253 return MaybeRead;
254 Piece = MaybeRead.get();
255 }
256 }
257
258 // Read a VBR that may have a value up to 64-bits in size. The chunk size of
259 // the VBR must still be <= 32 bits though.
260 Expected<uint64_t> ReadVBR64(unsigned NumBits) {
261 Expected<uint64_t> MaybeRead = Read(NumBits);
262 if (!MaybeRead)
263 return MaybeRead;
264 uint32_t Piece = MaybeRead.get();
265
266 if ((Piece & (1U << (NumBits-1))) == 0)
267 return uint64_t(Piece);
268
269 uint64_t Result = 0;
270 unsigned NextBit = 0;
271 while (true) {
272 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
273
274 if ((Piece & (1U << (NumBits-1))) == 0)
275 return Result;
276
277 NextBit += NumBits-1;
278 MaybeRead = Read(NumBits);
279 if (!MaybeRead)
280 return MaybeRead;
281 Piece = MaybeRead.get();
282 }
283 }
284
285 void SkipToFourByteBoundary() {
286 // If word_t is 64-bits and if we've read less than 32 bits, just dump
287 // the bits we have up to the next 32-bit boundary.
288 if (sizeof(word_t) > 4 &&
289 BitsInCurWord >= 32) {
290 CurWord >>= BitsInCurWord-32;
291 BitsInCurWord = 32;
292 return;
293 }
294
295 BitsInCurWord = 0;
296 }
297
298 /// Return the size of the stream in bytes.
299 size_t SizeInBytes() const { return BitcodeBytes.size(); }
300
301 /// Skip to the end of the file.
302 void skipToEnd() { NextChar = BitcodeBytes.size(); }
303};
304
305/// When advancing through a bitstream cursor, each advance can discover a few
306/// different kinds of entries:
307struct BitstreamEntry {
308 enum {
309 Error, // Malformed bitcode was found.
310 EndBlock, // We've reached the end of the current block, (or the end of the
311 // file, which is treated like a series of EndBlock records.
312 SubBlock, // This is the start of a new subblock of a specific ID.
313 Record // This is a record with a specific AbbrevID.
314 } Kind;
315
316 unsigned ID;
317
318 static BitstreamEntry getError() {
319 BitstreamEntry E; E.Kind = Error; return E;
320 }
321
322 static BitstreamEntry getEndBlock() {
323 BitstreamEntry E; E.Kind = EndBlock; return E;
324 }
325
326 static BitstreamEntry getSubBlock(unsigned ID) {
327 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
328 }
329
330 static BitstreamEntry getRecord(unsigned AbbrevID) {
331 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
332 }
333};
334
335/// This represents a position within a bitcode file, implemented on top of a
336/// SimpleBitstreamCursor.
337///
338/// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
339/// be passed by value.
340class BitstreamCursor : SimpleBitstreamCursor {
341 // This is the declared size of code values used for the current block, in
342 // bits.
343 unsigned CurCodeSize = 2;
344
345 /// Abbrevs installed at in this block.
346 std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
347
348 struct Block {
349 unsigned PrevCodeSize;
350 std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
351
352 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
353 };
354
355 /// This tracks the codesize of parent blocks.
356 SmallVector<Block, 8> BlockScope;
357
358 BitstreamBlockInfo *BlockInfo = nullptr;
359
360public:
361 static const size_t MaxChunkSize = sizeof(word_t) * 8;
362
363 BitstreamCursor() = default;
364 explicit BitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
365 : SimpleBitstreamCursor(BitcodeBytes) {}
366 explicit BitstreamCursor(StringRef BitcodeBytes)
367 : SimpleBitstreamCursor(BitcodeBytes) {}
368 explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
369 : SimpleBitstreamCursor(BitcodeBytes) {}
370
371 using SimpleBitstreamCursor::AtEndOfStream;
372 using SimpleBitstreamCursor::canSkipToPos;
373 using SimpleBitstreamCursor::fillCurWord;
374 using SimpleBitstreamCursor::getBitcodeBytes;
375 using SimpleBitstreamCursor::GetCurrentBitNo;
376 using SimpleBitstreamCursor::getCurrentByteNo;
377 using SimpleBitstreamCursor::getPointerToByte;
378 using SimpleBitstreamCursor::JumpToBit;
379 using SimpleBitstreamCursor::Read;
380 using SimpleBitstreamCursor::ReadVBR;
381 using SimpleBitstreamCursor::ReadVBR64;
382 using SimpleBitstreamCursor::SizeInBytes;
383 using SimpleBitstreamCursor::skipToEnd;
384
385 /// Return the number of bits used to encode an abbrev #.
386 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
387
388 /// Flags that modify the behavior of advance().
389 enum {
390 /// If this flag is used, the advance() method does not automatically pop
391 /// the block scope when the end of a block is reached.
392 AF_DontPopBlockAtEnd = 1,
393
394 /// If this flag is used, abbrev entries are returned just like normal
395 /// records.
396 AF_DontAutoprocessAbbrevs = 2
397 };
398
399 /// Advance the current bitstream, returning the next entry in the stream.
400 Expected<BitstreamEntry> advance(unsigned Flags = 0) {
401 while (true) {
15
Loop condition is true. Entering loop body
402 if (AtEndOfStream())
16
Taking false branch
403 return BitstreamEntry::getError();
404
405 Expected<unsigned> MaybeCode = ReadCode();
17
Calling 'BitstreamCursor::ReadCode'
406 if (!MaybeCode)
407 return MaybeCode.takeError();
408 unsigned Code = MaybeCode.get();
409
410 if (Code == bitc::END_BLOCK) {
411 // Pop the end of the block unless Flags tells us not to.
412 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
413 return BitstreamEntry::getError();
414 return BitstreamEntry::getEndBlock();
415 }
416
417 if (Code == bitc::ENTER_SUBBLOCK) {
418 if (Expected<unsigned> MaybeSubBlock = ReadSubBlockID())
419 return BitstreamEntry::getSubBlock(MaybeSubBlock.get());
420 else
421 return MaybeSubBlock.takeError();
422 }
423
424 if (Code == bitc::DEFINE_ABBREV &&
425 !(Flags & AF_DontAutoprocessAbbrevs)) {
426 // We read and accumulate abbrev's, the client can't do anything with
427 // them anyway.
428 if (Error Err = ReadAbbrevRecord())
429 return std::move(Err);
430 continue;
431 }
432
433 return BitstreamEntry::getRecord(Code);
434 }
435 }
436
437 /// This is a convenience function for clients that don't expect any
438 /// subblocks. This just skips over them automatically.
439 Expected<BitstreamEntry> advanceSkippingSubblocks(unsigned Flags = 0) {
440 while (true) {
13
Loop condition is true. Entering loop body
441 // If we found a normal entry, return it.
442 Expected<BitstreamEntry> MaybeEntry = advance(Flags);
14
Calling 'BitstreamCursor::advance'
443 if (!MaybeEntry)
444 return MaybeEntry;
445 BitstreamEntry Entry = MaybeEntry.get();
446
447 if (Entry.Kind != BitstreamEntry::SubBlock)
448 return Entry;
449
450 // If we found a sub-block, just skip over it and check the next entry.
451 if (Error Err = SkipBlock())
452 return std::move(Err);
453 }
454 }
455
456 Expected<unsigned> ReadCode() { return Read(CurCodeSize); }
18
Calling 'SimpleBitstreamCursor::Read'
457
458 // Block header:
459 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
460
461 /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
462 Expected<unsigned> ReadSubBlockID() { return ReadVBR(bitc::BlockIDWidth); }
463
464 /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
465 /// of this block.
466 Error SkipBlock() {
467 // Read and ignore the codelen value.
468 if (Expected<uint32_t> Res = ReadVBR(bitc::CodeLenWidth))
469 ; // Since we are skipping this block, we don't care what code widths are
470 // used inside of it.
471 else
472 return Res.takeError();
473
474 SkipToFourByteBoundary();
475 Expected<unsigned> MaybeNum = Read(bitc::BlockSizeWidth);
476 if (!MaybeNum)
477 return MaybeNum.takeError();
478 size_t NumFourBytes = MaybeNum.get();
479
480 // Check that the block wasn't partially defined, and that the offset isn't
481 // bogus.
482 size_t SkipTo = GetCurrentBitNo() + NumFourBytes * 4 * 8;
483 if (AtEndOfStream())
484 return createStringError(std::errc::illegal_byte_sequence,
485 "can't skip block: already at end of stream");
486 if (!canSkipToPos(SkipTo / 8))
487 return createStringError(std::errc::illegal_byte_sequence,
488 "can't skip to bit %zu from %" PRIu64"l" "u", SkipTo,
489 GetCurrentBitNo());
490
491 if (Error Res = JumpToBit(SkipTo))
492 return Res;
493
494 return Error::success();
495 }
496
497 /// Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
498 Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
499
500 bool ReadBlockEnd() {
501 if (BlockScope.empty()) return true;
502
503 // Block tail:
504 // [END_BLOCK, <align4bytes>]
505 SkipToFourByteBoundary();
506
507 popBlockScope();
508 return false;
509 }
510
511private:
512 void popBlockScope() {
513 CurCodeSize = BlockScope.back().PrevCodeSize;
514
515 CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
516 BlockScope.pop_back();
517 }
518
519 //===--------------------------------------------------------------------===//
520 // Record Processing
521 //===--------------------------------------------------------------------===//
522
523public:
524 /// Return the abbreviation for the specified AbbrevId.
525 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
526 unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
527 if (AbbrevNo >= CurAbbrevs.size())
528 report_fatal_error("Invalid abbrev number");
529 return CurAbbrevs[AbbrevNo].get();
530 }
531
532 /// Read the current record and discard it, returning the code for the record.
533 Expected<unsigned> skipRecord(unsigned AbbrevID);
534
535 Expected<unsigned> readRecord(unsigned AbbrevID,
536 SmallVectorImpl<uint64_t> &Vals,
537 StringRef *Blob = nullptr);
538
539 //===--------------------------------------------------------------------===//
540 // Abbrev Processing
541 //===--------------------------------------------------------------------===//
542 Error ReadAbbrevRecord();
543
544 /// Read and return a block info block from the bitstream. If an error was
545 /// encountered, return None.
546 ///
547 /// \param ReadBlockInfoNames Whether to read block/record name information in
548 /// the BlockInfo block. Only llvm-bcanalyzer uses this.
549 Expected<Optional<BitstreamBlockInfo>>
550 ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
551
552 /// Set the block info to be used by this BitstreamCursor to interpret
553 /// abbreviated records.
554 void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
555};
556
557} // end llvm namespace
558
559#endif // LLVM_BITSTREAM_BITSTREAMREADER_H