Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include/llvm/Bitstream/BitstreamReader.h
Warning:line 216, 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 'word_t'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name BitstreamReader.cpp -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 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Bitstream/Reader -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/Bitstream/Reader -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/Bitstream/Reader/BitstreamReader.cpp

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

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