llvm.org GIT mirror llvm / 22d9c5c
BitStream reader: propagate errors The bitstream reader handles errors poorly. This has two effects: * Bugs in file handling (especially modules) manifest as an "unexpected end of file" crash * Users of clang as a library end up aborting because the code unconditionally calls `report_fatal_error` The bitstream reader should be more resilient and return Expected / Error as soon as an error is encountered, not way late like it does now. This patch starts doing so and adopting the error handling where I think it makes sense. There's plenty more to do: this patch propagates errors to be minimally useful, and follow-ups will propagate them further and improve diagnostics. https://bugs.llvm.org/show_bug.cgi?id=42311 <rdar://problem/33159405> Differential Revision: https://reviews.llvm.org/D63518 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@364464 91177308-0d34-0410-b5e6-96231b3b80d8 JF Bastien a month ago
9 changed file(s) with 960 addition(s) and 444 deletion(s). Raw diff Collapse all Expand all
9696 unsigned BitsInCurWord = 0;
9797
9898 public:
99 static const size_t MaxChunkSize = sizeof(word_t) * 8;
99 static const constexpr size_t MaxChunkSize = sizeof(word_t) * 8;
100100
101101 SimpleBitstreamCursor() = default;
102102 explicit SimpleBitstreamCursor(ArrayRef BitcodeBytes)
126126 ArrayRef getBitcodeBytes() const { return BitcodeBytes; }
127127
128128 /// Reset the stream to the specified bit number.
129 void JumpToBit(uint64_t BitNo) {
129 Error JumpToBit(uint64_t BitNo) {
130130 size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
131131 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
132132 assert(canSkipToPos(ByteNo) && "Invalid location");
136136 BitsInCurWord = 0;
137137
138138 // Skip over any bits that are already consumed.
139 if (WordBitNo)
140 Read(WordBitNo);
139 if (WordBitNo) {
140 if (Expected Res = Read(WordBitNo))
141 return Error::success();
142 else
143 return Res.takeError();
144 }
145
146 return Error::success();
141147 }
142148
143149 /// Get a pointer into the bitstream at the specified byte offset.
153159 return getPointerToByte(BitNo / 8, NumBytes);
154160 }
155161
156 void fillCurWord() {
162 Error fillCurWord() {
157163 if (NextChar >= BitcodeBytes.size())
158 report_fatal_error("Unexpected end of file");
164 return createStringError(std::errc::io_error,
165 "Unexpected end of file reading %u of %u bytes",
166 NextChar, BitcodeBytes.size());
159167
160168 // Read the next word from the stream.
161169 const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
174182 }
175183 NextChar += BytesRead;
176184 BitsInCurWord = BytesRead * 8;
177 }
178
179 word_t Read(unsigned NumBits) {
185 return Error::success();
186 }
187
188 Expected Read(unsigned NumBits) {
180189 static const unsigned BitsInWord = MaxChunkSize;
181190
182191 assert(NumBits && NumBits <= BitsInWord &&
198207 word_t R = BitsInCurWord ? CurWord : 0;
199208 unsigned BitsLeft = NumBits - BitsInCurWord;
200209
201 fillCurWord();
210 if (Error fillResult = fillCurWord())
211 return std::move(fillResult);
202212
203213 // If we run out of data, abort.
204214 if (BitsLeft > BitsInCurWord)
205 report_fatal_error("Unexpected end of file");
215 return createStringError(std::errc::io_error,
216 "Unexpected end of file reading %u of %u bits",
217 BitsInCurWord, BitsLeft);
206218
207219 word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
208220
216228 return R;
217229 }
218230
219 uint32_t ReadVBR(unsigned NumBits) {
220 uint32_t Piece = Read(NumBits);
231 Expected ReadVBR(unsigned NumBits) {
232 Expected MaybeRead = Read(NumBits);
233 if (!MaybeRead)
234 return MaybeRead;
235 uint32_t Piece = MaybeRead.get();
236
221237 if ((Piece & (1U << (NumBits-1))) == 0)
222238 return Piece;
223239
230246 return Result;
231247
232248 NextBit += NumBits-1;
233 Piece = Read(NumBits);
249 MaybeRead = Read(NumBits);
250 if (!MaybeRead)
251 return MaybeRead;
252 Piece = MaybeRead.get();
234253 }
235254 }
236255
237256 // Read a VBR that may have a value up to 64-bits in size. The chunk size of
238257 // the VBR must still be <= 32 bits though.
239 uint64_t ReadVBR64(unsigned NumBits) {
240 uint32_t Piece = Read(NumBits);
258 Expected ReadVBR64(unsigned NumBits) {
259 Expected MaybeRead = Read(NumBits);
260 if (!MaybeRead)
261 return MaybeRead;
262 uint32_t Piece = MaybeRead.get();
263
241264 if ((Piece & (1U << (NumBits-1))) == 0)
242265 return uint64_t(Piece);
243266
250273 return Result;
251274
252275 NextBit += NumBits-1;
253 Piece = Read(NumBits);
276 MaybeRead = Read(NumBits);
277 if (!MaybeRead)
278 return MaybeRead;
279 Piece = MaybeRead.get();
254280 }
255281 }
256282
364390 };
365391
366392 /// Advance the current bitstream, returning the next entry in the stream.
367 BitstreamEntry advance(unsigned Flags = 0) {
393 Expected advance(unsigned Flags = 0) {
368394 while (true) {
369395 if (AtEndOfStream())
370396 return BitstreamEntry::getError();
371397
372 unsigned Code = ReadCode();
398 Expected MaybeCode = ReadCode();
399 if (!MaybeCode)
400 return MaybeCode.takeError();
401 unsigned Code = MaybeCode.get();
402
373403 if (Code == bitc::END_BLOCK) {
374404 // Pop the end of the block unless Flags tells us not to.
375405 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
377407 return BitstreamEntry::getEndBlock();
378408 }
379409
380 if (Code == bitc::ENTER_SUBBLOCK)
381 return BitstreamEntry::getSubBlock(ReadSubBlockID());
410 if (Code == bitc::ENTER_SUBBLOCK) {
411 if (Expected MaybeSubBlock = ReadSubBlockID())
412 return BitstreamEntry::getSubBlock(MaybeSubBlock.get());
413 else
414 return MaybeSubBlock.takeError();
415 }
382416
383417 if (Code == bitc::DEFINE_ABBREV &&
384418 !(Flags & AF_DontAutoprocessAbbrevs)) {
385419 // We read and accumulate abbrev's, the client can't do anything with
386420 // them anyway.
387 ReadAbbrevRecord();
421 if (Error Err = ReadAbbrevRecord())
422 return std::move(Err);
388423 continue;
389424 }
390425
394429
395430 /// This is a convenience function for clients that don't expect any
396431 /// subblocks. This just skips over them automatically.
397 BitstreamEntry advanceSkippingSubblocks(unsigned Flags = 0) {
432 Expected advanceSkippingSubblocks(unsigned Flags = 0) {
398433 while (true) {
399434 // If we found a normal entry, return it.
400 BitstreamEntry Entry = advance(Flags);
435 Expected MaybeEntry = advance(Flags);
436 if (!MaybeEntry)
437 return MaybeEntry;
438 BitstreamEntry Entry = MaybeEntry.get();
439
401440 if (Entry.Kind != BitstreamEntry::SubBlock)
402441 return Entry;
403442
404443 // If we found a sub-block, just skip over it and check the next entry.
405 if (SkipBlock())
406 return BitstreamEntry::getError();
407 }
408 }
409
410 unsigned ReadCode() {
411 return Read(CurCodeSize);
412 }
444 if (Error Err = SkipBlock())
445 return std::move(Err);
446 }
447 }
448
449 Expected ReadCode() { return Read(CurCodeSize); }
413450
414451 // Block header:
415452 // [ENTER_SUBBLOCK, blockid, newcodelen, , blocklen]
416453
417454 /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
418 unsigned ReadSubBlockID() {
419 return ReadVBR(bitc::BlockIDWidth);
420 }
455 Expected ReadSubBlockID() { return ReadVBR(bitc::BlockIDWidth); }
421456
422457 /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
423 /// of this block. If the block record is malformed, return true.
424 bool SkipBlock() {
425 // Read and ignore the codelen value. Since we are skipping this block, we
426 // don't care what code widths are used inside of it.
427 ReadVBR(bitc::CodeLenWidth);
458 /// of this block.
459 Error SkipBlock() {
460 // Read and ignore the codelen value.
461 if (Expected Res = ReadVBR(bitc::CodeLenWidth))
462 ; // Since we are skipping this block, we don't care what code widths are
463 // used inside of it.
464 else
465 return Res.takeError();
466
428467 SkipToFourByteBoundary();
429 size_t NumFourBytes = Read(bitc::BlockSizeWidth);
468 Expected MaybeNum = Read(bitc::BlockSizeWidth);
469 if (!MaybeNum)
470 return MaybeNum.takeError();
471 size_t NumFourBytes = MaybeNum.get();
430472
431473 // Check that the block wasn't partially defined, and that the offset isn't
432474 // bogus.
433 size_t SkipTo = GetCurrentBitNo() + NumFourBytes*4*8;
434 if (AtEndOfStream() || !canSkipToPos(SkipTo/8))
435 return true;
436
437 JumpToBit(SkipTo);
438 return false;
439 }
440
441 /// Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true
442 /// if the block has an error.
443 bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
475 size_t SkipTo = GetCurrentBitNo() + NumFourBytes * 4 * 8;
476 if (AtEndOfStream())
477 return createStringError(std::errc::illegal_byte_sequence,
478 "can't skip block: already at end of stream");
479 if (!canSkipToPos(SkipTo / 8))
480 return createStringError(std::errc::illegal_byte_sequence,
481 "can't skip to bit %zu from %" PRIu64, SkipTo,
482 GetCurrentBitNo());
483
484 if (Error Res = JumpToBit(SkipTo))
485 return Res;
486
487 return Error::success();
488 }
489
490 /// Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
491 Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
444492
445493 bool ReadBlockEnd() {
446494 if (BlockScope.empty()) return true;
475523 }
476524
477525 /// Read the current record and discard it, returning the code for the record.
478 unsigned skipRecord(unsigned AbbrevID);
479
480 unsigned readRecord(unsigned AbbrevID, SmallVectorImpl &Vals,
481 StringRef *Blob = nullptr);
526 Expected skipRecord(unsigned AbbrevID);
527
528 Expected readRecord(unsigned AbbrevID,
529 SmallVectorImpl &Vals,
530 StringRef *Blob = nullptr);
482531
483532 //===--------------------------------------------------------------------===//
484533 // Abbrev Processing
485534 //===--------------------------------------------------------------------===//
486 void ReadAbbrevRecord();
535 Error ReadAbbrevRecord();
487536
488537 /// Read and return a block info block from the bitstream. If an error was
489538 /// encountered, return None.
490539 ///
491540 /// \param ReadBlockInfoNames Whether to read block/record name information in
492541 /// the BlockInfo block. Only llvm-bcanalyzer uses this.
493 Optional>
542 Expected>
494543 ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
495544
496545 /// Set the block info to be used by this BitstreamCursor to interpret
11591159
11601160 /// Create formatted StringError object.
11611161 template
1162 Error createStringError(std::error_code EC, char const *Fmt,
1163 const Ts &... Vals) {
1162 inline Error createStringError(std::error_code EC, char const *Fmt,
1163 const Ts &... Vals) {
11641164 std::string Buffer;
11651165 raw_string_ostream Stream(Buffer);
11661166 Stream << format(Fmt, Vals...);
11681168 }
11691169
11701170 Error createStringError(std::error_code EC, char const *Msg);
1171
1172 template
1173 inline Error createStringError(std::errc EC, char const *Fmt,
1174 const Ts &... Vals) {
1175 return createStringError(std::make_error_code(EC), Fmt, Vals...);
1176 }
11711177
11721178 /// This class wraps a filename and another Error.
11731179 ///
104104 Message, make_error_code(BitcodeError::CorruptedBitcode));
105105 }
106106
107 /// Helper to read the header common to all bitcode files.
108 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
109 // Sniff for the signature.
110 if (!Stream.canSkipToPos(4) ||
111 Stream.Read(8) != 'B' ||
112 Stream.Read(8) != 'C' ||
113 Stream.Read(4) != 0x0 ||
114 Stream.Read(4) != 0xC ||
115 Stream.Read(4) != 0xE ||
116 Stream.Read(4) != 0xD)
117 return false;
118 return true;
107 static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
108 if (!Stream.canSkipToPos(4))
109 return createStringError(std::errc::illegal_byte_sequence,
110 "file too small to contain bitcode header");
111 for (unsigned C : {'B', 'C'})
112 if (Expected Res = Stream.Read(8)) {
113 if (Res.get() != C)
114 return createStringError(std::errc::illegal_byte_sequence,
115 "file doesn't start with bitcode header");
116 } else
117 return Res.takeError();
118 for (unsigned C : {0x0, 0xC, 0xE, 0xD})
119 if (Expected Res = Stream.Read(4)) {
120 if (Res.get() != C)
121 return createStringError(std::errc::illegal_byte_sequence,
122 "file doesn't start with bitcode header");
123 } else
124 return Res.takeError();
125 return Error::success();
119126 }
120127
121128 static Expected initStream(MemoryBufferRef Buffer) {
132139 return error("Invalid bitcode wrapper header");
133140
134141 BitstreamCursor Stream(ArrayRef(BufPtr, BufEnd));
135 if (!hasValidBitcodeHeader(Stream))
136 return error("Invalid bitcode signature");
142 if (Error Err = hasInvalidBitcodeHeader(Stream))
143 return std::move(Err);
137144
138145 return std::move(Stream);
139146 }
163170 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
164171 /// "epoch" encoded in the bitcode, and return the producer name if any.
165172 static Expected readIdentificationBlock(BitstreamCursor &Stream) {
166 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
167 return error("Invalid record");
173 if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
174 return std::move(Err);
168175
169176 // Read all the records.
170177 SmallVector Record;
172179 std::string ProducerIdentification;
173180
174181 while (true) {
175 BitstreamEntry Entry = Stream.advance();
182 BitstreamEntry Entry;
183 if (Expected Res = Stream.advance())
184 Entry = Res.get();
185 else
186 return Res.takeError();
176187
177188 switch (Entry.Kind) {
178189 default:
187198
188199 // Read a record.
189200 Record.clear();
190 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
191 switch (BitCode) {
201 Expected MaybeBitCode = Stream.readRecord(Entry.ID, Record);
202 if (!MaybeBitCode)
203 return MaybeBitCode.takeError();
204 switch (unsigned BitCode = MaybeBitCode.get()) {
192205 default: // Default behavior: reject
193206 return error("Invalid value");
194207 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
213226 if (Stream.AtEndOfStream())
214227 return "";
215228
216 BitstreamEntry Entry = Stream.advance();
229 BitstreamEntry Entry;
230 if (Expected Res = Stream.advance())
231 Entry = std::move(Res.get());
232 else
233 return Res.takeError();
234
217235 switch (Entry.Kind) {
218236 case BitstreamEntry::EndBlock:
219237 case BitstreamEntry::Error:
224242 return readIdentificationBlock(Stream);
225243
226244 // Ignore other sub-blocks.
227 if (Stream.SkipBlock())
228 return error("Malformed block");
245 if (Error Err = Stream.SkipBlock())
246 return std::move(Err);
229247 continue;
230248 case BitstreamEntry::Record:
231 Stream.skipRecord(Entry.ID);
232 continue;
249 if (Expected Skipped = Stream.skipRecord(Entry.ID))
250 continue;
251 else
252 return Skipped.takeError();
233253 }
234254 }
235255 }
236256
237257 static Expected hasObjCCategoryInModule(BitstreamCursor &Stream) {
238 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
239 return error("Invalid record");
258 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
259 return std::move(Err);
240260
241261 SmallVector Record;
242262 // Read all the records for this module.
243263
244264 while (true) {
245 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
265 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
266 if (!MaybeEntry)
267 return MaybeEntry.takeError();
268 BitstreamEntry Entry = MaybeEntry.get();
246269
247270 switch (Entry.Kind) {
248271 case BitstreamEntry::SubBlock: // Handled for us already.
256279 }
257280
258281 // Read a record.
259 switch (Stream.readRecord(Entry.ID, Record)) {
282 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
283 if (!MaybeRecord)
284 return MaybeRecord.takeError();
285 switch (MaybeRecord.get()) {
260286 default:
261287 break; // Default behavior, ignore unknown content.
262288 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
279305 // We expect a number of well-defined blocks, though we don't necessarily
280306 // need to understand them all.
281307 while (true) {
282 BitstreamEntry Entry = Stream.advance();
308 BitstreamEntry Entry;
309 if (Expected Res = Stream.advance())
310 Entry = std::move(Res.get());
311 else
312 return Res.takeError();
283313
284314 switch (Entry.Kind) {
285315 case BitstreamEntry::Error:
292322 return hasObjCCategoryInModule(Stream);
293323
294324 // Ignore other sub-blocks.
295 if (Stream.SkipBlock())
296 return error("Malformed block");
325 if (Error Err = Stream.SkipBlock())
326 return std::move(Err);
297327 continue;
298328
299329 case BitstreamEntry::Record:
300 Stream.skipRecord(Entry.ID);
301 continue;
330 if (Expected Skipped = Stream.skipRecord(Entry.ID))
331 continue;
332 else
333 return Skipped.takeError();
302334 }
303335 }
304336 }
305337
306338 static Expected readModuleTriple(BitstreamCursor &Stream) {
307 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
308 return error("Invalid record");
339 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
340 return std::move(Err);
309341
310342 SmallVector Record;
311343
313345
314346 // Read all the records for this module.
315347 while (true) {
316 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
348 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
349 if (!MaybeEntry)
350 return MaybeEntry.takeError();
351 BitstreamEntry Entry = MaybeEntry.get();
317352
318353 switch (Entry.Kind) {
319354 case BitstreamEntry::SubBlock: // Handled for us already.
327362 }
328363
329364 // Read a record.
330 switch (Stream.readRecord(Entry.ID, Record)) {
365 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
366 if (!MaybeRecord)
367 return MaybeRecord.takeError();
368 switch (MaybeRecord.get()) {
331369 default: break; // Default behavior, ignore unknown content.
332370 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
333371 std::string S;
346384 // We expect a number of well-defined blocks, though we don't necessarily
347385 // need to understand them all.
348386 while (true) {
349 BitstreamEntry Entry = Stream.advance();
387 Expected MaybeEntry = Stream.advance();
388 if (!MaybeEntry)
389 return MaybeEntry.takeError();
390 BitstreamEntry Entry = MaybeEntry.get();
350391
351392 switch (Entry.Kind) {
352393 case BitstreamEntry::Error:
359400 return readModuleTriple(Stream);
360401
361402 // Ignore other sub-blocks.
362 if (Stream.SkipBlock())
363 return error("Malformed block");
403 if (Error Err = Stream.SkipBlock())
404 return std::move(Err);
364405 continue;
365406
366407 case BitstreamEntry::Record:
367 Stream.skipRecord(Entry.ID);
368 continue;
408 if (llvm::Expected Skipped = Stream.skipRecord(Entry.ID))
409 continue;
410 else
411 return Skipped.takeError();
369412 }
370413 }
371414 }
12521295 }
12531296
12541297 Error BitcodeReader::parseAttributeBlock() {
1255 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1256 return error("Invalid record");
1298 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1299 return Err;
12571300
12581301 if (!MAttributes.empty())
12591302 return error("Invalid multiple blocks");
12641307
12651308 // Read all the records.
12661309 while (true) {
1267 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1310 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
1311 if (!MaybeEntry)
1312 return MaybeEntry.takeError();
1313 BitstreamEntry Entry = MaybeEntry.get();
12681314
12691315 switch (Entry.Kind) {
12701316 case BitstreamEntry::SubBlock: // Handled for us already.
12791325
12801326 // Read a record.
12811327 Record.clear();
1282 switch (Stream.readRecord(Entry.ID, Record)) {
1328 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
1329 if (!MaybeRecord)
1330 return MaybeRecord.takeError();
1331 switch (MaybeRecord.get()) {
12831332 default: // Default behavior: ignore.
12841333 break;
12851334 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
14531502 }
14541503
14551504 Error BitcodeReader::parseAttributeGroupBlock() {
1456 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1457 return error("Invalid record");
1505 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1506 return Err;
14581507
14591508 if (!MAttributeGroups.empty())
14601509 return error("Invalid multiple blocks");
14631512
14641513 // Read all the records.
14651514 while (true) {
1466 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1515 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
1516 if (!MaybeEntry)
1517 return MaybeEntry.takeError();
1518 BitstreamEntry Entry = MaybeEntry.get();
14671519
14681520 switch (Entry.Kind) {
14691521 case BitstreamEntry::SubBlock: // Handled for us already.
14781530
14791531 // Read a record.
14801532 Record.clear();
1481 switch (Stream.readRecord(Entry.ID, Record)) {
1533 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
1534 if (!MaybeRecord)
1535 return MaybeRecord.takeError();
1536 switch (MaybeRecord.get()) {
14821537 default: // Default behavior: ignore.
14831538 break;
14841539 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
15541609 }
15551610
15561611 Error BitcodeReader::parseTypeTable() {
1557 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1558 return error("Invalid record");
1612 if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1613 return Err;
15591614
15601615 return parseTypeTableBody();
15611616 }
15711626
15721627 // Read all the records for this type table.
15731628 while (true) {
1574 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1629 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
1630 if (!MaybeEntry)
1631 return MaybeEntry.takeError();
1632 BitstreamEntry Entry = MaybeEntry.get();
15751633
15761634 switch (Entry.Kind) {
15771635 case BitstreamEntry::SubBlock: // Handled for us already.
15891647 // Read a record.
15901648 Record.clear();
15911649 Type *ResultTy = nullptr;
1592 switch (Stream.readRecord(Entry.ID, Record)) {
1650 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
1651 if (!MaybeRecord)
1652 return MaybeRecord.takeError();
1653 switch (MaybeRecord.get()) {
15931654 default:
15941655 return error("Invalid value");
15951656 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
17991860 }
18001861
18011862 Error BitcodeReader::parseOperandBundleTags() {
1802 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1803 return error("Invalid record");
1863 if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1864 return Err;
18041865
18051866 if (!BundleTags.empty())
18061867 return error("Invalid multiple blocks");
18081869 SmallVector Record;
18091870
18101871 while (true) {
1811 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1872 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
1873 if (!MaybeEntry)
1874 return MaybeEntry.takeError();
1875 BitstreamEntry Entry = MaybeEntry.get();
18121876
18131877 switch (Entry.Kind) {
18141878 case BitstreamEntry::SubBlock: // Handled for us already.
18231887
18241888 // Tags are implicitly mapped to integers by their order.
18251889
1826 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1890 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
1891 if (!MaybeRecord)
1892 return MaybeRecord.takeError();
1893 if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
18271894 return error("Invalid record");
18281895
18291896 // OPERAND_BUNDLE_TAG: [strchr x N]
18351902 }
18361903
18371904 Error BitcodeReader::parseSyncScopeNames() {
1838 if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1839 return error("Invalid record");
1905 if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1906 return Err;
18401907
18411908 if (!SSIDs.empty())
18421909 return error("Invalid multiple synchronization scope names blocks");
18431910
18441911 SmallVector Record;
18451912 while (true) {
1846 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1913 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
1914 if (!MaybeEntry)
1915 return MaybeEntry.takeError();
1916 BitstreamEntry Entry = MaybeEntry.get();
1917
18471918 switch (Entry.Kind) {
18481919 case BitstreamEntry::SubBlock: // Handled for us already.
18491920 case BitstreamEntry::Error:
18601931 // Synchronization scope names are implicitly mapped to synchronization
18611932 // scope IDs by their order.
18621933
1863 if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1934 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
1935 if (!MaybeRecord)
1936 return MaybeRecord.takeError();
1937 if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
18641938 return error("Invalid record");
18651939
18661940 SmallString<16> SSN;
19011975
19021976 /// Helper to note and return the current location, and jump to the given
19031977 /// offset.
1904 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1905 BitstreamCursor &Stream) {
1978 static Expected jumpToValueSymbolTable(uint64_t Offset,
1979 BitstreamCursor &Stream) {
19061980 // Save the current parsing location so we can jump back at the end
19071981 // of the VST read.
19081982 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1909 Stream.JumpToBit(Offset * 32);
1910 #ifndef NDEBUG
1911 // Do some checking if we are in debug mode.
1912 BitstreamEntry Entry = Stream.advance();
1913 assert(Entry.Kind == BitstreamEntry::SubBlock);
1914 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1915 #else
1916 // In NDEBUG mode ignore the output so we don't get an unused variable
1917 // warning.
1918 Stream.advance();
1919 #endif
1983 if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
1984 return std::move(JumpFailed);
1985 Expected MaybeEntry = Stream.advance();
1986 if (!MaybeEntry)
1987 return MaybeEntry.takeError();
1988 assert(MaybeEntry.get().Kind == BitstreamEntry::SubBlock);
1989 assert(MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID);
19201990 return CurrentBit;
19211991 }
19221992
19412011 unsigned FuncBitcodeOffsetDelta =
19422012 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
19432013
1944 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1945 return error("Invalid record");
2014 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2015 return Err;
19462016
19472017 SmallVector Record;
19482018 while (true) {
1949 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2019 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
2020 if (!MaybeEntry)
2021 return MaybeEntry.takeError();
2022 BitstreamEntry Entry = MaybeEntry.get();
19502023
19512024 switch (Entry.Kind) {
19522025 case BitstreamEntry::SubBlock:
19592032 }
19602033
19612034 Record.clear();
1962 switch (Stream.readRecord(Entry.ID, Record)) {
2035 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
2036 if (!MaybeRecord)
2037 return MaybeRecord.takeError();
2038 switch (MaybeRecord.get()) {
19632039 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
19642040 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
19652041 cast(ValueList[Record[0]]), Record);
19762052 // VST (where we want to jump to the VST offset) and the function-level
19772053 // VST (where we don't).
19782054 if (Offset > 0) {
1979 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
2055 Expected MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2056 if (!MaybeCurrentBit)
2057 return MaybeCurrentBit.takeError();
2058 CurrentBit = MaybeCurrentBit.get();
19802059 // If this module uses a string table, read this as a module-level VST.
19812060 if (UseStrtab) {
19822061 if (Error Err = parseGlobalValueSymbolTable())
19832062 return Err;
1984 Stream.JumpToBit(CurrentBit);
2063 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2064 return JumpFailed;
19852065 return Error::success();
19862066 }
19872067 // Otherwise, the VST will be in a similar format to a function-level VST,
20022082 unsigned FuncBitcodeOffsetDelta =
20032083 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
20042084
2005 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2006 return error("Invalid record");
2085 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2086 return Err;
20072087
20082088 SmallVector Record;
20092089
20132093 SmallString<128> ValueName;
20142094
20152095 while (true) {
2016 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2096 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
2097 if (!MaybeEntry)
2098 return MaybeEntry.takeError();
2099 BitstreamEntry Entry = MaybeEntry.get();
20172100
20182101 switch (Entry.Kind) {
20192102 case BitstreamEntry::SubBlock: // Handled for us already.
20212104 return error("Malformed block");
20222105 case BitstreamEntry::EndBlock:
20232106 if (Offset > 0)
2024 Stream.JumpToBit(CurrentBit);
2107 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2108 return JumpFailed;
20252109 return Error::success();
20262110 case BitstreamEntry::Record:
20272111 // The interesting case.
20302114
20312115 // Read a record.
20322116 Record.clear();
2033 switch (Stream.readRecord(Entry.ID, Record)) {
2117 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
2118 if (!MaybeRecord)
2119 return MaybeRecord.takeError();
2120 switch (MaybeRecord.get()) {
20342121 default: // Default behavior: unknown type.
20352122 break;
20362123 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
21752262 }
21762263
21772264 Error BitcodeReader::parseConstants() {
2178 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2179 return error("Invalid record");
2265 if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2266 return Err;
21802267
21812268 SmallVector Record;
21822269
21852272 unsigned NextCstNo = ValueList.size();
21862273
21872274 while (true) {
2188 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2275 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
2276 if (!MaybeEntry)
2277 return MaybeEntry.takeError();
2278 BitstreamEntry Entry = MaybeEntry.get();
21892279
21902280 switch (Entry.Kind) {
21912281 case BitstreamEntry::SubBlock: // Handled for us already.
22082298 Record.clear();
22092299 Type *VoidType = Type::getVoidTy(Context);
22102300 Value *V = nullptr;
2211 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2212 switch (BitCode) {
2301 Expected MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2302 if (!MaybeBitCode)
2303 return MaybeBitCode.takeError();
2304 switch (unsigned BitCode = MaybeBitCode.get()) {
22132305 default: // Default behavior: unknown constant
22142306 case bitc::CST_CODE_UNDEF: // UNDEF
22152307 V = UndefValue::get(CurTy);
26682760 }
26692761
26702762 Error BitcodeReader::parseUseLists() {
2671 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2672 return error("Invalid record");
2763 if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2764 return Err;
26732765
26742766 // Read all the records.
26752767 SmallVector Record;
26762768
26772769 while (true) {
2678 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2770 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
2771 if (!MaybeEntry)
2772 return MaybeEntry.takeError();
2773 BitstreamEntry Entry = MaybeEntry.get();
26792774
26802775 switch (Entry.Kind) {
26812776 case BitstreamEntry::SubBlock: // Handled for us already.
26912786 // Read a use list record.
26922787 Record.clear();
26932788 bool IsBB = false;
2694 switch (Stream.readRecord(Entry.ID, Record)) {
2789 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
2790 if (!MaybeRecord)
2791 return MaybeRecord.takeError();
2792 switch (MaybeRecord.get()) {
26952793 default: // Default behavior: unknown type.
26962794 break;
26972795 case bitc::USELIST_CODE_BB:
27402838 DeferredMetadataInfo.push_back(CurBit);
27412839
27422840 // Skip over the block for now.
2743 if (Stream.SkipBlock())
2744 return error("Invalid record");
2841 if (Error Err = Stream.SkipBlock())
2842 return Err;
27452843 return Error::success();
27462844 }
27472845
27482846 Error BitcodeReader::materializeMetadata() {
27492847 for (uint64_t BitPos : DeferredMetadataInfo) {
27502848 // Move the bit stream to the saved position.
2751 Stream.JumpToBit(BitPos);
2849 if (Error JumpFailed = Stream.JumpToBit(BitPos))
2850 return JumpFailed;
27522851 if (Error Err = MDLoader->parseModuleMetadata())
27532852 return Err;
27542853 }
27862885 DeferredFunctionInfo[Fn] = CurBit;
27872886
27882887 // Skip over the function block for now.
2789 if (Stream.SkipBlock())
2790 return error("Invalid record");
2888 if (Error Err = Stream.SkipBlock())
2889 return Err;
27912890 return Error::success();
27922891 }
27932892
28342933 /// or if we have an anonymous function being materialized, since anonymous
28352934 /// functions do not have a name and are therefore not in the VST.
28362935 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2837 Stream.JumpToBit(NextUnreadBit);
2936 if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
2937 return JumpFailed;
28382938
28392939 if (Stream.AtEndOfStream())
28402940 return error("Could not find function in stream");
28492949 SmallVector Record;
28502950
28512951 while (true) {
2852 BitstreamEntry Entry = Stream.advance();
2952 Expected MaybeEntry = Stream.advance();
2953 if (!MaybeEntry)
2954 return MaybeEntry.takeError();
2955 llvm::BitstreamEntry Entry = MaybeEntry.get();
2956
28532957 switch (Entry.Kind) {
28542958 default:
28552959 return error("Expect SubBlock");
28682972 }
28692973
28702974 bool BitcodeReaderBase::readBlockInfo() {
2871 Optional NewBlockInfo = Stream.ReadBlockInfoBlock();
2975 Expected> MaybeNewBlockInfo =
2976 Stream.ReadBlockInfoBlock();
2977 if (!MaybeNewBlockInfo)
2978 return true; // FIXME Handle the error.
2979 Optional NewBlockInfo =
2980 std::move(MaybeNewBlockInfo.get());
28722981 if (!NewBlockInfo)
28732982 return true;
28742983 BlockInfo = std::move(*NewBlockInfo);
32043313
32053314 Error BitcodeReader::parseModule(uint64_t ResumeBit,
32063315 bool ShouldLazyLoadMetadata) {
3207 if (ResumeBit)
3208 Stream.JumpToBit(ResumeBit);
3209 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3210 return error("Invalid record");
3316 if (ResumeBit) {
3317 if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
3318 return JumpFailed;
3319 } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3320 return Err;
32113321
32123322 SmallVector Record;
32133323
32143324 // Read all the records for this module.
32153325 while (true) {
3216 BitstreamEntry Entry = Stream.advance();
3326 Expected MaybeEntry = Stream.advance();
3327 if (!MaybeEntry)
3328 return MaybeEntry.takeError();
3329 llvm::BitstreamEntry Entry = MaybeEntry.get();
32173330
32183331 switch (Entry.Kind) {
32193332 case BitstreamEntry::Error:
32243337 case BitstreamEntry::SubBlock:
32253338 switch (Entry.ID) {
32263339 default: // Skip unknown content.
3227 if (Stream.SkipBlock())
3228 return error("Invalid record");
3340 if (Error Err = Stream.SkipBlock())
3341 return Err;
32293342 break;
32303343 case bitc::BLOCKINFO_BLOCK_ID:
32313344 if (readBlockInfo())
32583371 // We must have had a VST forward declaration record, which caused
32593372 // the parser to jump to and parse the VST earlier.
32603373 assert(VSTOffset > 0);
3261 if (Stream.SkipBlock())
3262 return error("Invalid record");
3374 if (Error Err = Stream.SkipBlock())
3375 return Err;
32633376 }
32643377 break;
32653378 case bitc::CONSTANTS_BLOCK_ID:
33113424 // materializing functions. The ResumeBit points to the
33123425 // start of the last function block recorded in the
33133426 // DeferredFunctionInfo map. Skip it.
3314 if (Stream.SkipBlock())
3315 return error("Invalid record");
3427 if (Error Err = Stream.SkipBlock())
3428 return Err;
33163429 continue;
33173430 }
33183431 }
33563469 }
33573470
33583471 // Read a record.
3359 auto BitCode = Stream.readRecord(Entry.ID, Record);
3360 switch (BitCode) {
3472 Expected MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3473 if (!MaybeBitCode)
3474 return MaybeBitCode.takeError();
3475 switch (unsigned BitCode = MaybeBitCode.get()) {
33613476 default: break; // Default behavior, ignore unknown content.
33623477 case bitc::MODULE_CODE_VERSION: {
33633478 Expected VersionOrErr = parseVersionRecord(Record);
34843599
34853600 /// Lazily parse the specified function body block.
34863601 Error BitcodeReader::parseFunctionBody(Function *F) {
3487 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3488 return error("Invalid record");
3602 if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3603 return Err;
34893604
34903605 // Unexpected unresolved metadata when parsing function.
34913606 if (MDLoader->hasFwdRefs())
35193634 SmallVector Record;
35203635
35213636 while (true) {
3522 BitstreamEntry Entry = Stream.advance();
3637 Expected MaybeEntry = Stream.advance();
3638 if (!MaybeEntry)
3639 return MaybeEntry.takeError();
3640 llvm::BitstreamEntry Entry = MaybeEntry.get();
35233641
35243642 switch (Entry.Kind) {
35253643 case BitstreamEntry::Error:
35303648 case BitstreamEntry::SubBlock:
35313649 switch (Entry.ID) {
35323650 default: // Skip unknown content.
3533 if (Stream.SkipBlock())
3534 return error("Invalid record");
3651 if (Error Err = Stream.SkipBlock())
3652 return Err;
35353653 break;
35363654 case bitc::CONSTANTS_BLOCK_ID:
35373655 if (Error Err = parseConstants())
35673685 // Read a record.
35683686 Record.clear();
35693687 Instruction *I = nullptr;
3570 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3571 switch (BitCode) {
3688 Expected MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3689 if (!MaybeBitCode)
3690 return MaybeBitCode.takeError();
3691 switch (unsigned BitCode = MaybeBitCode.get()) {
35723692 default: // Default behavior: reject
35733693 return error("Invalid value");
35743694 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
49215041 return Err;
49225042
49235043 // Move the bit stream to the saved position of the deferred function body.
4924 Stream.JumpToBit(DFII->second);
4925
5044 if (Error JumpFailed = Stream.JumpToBit(DFII->second))
5045 return JumpFailed;
49265046 if (Error Err = parseFunctionBody(F))
49275047 return Err;
49285048 F->setIsMaterializable(false);
50855205 return Error::success();
50865206
50875207 assert(Offset > 0 && "Expected non-zero VST offset");
5088 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5089
5090 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5091 return error("Invalid record");
5208 Expected MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
5209 if (!MaybeCurrentBit)
5210 return MaybeCurrentBit.takeError();
5211 uint64_t CurrentBit = MaybeCurrentBit.get();
5212
5213 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5214 return Err;
50925215
50935216 SmallVector Record;
50945217
50965219 SmallString<128> ValueName;
50975220
50985221 while (true) {
5099 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5222 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
5223 if (!MaybeEntry)
5224 return MaybeEntry.takeError();
5225 BitstreamEntry Entry = MaybeEntry.get();
51005226
51015227 switch (Entry.Kind) {
51025228 case BitstreamEntry::SubBlock: // Handled for us already.
51045230 return error("Malformed block");
51055231 case BitstreamEntry::EndBlock:
51065232 // Done parsing VST, jump back to wherever we came from.
5107 Stream.JumpToBit(CurrentBit);
5233 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
5234 return JumpFailed;
51085235 return Error::success();
51095236 case BitstreamEntry::Record:
51105237 // The interesting case.
51135240
51145241 // Read a record.
51155242 Record.clear();
5116 switch (Stream.readRecord(Entry.ID, Record)) {
5243 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
5244 if (!MaybeRecord)
5245 return MaybeRecord.takeError();
5246 switch (MaybeRecord.get()) {
51175247 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
51185248 break;
51195249 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
51615291 // At the end of this routine the module Index is populated with a map
51625292 // from global value id to GlobalValueSummary objects.
51635293 Error ModuleSummaryIndexBitcodeReader::parseModule() {
5164 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5165 return error("Invalid record");
5294 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5295 return Err;
51665296
51675297 SmallVector Record;
51685298 DenseMap ValueIdToLinkageMap;
51705300
51715301 // Read the index for this module.
51725302 while (true) {
5173 BitstreamEntry Entry = Stream.advance();
5303 Expected MaybeEntry = Stream.advance();
5304 if (!MaybeEntry)
5305 return MaybeEntry.takeError();
5306 llvm::BitstreamEntry Entry = MaybeEntry.get();
51745307
51755308 switch (Entry.Kind) {
51765309 case BitstreamEntry::Error:
51815314 case BitstreamEntry::SubBlock:
51825315 switch (Entry.ID) {
51835316 default: // Skip unknown content.
5184 if (Stream.SkipBlock())
5185 return error("Invalid record");
5317 if (Error Err = Stream.SkipBlock())
5318 return Err;
51865319 break;
51875320 case bitc::BLOCKINFO_BLOCK_ID:
51885321 // Need to parse these to get abbrev ids (e.g. for VST)
51955328 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
51965329 !SeenGlobalValSummary) &&
51975330 "Expected early VST parse via VSTOffset record");
5198 if (Stream.SkipBlock())
5199 return error("Invalid record");
5331 if (Error Err = Stream.SkipBlock())
5332 return Err;
52005333 break;
52015334 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
52025335 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
52275360
52285361 case BitstreamEntry::Record: {
52295362 Record.clear();
5230 auto BitCode = Stream.readRecord(Entry.ID, Record);
5231 switch (BitCode) {
5363 Expected MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5364 if (!MaybeBitCode)
5365 return MaybeBitCode.takeError();
5366 switch (unsigned BitCode = MaybeBitCode.get()) {
52325367 default:
52335368 break; // Default behavior, ignore unknown content.
52345369 case bitc::MODULE_CODE_VERSION: {
53855520 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
53865521 // objects in the index.
53875522 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5388 if (Stream.EnterSubBlock(ID))
5389 return error("Invalid record");
5523 if (Error Err = Stream.EnterSubBlock(ID))
5524 return Err;
53905525 SmallVector Record;
53915526
53925527 // Parse version
53935528 {
5394 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5529 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
5530 if (!MaybeEntry)
5531 return MaybeEntry.takeError();
5532 BitstreamEntry Entry = MaybeEntry.get();
5533
53955534 if (Entry.Kind != BitstreamEntry::Record)
53965535 return error("Invalid Summary Block: record for version expected");
5397 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
5536 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
5537 if (!MaybeRecord)
5538 return MaybeRecord.takeError();
5539 if (MaybeRecord.get() != bitc::FS_VERSION)
53985540 return error("Invalid Summary Block: version expected");
53995541 }
54005542 const uint64_t Version = Record[0];
54195561 PendingTypeCheckedLoadConstVCalls;
54205562
54215563 while (true) {
5422 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5564 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
5565 if (!MaybeEntry)
5566 return MaybeEntry.takeError();
5567 BitstreamEntry Entry = MaybeEntry.get();
54235568
54245569 switch (Entry.Kind) {
54255570 case BitstreamEntry::SubBlock: // Handled for us already.
54405585 // in the combined index VST entries). The records also contain
54415586 // information used for ThinLTO renaming and importing.
54425587 Record.clear();
5443 auto BitCode = Stream.readRecord(Entry.ID, Record);
5444 switch (BitCode) {
5588 Expected MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5589 if (!MaybeBitCode)
5590 return MaybeBitCode.takeError();
5591 switch (unsigned BitCode = MaybeBitCode.get()) {
54455592 default: // Default behavior: ignore.
54465593 break;
54475594 case bitc::FS_FLAGS: { // [flags]
57645911 // Parse the module string table block into the Index.
57655912 // This populates the ModulePathStringTable map in the index.
57665913 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5767 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5768 return error("Invalid record");
5914 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5915 return Err;
57695916
57705917 SmallVector Record;
57715918
57735920 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
57745921
57755922 while (true) {
5776 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5923 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
5924 if (!MaybeEntry)
5925 return MaybeEntry.takeError();
5926 BitstreamEntry Entry = MaybeEntry.get();
57775927
57785928 switch (Entry.Kind) {
57795929 case BitstreamEntry::SubBlock: // Handled for us already.
57875937 }
57885938
57895939 Record.clear();
5790 switch (Stream.readRecord(Entry.ID, Record)) {
5940 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
5941 if (!MaybeRecord)
5942 return MaybeRecord.takeError();
5943 switch (MaybeRecord.get()) {
57915944 default: // Default behavior: ignore.
57925945 break;
57935946 case bitc::MST_CODE_ENTRY: {
58536006
58546007 static Expected readBlobInRecord(BitstreamCursor &Stream,
58556008 unsigned Block, unsigned RecordID) {
5856 if (Stream.EnterSubBlock(Block))
5857 return error("Invalid record");
6009 if (Error Err = Stream.EnterSubBlock(Block))
6010 return std::move(Err);
58586011
58596012 StringRef Strtab;
58606013 while (true) {
5861 BitstreamEntry Entry = Stream.advance();
6014 Expected MaybeEntry = Stream.advance();
6015 if (!MaybeEntry)
6016 return MaybeEntry.takeError();
6017 llvm::BitstreamEntry Entry = MaybeEntry.get();
6018
58626019 switch (Entry.Kind) {
58636020 case BitstreamEntry::EndBlock:
58646021 return Strtab;
58676024 return error("Malformed block");
58686025
58696026 case BitstreamEntry::SubBlock:
5870 if (Stream.SkipBlock())
5871 return error("Malformed block");
6027 if (Error Err = Stream.SkipBlock())
6028 return std::move(Err);
58726029 break;
58736030
58746031 case BitstreamEntry::Record:
58756032 StringRef Blob;
58766033 SmallVector Record;
5877 if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
6034 Expected MaybeRecord =
6035 Stream.readRecord(Entry.ID, Record, &Blob);
6036 if (!MaybeRecord)
6037 return MaybeRecord.takeError();
6038 if (MaybeRecord.get() == RecordID)
58786039 Strtab = Blob;
58796040 break;
58806041 }
59106071 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
59116072 return F;
59126073
5913 BitstreamEntry Entry = Stream.advance();
6074 Expected MaybeEntry = Stream.advance();
6075 if (!MaybeEntry)
6076 return MaybeEntry.takeError();
6077 llvm::BitstreamEntry Entry = MaybeEntry.get();
6078
59146079 switch (Entry.Kind) {
59156080 case BitstreamEntry::EndBlock:
59166081 case BitstreamEntry::Error:
59206085 uint64_t IdentificationBit = -1ull;
59216086 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
59226087 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5923 if (Stream.SkipBlock())
5924 return error("Malformed block");
5925
5926 Entry = Stream.advance();
6088 if (Error Err = Stream.SkipBlock())
6089 return std::move(Err);
6090
6091 {
6092 Expected MaybeEntry = Stream.advance();
6093 if (!MaybeEntry)
6094 return MaybeEntry.takeError();
6095 Entry = MaybeEntry.get();
6096 }
6097
59276098 if (Entry.Kind != BitstreamEntry::SubBlock ||
59286099 Entry.ID != bitc::MODULE_BLOCK_ID)
59296100 return error("Malformed block");
59316102
59326103 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
59336104 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5934 if (Stream.SkipBlock())
5935 return error("Malformed block");
6105 if (Error Err = Stream.SkipBlock())
6106 return std::move(Err);
59366107
59376108 F.Mods.push_back({Stream.getBitcodeBytes().slice(
59386109 BCBegin, Stream.getCurrentByteNo() - BCBegin),
59806151 continue;
59816152 }
59826153
5983 if (Stream.SkipBlock())
5984 return error("Malformed block");
6154 if (Error Err = Stream.SkipBlock())
6155 return std::move(Err);
59856156 continue;
59866157 }
59876158 case BitstreamEntry::Record:
5988 Stream.skipRecord(Entry.ID);
5989 continue;
6159 if (Expected StreamFailed = Stream.skipRecord(Entry.ID))
6160 continue;
6161 else
6162 return StreamFailed.takeError();
59906163 }
59916164 }
59926165 }
60066179
60076180 std::string ProducerIdentification;
60086181 if (IdentificationBit != -1ull) {
6009 Stream.JumpToBit(IdentificationBit);
6182 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
6183 return std::move(JumpFailed);
60106184 Expected ProducerIdentificationOrErr =
60116185 readIdentificationBlock(Stream);
60126186 if (!ProducerIdentificationOrErr)
60156189 ProducerIdentification = *ProducerIdentificationOrErr;
60166190 }
60176191
6018 Stream.JumpToBit(ModuleBit);
6192 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6193 return std::move(JumpFailed);
60196194 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
60206195 Context);
60216196
60536228 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
60546229 StringRef ModulePath, uint64_t ModuleId) {
60556230 BitstreamCursor Stream(Buffer);
6056 Stream.JumpToBit(ModuleBit);
6231 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6232 return JumpFailed;
60576233
60586234 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
60596235 ModulePath, ModuleId);
60636239 // Parse the specified bitcode buffer, returning the function info index.
60646240 Expected> BitcodeModule::getSummary() {
60656241 BitstreamCursor Stream(Buffer);
6066 Stream.JumpToBit(ModuleBit);
6242 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6243 return std::move(JumpFailed);
60676244
60686245 auto Index = llvm::make_unique(/*HaveGVs=*/false);
60696246 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
60776254
60786255 static Expected getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
60796256 unsigned ID) {
6080 if (Stream.EnterSubBlock(ID))
6081 return error("Invalid record");
6257 if (Error Err = Stream.EnterSubBlock(ID))
6258 return std::move(Err);
60826259 SmallVector Record;
60836260
60846261 while (true) {
6085 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6262 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
6263 if (!MaybeEntry)
6264 return MaybeEntry.takeError();
6265 BitstreamEntry Entry = MaybeEntry.get();
60866266
60876267 switch (Entry.Kind) {
60886268 case BitstreamEntry::SubBlock: // Handled for us already.
60996279
61006280 // Look for the FS_FLAGS record.
61016281 Record.clear();
6102 auto BitCode = Stream.readRecord(Entry.ID, Record);
6103 switch (BitCode) {
6282 Expected MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6283 if (!MaybeBitCode)
6284 return MaybeBitCode.takeError();
6285 switch (MaybeBitCode.get()) {
61046286 default: // Default behavior: ignore.
61056287 break;
61066288 case bitc::FS_FLAGS: { // [flags]
61186300 // Check if the given bitcode buffer contains a global value summary block.
61196301 Expected BitcodeModule::getLTOInfo() {
61206302 BitstreamCursor Stream(Buffer);
6121 Stream.JumpToBit(ModuleBit);
6122
6123 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6124 return error("Invalid record");
6303 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6304 return std::move(JumpFailed);
6305
6306 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6307 return std::move(Err);
61256308
61266309 while (true) {
6127 BitstreamEntry Entry = Stream.advance();
6310 Expected MaybeEntry = Stream.advance();
6311 if (!MaybeEntry)
6312 return MaybeEntry.takeError();
6313 llvm::BitstreamEntry Entry = MaybeEntry.get();
61286314
61296315 switch (Entry.Kind) {
61306316 case BitstreamEntry::Error:
61536339 }
61546340
61556341 // Ignore other sub-blocks.
6156 if (Stream.SkipBlock())
6157 return error("Malformed block");
6342 if (Error Err = Stream.SkipBlock())
6343 return std::move(Err);
61586344 continue;
61596345
61606346 case BitstreamEntry::Record:
6161 Stream.skipRecord(Entry.ID);
6162 continue;
6347 if (Expected StreamFailed = Stream.skipRecord(Entry.ID))
6348 continue;
6349 else
6350 return StreamFailed.takeError();
61636351 }
61646352 }
61656353 }
1616 // BitstreamCursor implementation
1717 //===----------------------------------------------------------------------===//
1818
19 /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
20 /// the block, and return true if the block has an error.
21 bool BitstreamCursor::EnterSubBlock(unsigned BlockID, unsigned *NumWordsP) {
19 /// Having read the ENTER_SUBBLOCK abbrevid, enter the block.
20 Error BitstreamCursor::EnterSubBlock(unsigned BlockID, unsigned *NumWordsP) {
2221 // Save the current block's state on BlockScope.
2322 BlockScope.push_back(Block(CurCodeSize));
2423 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
3332 }
3433
3534 // Get the codesize of this block.
36 CurCodeSize = ReadVBR(bitc::CodeLenWidth);
37 // We can't read more than MaxChunkSize at a time
35 Expected MaybeVBR = ReadVBR(bitc::CodeLenWidth);
36 if (!MaybeVBR)
37 return MaybeVBR.takeError();
38 CurCodeSize = MaybeVBR.get();
39
3840 if (CurCodeSize > MaxChunkSize)
39 return true;
41 return llvm::createStringError(
42 std::errc::illegal_byte_sequence,
43 "can't read more than %zu at a time, trying to read %u", +MaxChunkSize,
44 CurCodeSize);
4045
4146 SkipToFourByteBoundary();
42 unsigned NumWords = Read(bitc::BlockSizeWidth);
43 if (NumWordsP) *NumWordsP = NumWords;
44
45 // Validate that this block is sane.
46 return CurCodeSize == 0 || AtEndOfStream();
47 }
48
49 static uint64_t readAbbreviatedField(BitstreamCursor &Cursor,
50 const BitCodeAbbrevOp &Op) {
47 Expected MaybeNum = Read(bitc::BlockSizeWidth);
48 if (!MaybeNum)
49 return MaybeNum.takeError();
50 word_t NumWords = MaybeNum.get();
51 if (NumWordsP)
52 *NumWordsP = NumWords;
53
54 if (CurCodeSize == 0)
55 return llvm::createStringError(
56 std::errc::illegal_byte_sequence,
57 "can't enter sub-block: current code size is 0");
58 if (AtEndOfStream())
59 return llvm::createStringError(
60 std::errc::illegal_byte_sequence,
61 "can't enter sub block: already at end of stream");
62
63 return Error::success();
64 }
65
66 static Expected readAbbreviatedField(BitstreamCursor &Cursor,
67 const BitCodeAbbrevOp &Op) {
5168 assert(!Op.isLiteral() && "Not to be used with literals!");
5269
5370 // Decode the value as we are commanded.
6279 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
6380 return Cursor.ReadVBR64((unsigned)Op.getEncodingData());
6481 case BitCodeAbbrevOp::Char6:
65 return BitCodeAbbrevOp::DecodeChar6(Cursor.Read(6));
82 if (Expected Res = Cursor.Read(6))
83 return BitCodeAbbrevOp::DecodeChar6(Res.get());
84 else
85 return Res.takeError();
6686 }
6787 llvm_unreachable("invalid abbreviation encoding");
6888 }
6989
70 static void skipAbbreviatedField(BitstreamCursor &Cursor,
71 const BitCodeAbbrevOp &Op) {
90 static Error skipAbbreviatedField(BitstreamCursor &Cursor,
91 const BitCodeAbbrevOp &Op) {
7292 assert(!Op.isLiteral() && "Not to be used with literals!");
7393
7494 // Decode the value as we are commanded.
7898 llvm_unreachable("Should not reach here");
7999 case BitCodeAbbrevOp::Fixed:
80100 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
81 Cursor.Read((unsigned)Op.getEncodingData());
82 break;
101 if (Expected Res = Cursor.Read((unsigned)Op.getEncodingData()))
102 break;
103 else
104 return Res.takeError();
83105 case BitCodeAbbrevOp::VBR:
84106 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
85 Cursor.ReadVBR64((unsigned)Op.getEncodingData());
86 break;
107 if (Expected Res =
108 Cursor.ReadVBR64((unsigned)Op.getEncodingData()))
109 break;
110 else
111 return Res.takeError();
87112 case BitCodeAbbrevOp::Char6:
88 Cursor.Read(6);
89 break;
90 }
113 if (Expected Res = Cursor.Read(6))
114 break;
115 else
116 return Res.takeError();
117 }
118 return ErrorSuccess();
91119 }
92120
93121 /// skipRecord - Read the current record and discard it.
94 unsigned BitstreamCursor::skipRecord(unsigned AbbrevID) {
122 Expected BitstreamCursor::skipRecord(unsigned AbbrevID) {
95123 // Skip unabbreviated records by reading past their entries.
96124 if (AbbrevID == bitc::UNABBREV_RECORD) {
97 unsigned Code = ReadVBR(6);
98 unsigned NumElts = ReadVBR(6);
125 Expected MaybeCode = ReadVBR(6);
126 if (!MaybeCode)
127 return MaybeCode.takeError();
128 unsigned Code = MaybeCode.get();
129 Expected MaybeVBR = ReadVBR(6);
130 if (!MaybeVBR)
131 return MaybeVBR.get();
132 unsigned NumElts = MaybeVBR.get();
99133 for (unsigned i = 0; i != NumElts; ++i)
100 (void)ReadVBR64(6);
134 if (Expected Res = ReadVBR64(6))
135 ; // Skip!
136 else
137 return Res.takeError();
101138 return Code;
102139 }
103140
109146 else {
110147 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
111148 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
112 report_fatal_error("Abbreviation starts with an Array or a Blob");
113 Code = readAbbreviatedField(*this, CodeOp);
149 return llvm::createStringError(
150 std::errc::illegal_byte_sequence,
151 "Abbreviation starts with an Array or a Blob");
152 Expected MaybeCode = readAbbreviatedField(*this, CodeOp);
153 if (!MaybeCode)
154 return MaybeCode.takeError();
155 Code = MaybeCode.get();
114156 }
115157
116158 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i < e; ++i) {
120162
121163 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
122164 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
123 skipAbbreviatedField(*this, Op);
165 if (Error Err = skipAbbreviatedField(*this, Op))
166 return std::move(Err);
124167 continue;
125168 }
126169
127170 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
128171 // Array case. Read the number of elements as a vbr6.
129 unsigned NumElts = ReadVBR(6);
172 Expected MaybeNum = ReadVBR(6);
173 if (!MaybeNum)
174 return MaybeNum.takeError();
175 unsigned NumElts = MaybeNum.get();
130176
131177 // Get the element encoding.
132178 assert(i+2 == e && "array op not second to last?");
139185 report_fatal_error("Array element type can't be an Array or a Blob");
140186 case BitCodeAbbrevOp::Fixed:
141187 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize);
142 JumpToBit(GetCurrentBitNo() + NumElts * EltEnc.getEncodingData());
188 if (Error Err = JumpToBit(GetCurrentBitNo() +
189 NumElts * EltEnc.getEncodingData()))
190 return std::move(Err);
143191 break;
144192 case BitCodeAbbrevOp::VBR:
145193 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize);
146194 for (; NumElts; --NumElts)
147 ReadVBR64((unsigned)EltEnc.getEncodingData());
195 if (Expected Res =
196 ReadVBR64((unsigned)EltEnc.getEncodingData()))
197 ; // Skip!
198 else
199 return Res.takeError();
148200 break;
149201 case BitCodeAbbrevOp::Char6:
150 JumpToBit(GetCurrentBitNo() + NumElts * 6);
202 if (Error Err = JumpToBit(GetCurrentBitNo() + NumElts * 6))
203 return std::move(Err);
151204 break;
152205 }
153206 continue;
155208
156209 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
157210 // Blob case. Read the number of bytes as a vbr6.
158 unsigned NumElts = ReadVBR(6);
211 Expected MaybeNum = ReadVBR(6);
212 if (!MaybeNum)
213 return MaybeNum.takeError();
214 unsigned NumElts = MaybeNum.get();
159215 SkipToFourByteBoundary(); // 32-bit alignment
160216
161217 // Figure out where the end of this blob will be including tail padding.
169225 }
170226
171227 // Skip over the blob.
172 JumpToBit(NewEnd);
228 if (Error Err = JumpToBit(NewEnd))
229 return std::move(Err);
173230 }
174231 return Code;
175232 }
176233
177 unsigned BitstreamCursor::readRecord(unsigned AbbrevID,
178 SmallVectorImpl &Vals,
179 StringRef *Blob) {
234 Expected BitstreamCursor::readRecord(unsigned AbbrevID,
235 SmallVectorImpl &Vals,
236 StringRef *Blob) {
180237 if (AbbrevID == bitc::UNABBREV_RECORD) {
181 unsigned Code = ReadVBR(6);
182 unsigned NumElts = ReadVBR(6);
238 Expected MaybeCode = ReadVBR(6);
239 if (!MaybeCode)
240 return MaybeCode.takeError();
241 uint32_t Code = MaybeCode.get();
242 Expected MaybeNumElts = ReadVBR(6);
243 if (!MaybeNumElts)
244 return MaybeNumElts.takeError();
245 uint32_t NumElts = MaybeNumElts.get();
246
183247 for (unsigned i = 0; i != NumElts; ++i)
184 Vals.push_back(ReadVBR64(6));
248 if (Expected MaybeVal = ReadVBR64(6))
249 Vals.push_back(MaybeVal.get());
250 else
251 return MaybeVal.takeError();
185252 return Code;
186253 }
187254
197264 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
198265 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
199266 report_fatal_error("Abbreviation starts with an Array or a Blob");
200 Code = readAbbreviatedField(*this, CodeOp);
267 if (Expected MaybeCode = readAbbreviatedField(*this, CodeOp))
268 Code = MaybeCode.get();
269 else
270 return MaybeCode.takeError();
201271 }
202272
203273 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
209279
210280 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
211281 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
212 Vals.push_back(readAbbreviatedField(*this, Op));
282 if (Expected MaybeVal = readAbbreviatedField(*this, Op))
283 Vals.push_back(MaybeVal.get());
284 else
285 return MaybeVal.takeError();
213286 continue;
214287 }
215288
216289 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
217290 // Array case. Read the number of elements as a vbr6.
218 unsigned NumElts = ReadVBR(6);
291 Expected MaybeNumElts = ReadVBR(6);
292 if (!MaybeNumElts)
293 return MaybeNumElts.takeError();
294 uint32_t NumElts = MaybeNumElts.get();
219295
220296 // Get the element encoding.
221297 if (i + 2 != e)
231307 report_fatal_error("Array element type can't be an Array or a Blob");
232308 case BitCodeAbbrevOp::Fixed:
233309 for (; NumElts; --NumElts)
234 Vals.push_back(Read((unsigned)EltEnc.getEncodingData()));
310 if (Expected MaybeVal =
311 Read((unsigned)EltEnc.getEncodingData()))
312 Vals.push_back(MaybeVal.get());
313 else
314 return MaybeVal.takeError();
235315 break;
236316 case BitCodeAbbrevOp::VBR:
237317 for (; NumElts; --NumElts)
238 Vals.push_back(ReadVBR64((unsigned)EltEnc.getEncodingData()));
318 if (Expected MaybeVal =
319 ReadVBR64((unsigned)EltEnc.getEncodingData()))
320 Vals.push_back(MaybeVal.get());
321 else
322 return MaybeVal.takeError();
239323 break;
240324 case BitCodeAbbrevOp::Char6:
241325 for (; NumElts; --NumElts)
242 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
326 if (Expected MaybeVal = Read(6))
327 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(MaybeVal.get()));
328 else
329 return MaybeVal.takeError();
243330 }
244331 continue;
245332 }
246333
247334 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
248335 // Blob case. Read the number of bytes as a vbr6.
249 unsigned NumElts = ReadVBR(6);
336 Expected MaybeNumElts = ReadVBR(6);
337 if (!MaybeNumElts)
338 return MaybeNumElts.takeError();
339 uint32_t NumElts = MaybeNumElts.get();
250340 SkipToFourByteBoundary(); // 32-bit alignment
251341
252342 // Figure out where the end of this blob will be including tail padding.
264354 // Otherwise, inform the streamer that we need these bytes in memory. Skip
265355 // over tail padding first, in case jumping to NewEnd invalidates the Blob
266356 // pointer.
267 JumpToBit(NewEnd);
357 if (Error Err = JumpToBit(NewEnd))
358 return std::move(Err);
268359 const char *Ptr = (const char *)getPointerToBit(CurBitPos, NumElts);
269360
270361 // If we can return a reference to the data, do so to avoid copying it.
280371 return Code;
281372 }
282373
283 void BitstreamCursor::ReadAbbrevRecord() {
374 Error BitstreamCursor::ReadAbbrevRecord() {
284375 auto Abbv = std::make_shared();
285 unsigned NumOpInfo = ReadVBR(5);
376 Expected MaybeNumOpInfo = ReadVBR(5);
377 if (!MaybeNumOpInfo)
378 return MaybeNumOpInfo.takeError();
379 unsigned NumOpInfo = MaybeNumOpInfo.get();
286380 for (unsigned i = 0; i != NumOpInfo; ++i) {
287 bool IsLiteral = Read(1);
381 Expected MaybeIsLiteral = Read(1);
382 if (!MaybeIsLiteral)
383 return MaybeIsLiteral.takeError();
384 bool IsLiteral = MaybeIsLiteral.get();
288385 if (IsLiteral) {
289 Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
290 continue;
291 }
292
293 BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
386 Expected MaybeOp = ReadVBR64(8);
387 if (!MaybeOp)
388 return MaybeOp.takeError();
389 Abbv->Add(BitCodeAbbrevOp(MaybeOp.get()));
390 continue;
391 }
392
393 Expected MaybeEncoding = Read(3);
394 if (!MaybeEncoding)
395 return MaybeEncoding.takeError();
396 BitCodeAbbrevOp::Encoding E =
397 (BitCodeAbbrevOp::Encoding)MaybeEncoding.get();
294398 if (BitCodeAbbrevOp::hasEncodingData(E)) {
295 uint64_t Data = ReadVBR64(5);
399 Expected MaybeData = ReadVBR64(5);
400 if (!MaybeData)
401 return MaybeData.takeError();
402 uint64_t Data = MaybeData.get();
296403
297404 // As a special case, handle fixed(0) (i.e., a fixed field with zero bits)
298405 // and vbr(0) as a literal zero. This is decoded the same way, and avoids
316423 if (Abbv->getNumOperandInfos() == 0)
317424 report_fatal_error("Abbrev record with no operands");
318425 CurAbbrevs.push_back(std::move(Abbv));
319 }
320
321 Optional
426
427 return Error::success();
428 }
429
430 Expected>
322431 BitstreamCursor::ReadBlockInfoBlock(bool ReadBlockInfoNames) {
323 if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return None;
432 if (llvm::Error Err = EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID))
433 return std::move(Err);
324434
325435 BitstreamBlockInfo NewBlockInfo;
326436
329439
330440 // Read all the records for this module.
331441 while (true) {
332 BitstreamEntry Entry = advanceSkippingSubblocks(AF_DontAutoprocessAbbrevs);
442 Expected MaybeEntry =
443 advanceSkippingSubblocks(AF_DontAutoprocessAbbrevs);
444 if (!MaybeEntry)
445 return MaybeEntry.takeError();
446 BitstreamEntry Entry = MaybeEntry.get();
333447
334448 switch (Entry.Kind) {
335449 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
345459 // Read abbrev records, associate them with CurBID.
346460 if (Entry.ID == bitc::DEFINE_ABBREV) {
347461 if (!CurBlockInfo) return None;
348 ReadAbbrevRecord();
462 if (Error Err = ReadAbbrevRecord())
463 return std::move(Err);
349464
350465 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
351466 // appropriate BlockInfo.
356471
357472 // Read a record.
358473 Record.clear();
359 switch (readRecord(Entry.ID, Record)) {
360 default: break; // Default behavior, ignore unknown content.
361 case bitc::BLOCKINFO_CODE_SETBID:
362 if (Record.size() < 1) return None;
363 CurBlockInfo = &NewBlockInfo.getOrCreateBlockInfo((unsigned)Record[0]);
364 break;
365 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
366 if (!CurBlockInfo) return None;
367 if (!ReadBlockInfoNames)
368 break; // Ignore name.
369 std::string Name;
370 for (unsigned i = 0, e = Record.size(); i != e; ++i)
371 Name += (char)Record[i];
372 CurBlockInfo->Name = Name;
373 break;
374 }
474 Expected MaybeBlockInfo = readRecord(Entry.ID, Record);
475 if (!MaybeBlockInfo)
476 return MaybeBlockInfo.takeError();
477 switch (MaybeBlockInfo.get()) {
478 default:
479 break; // Default behavior, ignore unknown content.
480 case bitc::BLOCKINFO_CODE_SETBID:
481 if (Record.size() < 1)
482 return None;
483 CurBlockInfo = &NewBlockInfo.getOrCreateBlockInfo((unsigned)Record[0]);
484 break;
485 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
486 if (!CurBlockInfo)
487 return None;
488 if (!ReadBlockInfoNames)
489 break; // Ignore name.
490 std::string Name;
491 for (unsigned i = 0, e = Record.size(); i != e; ++i)
492 Name += (char)Record[i];
493 CurBlockInfo->Name = Name;
494 break;
495 }
375496 case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
376497 if (!CurBlockInfo) return None;
377498 if (!ReadBlockInfoNames)
383504 Name));
384505 break;
385506 }
386 }
387 }
388 }
507 }
508 }
509 }
673673 SmallVector Record;
674674 // Get the abbrevs, and preload record positions to make them lazy-loadable.
675675 while (true) {
676 BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
676 Expected MaybeEntry = IndexCursor.advanceSkippingSubblocks(
677677 BitstreamCursor::AF_DontPopBlockAtEnd);
678 if (!MaybeEntry)
679 return MaybeEntry.takeError();
680 BitstreamEntry Entry = MaybeEntry.get();
681
678682 switch (Entry.Kind) {
679683 case BitstreamEntry::SubBlock: // Handled for us already.
680684 case BitstreamEntry::Error:
686690 // The interesting case.
687691 ++NumMDRecordLoaded;
688692 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
689 auto Code = IndexCursor.skipRecord(Entry.ID);
693 Expected MaybeCode = IndexCursor.skipRecord(Entry.ID);
694 if (!MaybeCode)
695 return MaybeCode.takeError();
696 unsigned Code = MaybeCode.get();
690697 switch (Code) {
691698 case bitc::METADATA_STRINGS: {
692699 // Rewind and parse the strings.
693 IndexCursor.JumpToBit(CurrentPos);
700 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
701 return std::move(Err);
694702 StringRef Blob;
695703 Record.clear();
696 IndexCursor.readRecord(Entry.ID, Record, &Blob);
704 if (Expected MaybeRecord =
705 IndexCursor.readRecord(Entry.ID, Record, &Blob))
706 ;
707 else
708 return MaybeRecord.takeError();
697709 unsigned NumStrings = Record[0];
698710 MDStringRef.reserve(NumStrings);
699711 auto IndexNextMDString = [&](StringRef Str) {
706718 case bitc::METADATA_INDEX_OFFSET: {
707719 // This is the offset to the index, when we see this we skip all the
708720 // records and load only an index to these.
709 IndexCursor.JumpToBit(CurrentPos);
721 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
722 return std::move(Err);
710723 Record.clear();
711 IndexCursor.readRecord(Entry.ID, Record);
724 if (Expected MaybeRecord =
725 IndexCursor.readRecord(Entry.ID, Record))
726 ;
727 else
728 return MaybeRecord.takeError();
712729 if (Record.size() != 2)
713730 return error("Invalid record");
714731 auto Offset = Record[0] + (Record[1] << 32);
715732 auto BeginPos = IndexCursor.GetCurrentBitNo();
716 IndexCursor.JumpToBit(BeginPos + Offset);
717 Entry = IndexCursor.advanceSkippingSubblocks(
718 BitstreamCursor::AF_DontPopBlockAtEnd);
733 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
734 return std::move(Err);
735 Expected MaybeEntry =
736 IndexCursor.advanceSkippingSubblocks(
737 BitstreamCursor::AF_DontPopBlockAtEnd);
738 if (!MaybeEntry)
739 return MaybeEntry.takeError();
740 Entry = MaybeEntry.get();
719741 assert(Entry.Kind == BitstreamEntry::Record &&
720742 "Corrupted bitcode: Expected `Record` when trying to find the "
721743 "Metadata index");
722744 Record.clear();
723 auto Code = IndexCursor.readRecord(Entry.ID, Record);
724 (void)Code;
725 assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
726 "`METADATA_INDEX` when trying "
727 "to find the Metadata index");
728
745 if (Expected MaybeCode =
746 IndexCursor.readRecord(Entry.ID, Record))
747 assert(MaybeCode.get() == bitc::METADATA_INDEX &&
748 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
749 "find the Metadata index");
750 else
751 return MaybeCode.takeError();
729752 // Delta unpack
730753 auto CurrentValue = BeginPos;
731754 GlobalMetadataBitPosIndex.reserve(Record.size());
741764 return error("Corrupted Metadata block");
742765 case bitc::METADATA_NAME: {
743766 // Named metadata need to be materialized now and aren't deferred.
744 IndexCursor.JumpToBit(CurrentPos);
767 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
768 return std::move(Err);
745769 Record.clear();
746 unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
747 assert(Code == bitc::METADATA_NAME);
770
771 unsigned Code;
772 if (Expected MaybeCode =
773 IndexCursor.readRecord(Entry.ID, Record)) {
774 Code = MaybeCode.get();
775 assert(Code == bitc::METADATA_NAME);
776 } else
777 return MaybeCode.takeError();
748778
749779 // Read name of the named metadata.
750780 SmallString<8> Name(Record.begin(), Record.end());
751 Code = IndexCursor.ReadCode();
781 if (Expected MaybeCode = IndexCursor.ReadCode())
782 Code = MaybeCode.get();
783 else
784 return MaybeCode.takeError();
752785
753786 // Named Metadata comes in two parts, we expect the name to be followed
754787 // by the node
755788 Record.clear();
756 unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
757 assert(NextBitCode == bitc::METADATA_NAMED_NODE);
758 (void)NextBitCode;
789 if (Expected MaybeNextBitCode =
790 IndexCursor.readRecord(Code, Record))
791 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
792 else
793 return MaybeNextBitCode.takeError();
759794
760795 // Read named metadata elements.
761796 unsigned Size = Record.size();
774809 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
775810 // FIXME: we need to do this early because we don't materialize global
776811 // value explicitly.
777 IndexCursor.JumpToBit(CurrentPos);
812 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
813 return std::move(Err);
778814 Record.clear();
779 IndexCursor.readRecord(Entry.ID, Record);
815 if (Expected MaybeRecord =
816 IndexCursor.readRecord(Entry.ID, Record))
817 ;
818 else
819 return MaybeRecord.takeError();
780820 if (Record.size() % 2 == 0)
781821 return error("Invalid record");
782822 unsigned ValueID = Record[0];
844884 // skip the whole block in case we lazy-load.
845885 auto EntryPos = Stream.GetCurrentBitNo();
846886
847 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
848 return error("Invalid record");
887 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
888 return Err;
849889
850890 SmallVector Record;
851891 PlaceholderQueue Placeholders;
870910 // Return at the beginning of the block, since it is easy to skip it
871911 // entirely from there.
872912 Stream.ReadBlockEnd(); // Pop the abbrev block context.
873 Stream.JumpToBit(EntryPos);
874 if (Stream.SkipBlock())
875 return error("Invalid record");
913 if (Error Err = IndexCursor.JumpToBit(EntryPos))
914 return Err;
915 if (Error Err = Stream.SkipBlock()) {
916 // FIXME this drops the error on the floor, which
917 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
918 consumeError(std::move(Err));
919 return Error::success();
920 }
876921 return Error::success();
877922 }
878923 // Couldn't load an index, fallback to loading all the block "old-style".
882927
883928 // Read all the records.
884929 while (true) {
885 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
930 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
931 if (!MaybeEntry)
932 return MaybeEntry.takeError();
933 BitstreamEntry Entry = MaybeEntry.get();
886934
887935 switch (Entry.Kind) {
888936 case BitstreamEntry::SubBlock: // Handled for us already.
901949 Record.clear();
902950 StringRef Blob;
903951 ++NumMDRecordLoaded;
904 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
905 if (Error Err =
906 parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
907 return Err;
952 if (Expected MaybeCode =
953 Stream.readRecord(Entry.ID, Record, &Blob)) {
954 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
955 Blob, NextMetadataNo))
956 return Err;
957 } else
958 return MaybeCode.takeError();
908959 }
909960 }
910961
929980 }
930981 SmallVector Record;
931982 StringRef Blob;
932 IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
933 auto Entry = IndexCursor.advanceSkippingSubblocks();
983 if (Error Err = IndexCursor.JumpToBit(
984 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
985 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
986 toString(std::move(Err)));
987 Expected MaybeEntry = IndexCursor.advanceSkippingSubblocks();
988 if (!MaybeEntry)
989 // FIXME this drops the error on the floor.
990 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
991 toString(MaybeEntry.takeError()));
992 BitstreamEntry Entry = MaybeEntry.get();
934993 ++NumMDRecordLoaded;
935 unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
936 if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
937 report_fatal_error("Can't lazyload MD");
994 if (Expected MaybeCode =
995 IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
996 if (Error Err =
997 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
998 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
999 toString(std::move(Err)));
1000 } else
1001 report_fatal_error("Can't lazyload MD: " + toString(MaybeCode.takeError()));
9381002 }
9391003
9401004 /// Ensure that all forward-references and placeholders are resolved.
10311095 // Read name of the named metadata.
10321096 SmallString<8> Name(Record.begin(), Record.end());
10331097 Record.clear();
1034 Code = Stream.ReadCode();
1098 Expected MaybeCode = Stream.ReadCode();
1099 if (!MaybeCode)
1100 return MaybeCode.takeError();
1101 Code = MaybeCode.get();
10351102
10361103 ++NumMDRecordLoaded;
1037 unsigned NextBitCode = Stream.readRecord(Code, Record);
1038 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1039 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1104 if (Expected MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1105 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1106 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1107 } else
1108 return MaybeNextBitCode.takeError();
10401109
10411110 // Read named metadata elements.
10421111 unsigned Size = Record.size();
18621931 if (R.AtEndOfStream())
18631932 return error("Invalid record: metadata strings bad length");
18641933
1865 unsigned Size = R.ReadVBR(6);
1934 Expected MaybeSize = R.ReadVBR(6);
1935 if (!MaybeSize)
1936 return MaybeSize.takeError();
1937 uint32_t Size = MaybeSize.get();
18661938 if (Strings.size() < Size)
18671939 return error("Invalid record: metadata strings truncated chars");
18681940
18911963 /// Parse metadata attachments.
18921964 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
18931965 Function &F, const SmallVectorImpl &InstructionList) {
1894 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1895 return error("Invalid record");
1966 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1967 return Err;
18961968
18971969 SmallVector Record;
18981970 PlaceholderQueue Placeholders;
18991971
19001972 while (true) {
1901 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1973 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
1974 if (!MaybeEntry)
1975 return MaybeEntry.takeError();
1976 BitstreamEntry Entry = MaybeEntry.get();
19021977
19031978 switch (Entry.Kind) {
19041979 case BitstreamEntry::SubBlock: // Handled for us already.
19151990 // Read a metadata attachment record.
19161991 Record.clear();
19171992 ++NumMDRecordLoaded;
1918 switch (Stream.readRecord(Entry.ID, Record)) {
1993 Expected MaybeRecord = Stream.readRecord(Entry.ID, Record);
1994 if (!MaybeRecord)
1995 return MaybeRecord.takeError();
1996 switch (MaybeRecord.get()) {
19191997 default: // Default behavior: ignore.
19201998 break;
19211999 case bitc::METADATA_ATTACHMENT: {
19892067
19902068 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
19912069 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1992 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1993 return error("Invalid record");
2070 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2071 return Err;
19942072
19952073 SmallVector Record;
19962074
19972075 // Read all the records.
19982076 while (true) {
1999 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2077 Expected MaybeEntry = Stream.advanceSkippingSubblocks();
2078 if (!MaybeEntry)
2079 return MaybeEntry.takeError();
2080 BitstreamEntry Entry = MaybeEntry.get();
20002081
20012082 switch (Entry.Kind) {
20022083 case BitstreamEntry::SubBlock: // Handled for us already.
20122093 // Read a record.
20132094 Record.clear();
20142095 ++NumMDRecordLoaded;
2015 unsigned Code = Stream.readRecord(Entry.ID, Record);
2016 switch (Code) {
2096 Expected MaybeCode = Stream.readRecord(Entry.ID, Record);
2097 if (!MaybeCode)
2098 return MaybeCode.takeError();
2099 switch (MaybeCode.get()) {
20172100 default: // Default behavior: ignore.
20182101 break;
20192102 case bitc::METADATA_KIND: {
2828 RUN: not llvm-dis -disable-output %p/Inputs/invalid-invoke-non-function-explicit-type.bc 2>&1 | \
2929 RUN: FileCheck --check-prefix=NON-FUNCTION-EXPLICIT-INVOKE %s
3030
31 INVALID-EMPTY: Invalid bitcode signature
31 INVALID-EMPTY: error: file too small to contain bitcode header
3232 INVALID-ENCODING: Invalid encoding
33 BAD-ABBREV: Malformed block
34 UNEXPECTED-EOF: Malformed block
35 BAD-ABBREV-NUMBER: Malformed block
33 BAD-ABBREV: error: can't skip to bit 25870861920 from 96
34 UNEXPECTED-EOF: error: can't skip to bit 25870861920 from 96
35 BAD-ABBREV-NUMBER: error: can't skip to bit 25870861920 from 96
3636 BAD-TYPE-TABLE-FORWARD-REF: Invalid TYPE table: Only named structs can be forward referenced
37 BAD-BITWIDTH: Malformed block
37 BAD-BITWIDTH: error: can't skip to bit 3616 from 96
3838 BAD-ALIGN: Invalid alignment value
3939 MISMATCHED-EXPLICIT-GEP: Explicit gep type does not match pointee type of pointer operand
4040 MISMATCHED-EXPLICIT-LOAD: Explicit load/store type does not match pointee type of pointer operand
153153 RUN: not llvm-dis -disable-output %p/Inputs/invalid-load-ptr-type.bc 2>&1 | \
154154 RUN: FileCheck --check-prefix=BAD-LOAD-PTR-TYPE %s
155155
156 BAD-LOAD-PTR-TYPE: Malformed block
156 BAD-LOAD-PTR-TYPE: error: can't skip to bit 3616 from 96
157157
158158 RUN: not llvm-dis -disable-output %p/Inputs/invalid-inserted-value-type-mismatch.bc 2>&1 | \
159159 RUN: FileCheck --check-prefix=INSERT-TYPE-MISMATCH %s
163163 RUN: not llvm-dis -disable-output %p/Inputs/invalid-code-len-width.bc 2>&1 | \
164164 RUN: FileCheck --check-prefix=INVALID-CODELENWIDTH %s
165165
166 INVALID-CODELENWIDTH: Malformed block
166 INVALID-CODELENWIDTH: error: can't skip to bit 3616 from 96
167167
168168 RUN: not llvm-dis -disable-output %p/Inputs/invalid-function-argument-type.bc 2>&1 | \
169169 RUN: FileCheck --check-prefix=INVALID-ARGUMENT-TYPE %s
77 ; CHECK-LIBS: llvm-lto: {{.*}}/Inputs/empty.bc: Could not read LTO input file: The file was not recognized as a valid object file
88
99 ; RUN: not llvm-lto --thinlto %S/Inputs/empty.bc 2>&1 | FileCheck %s --check-prefix=CHECK-THIN
10 ; CHECK-THIN: llvm-lto: error loading file '{{.*}}/Inputs/empty.bc': Invalid bitcode signature
10 ; CHECK-THIN: llvm-lto: error loading file '{{.*}}/Inputs/empty.bc': file too small to contain bitcode header
448448
449449 static std::map BlockIDStats;
450450
451
452
453 /// ReportError - All bitcode analysis errors go through this function, making this a
454 /// good place to breakpoint if debugging.
451 /// All bitcode analysis errors go through this function, making this a good
452 /// place to breakpoint if debugging.
455453 static bool ReportError(const Twine &Err) {
456454 WithColor::error() << Err << "\n";
457455 return true;
456 }
457
458 static bool ReportError(Error &&Err) {
459 return ReportError(toString(std::move(Err)));
458460 }
459461
460462 static bool decodeMetadataStringsBlob(StringRef Indent,
477479 if (R.AtEndOfStream())
478480 return ReportError("bad length");
479481
480 unsigned Size = R.ReadVBR(6);
482 Expected MaybeSize = R.ReadVBR(6);
483 if (!MaybeSize)
484 return ReportError(MaybeSize.takeError());
485 uint32_t Size = MaybeSize.get();
481486 if (Strings.size() < Size)
482487 return ReportError("truncated chars");
483488
517522 bool DumpRecords = Dump;
518523 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
519524 if (Dump) outs() << Indent << "\n";
525 Expected> MaybeNewBlockInfo =
526 Stream.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
527 if (!MaybeNewBlockInfo)
528 return ReportError(MaybeNewBlockInfo.takeError());
520529 Optional NewBlockInfo =
521 Stream.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
530 std::move(MaybeNewBlockInfo.get());
522531 if (!NewBlockInfo)
523532 return ReportError("Malformed BlockInfoBlock");
524533 BlockInfo = std::move(*NewBlockInfo);
525 Stream.JumpToBit(BlockBitStart);
534 if (Error Err = Stream.JumpToBit(BlockBitStart))
535 return ReportError(std::move(Err));
526536 // It's not really interesting to dump the contents of the blockinfo block.
527537 DumpRecords = false;
528538 }
529539
530540 unsigned NumWords = 0;
531 if (Stream.EnterSubBlock(BlockID, &NumWords))
532 return ReportError("Malformed block record");
541 if (Error Err = Stream.EnterSubBlock(BlockID, &NumWords))
542 return ReportError(std::move(Err));
533543
534544 // Keep it for later, when we see a MODULE_HASH record
535545 uint64_t BlockEntryPos = Stream.getCurrentByteNo();
561571
562572 uint64_t RecordStartBit = Stream.GetCurrentBitNo();
563573
564 BitstreamEntry Entry =
565 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
566
574 Expected MaybeEntry =
575 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
576 if (!MaybeEntry)
577 return ReportError(MaybeEntry.takeError());
578 BitstreamEntry Entry = MaybeEntry.get();
579
567580 switch (Entry.Kind) {
568581 case BitstreamEntry::Error:
569582 return ReportError("malformed bitcode file");
598611 }
599612
600613 if (Entry.ID == bitc::DEFINE_ABBREV) {
601 Stream.ReadAbbrevRecord();
614 if (Error Err = Stream.ReadAbbrevRecord())
615 return ReportError(std::move(Err));
602616 ++BlockStats.NumAbbrevs;
603617 continue;
604618 }
609623
610624 StringRef Blob;
611625 uint64_t CurrentRecordPos = Stream.GetCurrentBitNo();
612 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
626 Expected MaybeCode = Stream.readRecord(Entry.ID, Record, &Blob);
627 if (!MaybeCode)
628 return ReportError(MaybeCode.takeError());
629 unsigned Code = MaybeCode.get();
613630
614631 // Increment the # occurrences of this code.
615632 if (BlockStats.CodeFreq.size() <= Code)
741758 }
742759
743760 // Make sure that we can skip the current record.
744 Stream.JumpToBit(CurrentRecordPos);
745 Stream.skipRecord(Entry.ID);
761 if (Error Err = Stream.JumpToBit(CurrentRecordPos))
762 return ReportError(std::move(Err));
763 if (Expected Skipped = Stream.skipRecord(Entry.ID))
764 ; // Do nothing.
765 else
766 return ReportError(Skipped.takeError());
746767 }
747768 }
748769
754775 (double)Bits/8, (unsigned long)(Bits/32));
755776 }
756777
757 static CurStreamTypeType ReadSignature(BitstreamCursor &Stream) {
778 static Expected ReadSignature(BitstreamCursor &Stream) {
779 auto tryRead = [&Stream](char &Dest, size_t size) -> Error {
780 if (Expected MaybeWord = Stream.Read(size))
781 Dest = MaybeWord.get();
782 else
783 return MaybeWord.takeError();
784 return Error::success();
785 };
786
758787 char Signature[6];
759 Signature[0] = Stream.Read(8);
760 Signature[1] = Stream.Read(8);
788 if (Error Err = tryRead(Signature[0], 8))
789 return std::move(Err);
790 if (Error Err = tryRead(Signature[1], 8))
791 return std::move(Err);
761792
762793 // Autodetect the file contents, if it is one we know.
763794 if (Signature[0] == 'C' && Signature[1] == 'P') {
764 Signature[2] = Stream.Read(8);
765 Signature[3] = Stream.Read(8);
795 if (Error Err = tryRead(Signature[2], 8))
796 return std::move(Err);
797 if (Error Err = tryRead(Signature[3], 8))
798 return std::move(Err);
766799 if (Signature[2] == 'C' && Signature[3] == 'H')
767800 return ClangSerializedASTBitstream;
768801 } else if (Signature[0] == 'D' && Signature[1] == 'I') {
769 Signature[2] = Stream.Read(8);
770 Signature[3] = Stream.Read(8);
802 if (Error Err = tryRead(Signature[2], 8))
803 return std::move(Err);
804 if (Error Err = tryRead(Signature[3], 8))
805 return std::move(Err);
771806 if (Signature[2] == 'A' && Signature[3] == 'G')
772807 return ClangSerializedDiagnosticsBitstream;
773808 } else {
774 Signature[2] = Stream.Read(4);
775 Signature[3] = Stream.Read(4);
776 Signature[4] = Stream.Read(4);
777 Signature[5] = Stream.Read(4);
809 if (Error Err = tryRead(Signature[2], 4))
810 return std::move(Err);
811 if (Error Err = tryRead(Signature[3], 4))
812 return std::move(Err);
813 if (Error Err = tryRead(Signature[4], 4))
814 return std::move(Err);
815 if (Error Err = tryRead(Signature[5], 4))
816 return std::move(Err);
778817 if (Signature[0] == 'B' && Signature[1] == 'C' &&
779818 Signature[2] == 0x0 && Signature[3] == 0xC &&
780819 Signature[4] == 0xE && Signature[5] == 0xD)
826865 }
827866
828867 Stream = BitstreamCursor(ArrayRef(BufPtr, EndBufPtr));
829 CurStreamType = ReadSignature(Stream);
868 Expected MaybeSignature = ReadSignature(Stream);
869 if (!MaybeSignature)
870 return ReportError(MaybeSignature.takeError());
871 CurStreamType = std::move(MaybeSignature.get());
830872
831873 return false;
832874 }
852894 return true;
853895
854896 while (!BlockInfoCursor.AtEndOfStream()) {
855 unsigned Code = BlockInfoCursor.ReadCode();
856 if (Code != bitc::ENTER_SUBBLOCK)
897 Expected MaybeCode = BlockInfoCursor.ReadCode();
898 if (!MaybeCode)
899 return ReportError(MaybeCode.takeError());
900 if (MaybeCode.get() != bitc::ENTER_SUBBLOCK)
857901 return ReportError("Invalid record at top-level in block info file");
858902
859 unsigned BlockID = BlockInfoCursor.ReadSubBlockID();
860 if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
903 Expected MaybeBlockID = BlockInfoCursor.ReadSubBlockID();
904 if (!MaybeBlockID)
905 return ReportError(MaybeBlockID.takeError());
906 if (MaybeBlockID.get() == bitc::BLOCKINFO_BLOCK_ID) {
907 Expected> MaybeNewBlockInfo =
908 BlockInfoCursor.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
909 if (!MaybeNewBlockInfo)
910 return ReportError(MaybeNewBlockInfo.takeError());
861911 Optional NewBlockInfo =
862 BlockInfoCursor.ReadBlockInfoBlock(/*ReadBlockInfoNames=*/true);
912 std::move(MaybeNewBlockInfo.get());
863913 if (!NewBlockInfo)
864914 return ReportError("Malformed BlockInfoBlock in block info file");
865915 BlockInfo = std::move(*NewBlockInfo);
866916 break;
867917 }
868918
869 BlockInfoCursor.SkipBlock();
919 if (Error Err = BlockInfoCursor.SkipBlock())
920 return ReportError(std::move(Err));
870921 }
871922 }
872923
874925
875926 // Parse the top-level structure. We only allow blocks at the top-level.
876927 while (!Stream.AtEndOfStream()) {
877 unsigned Code = Stream.ReadCode();
878 if (Code != bitc::ENTER_SUBBLOCK)
928 Expected MaybeCode = Stream.ReadCode();
929 if (!MaybeCode)
930 return ReportError(MaybeCode.takeError());
931 if (MaybeCode.get() != bitc::ENTER_SUBBLOCK)
879932 return ReportError("Invalid record at top-level");
880933
881 unsigned BlockID = Stream.ReadSubBlockID();
882
883 if (ParseBlock(Stream, BlockInfo, BlockID, 0, CurStreamType))
934 Expected MaybeBlockID = Stream.ReadSubBlockID();
935 if (!MaybeBlockID)
936 return ReportError(MaybeBlockID.takeError());
937
938 if (ParseBlock(Stream, BlockInfo, MaybeBlockID.get(), 0, CurStreamType))
884939 return true;
885940 ++NumTopBlocks;
886941 }
2121 BitstreamCursor Cursor(Bytes);
2222
2323 EXPECT_FALSE(Cursor.AtEndOfStream());
24 (void)Cursor.Read(8);
24 Expected MaybeRead = Cursor.Read(8);
25 EXPECT_TRUE((bool)MaybeRead);
2526 EXPECT_FALSE(Cursor.AtEndOfStream());
26 (void)Cursor.Read(24);
27 MaybeRead = Cursor.Read(24);
28 EXPECT_TRUE((bool)MaybeRead);
2729 EXPECT_TRUE(Cursor.AtEndOfStream());
2830
29 Cursor.JumpToBit(0);
31 EXPECT_FALSE(Cursor.JumpToBit(0));
3032 EXPECT_FALSE(Cursor.AtEndOfStream());
3133
32 Cursor.JumpToBit(32);
34 EXPECT_FALSE(Cursor.JumpToBit(32));
3335 EXPECT_TRUE(Cursor.AtEndOfStream());
3436 }
3537
3941 };
4042 BitstreamCursor Cursor(Bytes);
4143
42 Cursor.JumpToBit(32);
44 EXPECT_FALSE(Cursor.JumpToBit(32));
4345 EXPECT_TRUE(Cursor.AtEndOfStream());
4446 }
4547
5557
5658 for (unsigned I = 0, E = 32; I != E; ++I) {
5759 EXPECT_EQ(I / 8, Cursor.getCurrentByteNo());
58 (void)Cursor.Read(1);
60 Expected MaybeRead = Cursor.Read(1);
61 EXPECT_TRUE((bool)MaybeRead);
5962 }
6063 EXPECT_EQ(4u, Cursor.getCurrentByteNo());
6164 }
115118
116119 // Header. Included in test so that we can run llvm-bcanalyzer to debug
117120 // when there are problems.
118 ASSERT_EQ(Magic, Stream.Read(32));
121 Expected MaybeRead = Stream.Read(32);
122 ASSERT_TRUE((bool)MaybeRead);
123 ASSERT_EQ(Magic, MaybeRead.get());
119124
120125 // Block.
121 BitstreamEntry Entry =
126 Expected MaybeEntry =
122127 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
128 ASSERT_TRUE((bool)MaybeEntry);
129 BitstreamEntry Entry = MaybeEntry.get();
123130 ASSERT_EQ(BitstreamEntry::SubBlock, Entry.Kind);
124131 ASSERT_EQ(BlockID, Entry.ID);
125132 ASSERT_FALSE(Stream.EnterSubBlock(BlockID));
126133
127134 // Abbreviation.
128 Entry = Stream.advance();
135 MaybeEntry = Stream.advance();
136 ASSERT_TRUE((bool)MaybeEntry);
137 Entry = MaybeEntry.get();
129138 ASSERT_EQ(BitstreamEntry::Record, Entry.Kind);
130139 ASSERT_EQ(AbbrevID, Entry.ID);
131140
132141 // Record.
133142 StringRef BlobOut;
134143 SmallVector Record;
135 ASSERT_EQ(RecordID, Stream.readRecord(Entry.ID, Record, &BlobOut));
144 Expected MaybeRecord =
145 Stream.readRecord(Entry.ID, Record, &BlobOut);
146 ASSERT_TRUE((bool)MaybeRecord);
147 ASSERT_EQ(RecordID, MaybeRecord.get());
136148 EXPECT_TRUE(Record.empty());
137149 EXPECT_EQ(BlobIn, BlobOut);
138150 }
142154 uint8_t Bytes[] = {8, 7, 6, 5, 4, 3, 2, 1};
143155 for (unsigned I = 1; I != 8; ++I) {
144156 SimpleBitstreamCursor Cursor(ArrayRef(Bytes, I));
145 EXPECT_EQ(8ull, Cursor.Read(8));
157 Expected MaybeRead = Cursor.Read(8);
158 ASSERT_TRUE((bool)MaybeRead);
159 EXPECT_EQ(8ull, MaybeRead.get());
146160 }
147161 }
148162