llvm.org GIT mirror llvm / 9b252f0
Bitcode: Clean up error handling for certain bitcode query functions. The functions getBitcodeTargetTriple(), isBitcodeContainingObjCCategory(), getBitcodeProducerString() and hasGlobalValueSummary() now return errors via their return value rather than via the diagnostic handler. To make this work, re-implement these functions using non-member functions so that they can be used without the LLVMContext required by BitcodeReader. Differential Revision: https://reviews.llvm.org/D26532 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@286623 91177308-0d34-0410-b5e6-96231b3b80d8 Peter Collingbourne 2 years ago
9 changed file(s) with 321 addition(s) and 367 deletion(s). Raw diff Collapse all Expand all
1717 #include "llvm/IR/DiagnosticInfo.h"
1818 #include "llvm/IR/ModuleSummaryIndex.h"
1919 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/Error.h"
2021 #include "llvm/Support/ErrorOr.h"
2122 #include "llvm/Support/MemoryBuffer.h"
2223 #include
2425 namespace llvm {
2526 class LLVMContext;
2627 class Module;
28
29 // These functions are for converting Expected/Error values to
30 // ErrorOr/std::error_code for compatibility with legacy clients. FIXME:
31 // Remove these functions once no longer needed by the C and libLTO APIs.
32
33 std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err);
34 std::error_code
35 errorToErrorCodeAndEmitErrors(const DiagnosticHandlerFunction &DiagHandler,
36 Error Err);
37
38 template
39 ErrorOr expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected Val) {
40 if (!Val)
41 return errorToErrorCodeAndEmitErrors(Ctx, Val.takeError());
42 return std::move(*Val);
43 }
2744
2845 /// Read the header of the specified bitcode buffer and prepare for lazy
2946 /// deserialization of function bodies. If ShouldLazyLoadMetadata is true,
4360 /// Read the header of the specified bitcode buffer and extract just the
4461 /// triple information. If successful, this returns a string. On error, this
4562 /// returns "".
46 std::string getBitcodeTargetTriple(MemoryBufferRef Buffer,
47 LLVMContext &Context);
63 Expected getBitcodeTargetTriple(MemoryBufferRef Buffer);
4864
4965 /// Return true if \p Buffer contains a bitcode file with ObjC code (category
5066 /// or class) in it.
51 bool isBitcodeContainingObjCCategory(MemoryBufferRef Buffer,
52 LLVMContext &Context);
67 Expected isBitcodeContainingObjCCategory(MemoryBufferRef Buffer);
5368
5469 /// Read the header of the specified bitcode buffer and extract just the
5570 /// producer string information. If successful, this returns a string. On
5671 /// error, this returns "".
57 std::string getBitcodeProducerString(MemoryBufferRef Buffer,
58 LLVMContext &Context);
72 Expected getBitcodeProducerString(MemoryBufferRef Buffer);
5973
6074 /// Read the specified bitcode file, returning the module.
6175 ErrorOr> parseBitcodeFile(MemoryBufferRef Buffer,
6276 LLVMContext &Context);
6377
6478 /// Check if the given bitcode buffer contains a summary block.
65 bool
66 hasGlobalValueSummary(MemoryBufferRef Buffer,
67 const DiagnosticHandlerFunction &DiagnosticHandler);
79 Expected hasGlobalValueSummary(MemoryBufferRef Buffer);
6880
6981 /// Parse the specified bitcode buffer, returning the module summary index.
7082 ErrorOr>
7878 static ErrorOr
7979 findBitcodeInMemBuffer(MemoryBufferRef Object);
8080
81 /// \brief Looks for summary sections in the given memory buffer,
82 /// returns true if found, else false.
83 static bool hasGlobalValueSummaryInMemBuffer(
84 MemoryBufferRef Object,
85 const DiagnosticHandlerFunction &DiagnosticHandler);
86
8781 /// \brief Parse module summary index in the given memory buffer.
8882 /// Return new ModuleSummaryIndexObjectFile instance containing parsed module
8983 /// summary/index.
266266 return std::move(Stream);
267267 }
268268
269 /// Convert a string from a record into an std::string, return true on failure.
270 template
271 static bool convertToString(ArrayRef Record, unsigned Idx,
272 StrTy &Result) {
273 if (Idx > Record.size())
274 return true;
275
276 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
277 Result += (char)Record[i];
278 return false;
279 }
280
281 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
282 /// "epoch" encoded in the bitcode, and return the producer name if any.
283 Expected readIdentificationBlock(BitstreamCursor &Stream) {
284 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
285 return error("Invalid record");
286
287 // Read all the records.
288 SmallVector Record;
289
290 std::string ProducerIdentification;
291
292 while (true) {
293 BitstreamEntry Entry = Stream.advance();
294
295 switch (Entry.Kind) {
296 default:
297 case BitstreamEntry::Error:
298 return error("Malformed block");
299 case BitstreamEntry::EndBlock:
300 return ProducerIdentification;
301 case BitstreamEntry::Record:
302 // The interesting case.
303 break;
304 }
305
306 // Read a record.
307 Record.clear();
308 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
309 switch (BitCode) {
310 default: // Default behavior: reject
311 return error("Invalid value");
312 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
313 convertToString(Record, 0, ProducerIdentification);
314 break;
315 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
316 unsigned epoch = (unsigned)Record[0];
317 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
318 return error(
319 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
320 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
321 }
322 }
323 }
324 }
325 }
326
327 Expected readIdentificationCode(BitstreamCursor &Stream) {
328 // We expect a number of well-defined blocks, though we don't necessarily
329 // need to understand them all.
330 while (true) {
331 if (Stream.AtEndOfStream())
332 return "";
333
334 BitstreamEntry Entry = Stream.advance();
335 switch (Entry.Kind) {
336 case BitstreamEntry::EndBlock:
337 case BitstreamEntry::Error:
338 return error("Malformed block");
339
340 case BitstreamEntry::SubBlock:
341 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
342 return readIdentificationBlock(Stream);
343
344 // Ignore other sub-blocks.
345 if (Stream.SkipBlock())
346 return error("Malformed block");
347 continue;
348 case BitstreamEntry::Record:
349 Stream.skipRecord(Entry.ID);
350 continue;
351 }
352 }
353 }
354
355 Expected hasObjCCategoryInModule(BitstreamCursor &Stream) {
356 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
357 return error("Invalid record");
358
359 SmallVector Record;
360 // Read all the records for this module.
361
362 while (true) {
363 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
364
365 switch (Entry.Kind) {
366 case BitstreamEntry::SubBlock: // Handled for us already.
367 case BitstreamEntry::Error:
368 return error("Malformed block");
369 case BitstreamEntry::EndBlock:
370 return false;
371 case BitstreamEntry::Record:
372 // The interesting case.
373 break;
374 }
375
376 // Read a record.
377 switch (Stream.readRecord(Entry.ID, Record)) {
378 default:
379 break; // Default behavior, ignore unknown content.
380 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
381 std::string S;
382 if (convertToString(Record, 0, S))
383 return error("Invalid record");
384 // Check for the i386 and other (x86_64, ARM) conventions
385 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
386 S.find("__OBJC,__category") != std::string::npos)
387 return true;
388 break;
389 }
390 }
391 Record.clear();
392 }
393 llvm_unreachable("Exit infinite loop");
394 }
395
396 Expected hasObjCCategory(BitstreamCursor &Stream) {
397 // We expect a number of well-defined blocks, though we don't necessarily
398 // need to understand them all.
399 while (true) {
400 BitstreamEntry Entry = Stream.advance();
401
402 switch (Entry.Kind) {
403 case BitstreamEntry::Error:
404 return error("Malformed block");
405 case BitstreamEntry::EndBlock:
406 return false;
407
408 case BitstreamEntry::SubBlock:
409 if (Entry.ID == bitc::MODULE_BLOCK_ID)
410 return hasObjCCategoryInModule(Stream);
411
412 // Ignore other sub-blocks.
413 if (Stream.SkipBlock())
414 return error("Malformed block");
415 continue;
416
417 case BitstreamEntry::Record:
418 Stream.skipRecord(Entry.ID);
419 continue;
420 }
421 }
422 }
423
424 Expected readModuleTriple(BitstreamCursor &Stream) {
425 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
426 return error("Invalid record");
427
428 SmallVector Record;
429
430 std::string Triple;
431
432 // Read all the records for this module.
433 while (true) {
434 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
435
436 switch (Entry.Kind) {
437 case BitstreamEntry::SubBlock: // Handled for us already.
438 case BitstreamEntry::Error:
439 return error("Malformed block");
440 case BitstreamEntry::EndBlock:
441 return Triple;
442 case BitstreamEntry::Record:
443 // The interesting case.
444 break;
445 }
446
447 // Read a record.
448 switch (Stream.readRecord(Entry.ID, Record)) {
449 default: break; // Default behavior, ignore unknown content.
450 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
451 std::string S;
452 if (convertToString(Record, 0, S))
453 return error("Invalid record");
454 Triple = S;
455 break;
456 }
457 }
458 Record.clear();
459 }
460 llvm_unreachable("Exit infinite loop");
461 }
462
463 Expected readTriple(BitstreamCursor &Stream) {
464 // We expect a number of well-defined blocks, though we don't necessarily
465 // need to understand them all.
466 while (true) {
467 BitstreamEntry Entry = Stream.advance();
468
469 switch (Entry.Kind) {
470 case BitstreamEntry::Error:
471 return error("Malformed block");
472 case BitstreamEntry::EndBlock:
473 return "";
474
475 case BitstreamEntry::SubBlock:
476 if (Entry.ID == bitc::MODULE_BLOCK_ID)
477 return readModuleTriple(Stream);
478
479 // Ignore other sub-blocks.
480 if (Stream.SkipBlock())
481 return error("Malformed block");
482 continue;
483
484 case BitstreamEntry::Record:
485 Stream.skipRecord(Entry.ID);
486 continue;
487 }
488 }
489 }
490
269491 class BitcodeReaderBase {
270492 protected:
271493 BitcodeReaderBase(BitstreamCursor Stream) : Stream(std::move(Stream)) {
396618 /// \returns true if an error occurred.
397619 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false);
398620
399 /// \brief Cheap mechanism to just extract module triple
400 /// \returns true if an error occurred.
401 Expected parseTriple();
402
403 /// Cheap mechanism to just extract the identification block out of bitcode.
404 Expected parseIdentificationBlock();
405
406 /// Peak at the module content and return true if any ObjC category or class
407 /// is found.
408 Expected hasObjCCategory();
409
410621 static uint64_t decodeSignRotatedValue(uint64_t V);
411622
412623 /// Materialize any deferred Metadata block.
415626 void setStripDebugInfo() override;
416627
417628 private:
418 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
419 // ProducerIdentification data member, and do some basic enforcement on the
420 // "epoch" encoded in the bitcode.
421 Error parseBitcodeVersion();
422
423629 std::vector IdentifiedStructTypes;
424630 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
425631 StructType *createIdentifiedStructType(LLVMContext &Context);
545751 Error parseGlobalObjectAttachment(GlobalObject &GO,
546752 ArrayRef Record);
547753 Error parseMetadataAttachment(Function &F);
548 Expected parseModuleTriple();
549 Expected hasObjCCategoryInModule();
550754 Error parseUseLists();
551755 Error findFunctionInStream(
552756 Function *F,
621825 bool IsOldProfileFormat, bool HasProfile);
622826 };
623827
624 std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err) {
828 } // end anonymous namespace
829
830 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
831 Error Err) {
625832 if (Err) {
626833 std::error_code EC;
627834 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
633840 return std::error_code();
634841 }
635842
636 std::error_code
637 errorToErrorCodeAndEmitErrors(const DiagnosticHandlerFunction &DiagHandler,
638 Error Err) {
843 std::error_code llvm::errorToErrorCodeAndEmitErrors(
844 const DiagnosticHandlerFunction &DiagHandler, Error Err) {
639845 if (Err) {
640846 std::error_code EC;
641847 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
647853 return std::error_code();
648854 }
649855
650 template
651 ErrorOr expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected Val) {
652 if (!Val)
653 return errorToErrorCodeAndEmitErrors(Ctx, Val.takeError());
654 return std::move(*Val);
655 }
656
657 template
658 static ErrorOr
659 expectedToErrorOrAndEmitErrors(const DiagnosticHandlerFunction &DiagHandler,
660 Expected Val) {
661 if (!Val)
662 return errorToErrorCodeAndEmitErrors(DiagHandler, Val.takeError());
663 return std::move(*Val);
664 }
665
666 } // end anonymous namespace
667
668856 BitcodeReader::BitcodeReader(BitstreamCursor Stream, LLVMContext &Context)
669857 : BitcodeReaderBase(std::move(Stream)), Context(Context), ValueList(Context),
670858 MetadataList(Context) {}
705893 //===----------------------------------------------------------------------===//
706894 // Helper functions to implement forward reference resolution, etc.
707895 //===----------------------------------------------------------------------===//
708
709 /// Convert a string from a record into an std::string, return true on failure.
710 template
711 static bool convertToString(ArrayRef Record, unsigned Idx,
712 StrTy &Result) {
713 if (Idx > Record.size())
714 return true;
715
716 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
717 Result += (char)Record[i];
718 return false;
719 }
720896
721897 static bool hasImplicitComdat(size_t Val) {
722898 switch (Val) {
37123888 }
37133889 }
37143890
3715 Error BitcodeReader::parseBitcodeVersion() {
3716 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3717 return error("Invalid record");
3718
3719 // Read all the records.
3720 SmallVector Record;
3721
3722 while (true) {
3723 BitstreamEntry Entry = Stream.advance();
3724
3725 switch (Entry.Kind) {
3726 default:
3727 case BitstreamEntry::Error:
3728 return error("Malformed block");
3729 case BitstreamEntry::EndBlock:
3730 return Error::success();
3731 case BitstreamEntry::Record:
3732 // The interesting case.
3733 break;
3734 }
3735
3736 // Read a record.
3737 Record.clear();
3738 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3739 switch (BitCode) {
3740 default: // Default behavior: reject
3741 return error("Invalid value");
3742 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3743 // N]
3744 convertToString(Record, 0, ProducerIdentification);
3745 break;
3746 }
3747 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3748 unsigned epoch = (unsigned)Record[0];
3749 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3750 return error(
3751 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3752 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3753 }
3754 }
3755 }
3756 }
3757 }
3758
37593891 bool BitcodeReaderBase::readBlockInfo() {
37603892 Optional NewBlockInfo = Stream.ReadBlockInfoBlock();
37613893 if (!NewBlockInfo)
42584390 return error("Malformed block");
42594391
42604392 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4261 if (Error Err = parseBitcodeVersion())
4262 return Err;
4393 Expected ProducerIdentificationOrErr =
4394 readIdentificationBlock(Stream);
4395 if (!ProducerIdentificationOrErr)
4396 return ProducerIdentificationOrErr.takeError();
4397 ProducerIdentification = *ProducerIdentificationOrErr;
42634398 continue;
42644399 }
42654400
42684403
42694404 if (Stream.SkipBlock())
42704405 return error("Invalid record");
4271 }
4272 }
4273
4274 Expected BitcodeReader::parseModuleTriple() {
4275 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4276 return error("Invalid record");
4277
4278 SmallVector Record;
4279
4280 std::string Triple;
4281
4282 // Read all the records for this module.
4283 while (true) {
4284 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4285
4286 switch (Entry.Kind) {
4287 case BitstreamEntry::SubBlock: // Handled for us already.
4288 case BitstreamEntry::Error:
4289 return error("Malformed block");
4290 case BitstreamEntry::EndBlock:
4291 return Triple;
4292 case BitstreamEntry::Record:
4293 // The interesting case.
4294 break;
4295 }
4296
4297 // Read a record.
4298 switch (Stream.readRecord(Entry.ID, Record)) {
4299 default: break; // Default behavior, ignore unknown content.
4300 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
4301 std::string S;
4302 if (convertToString(Record, 0, S))
4303 return error("Invalid record");
4304 Triple = S;
4305 break;
4306 }
4307 }
4308 Record.clear();
4309 }
4310 llvm_unreachable("Exit infinite loop");
4311 }
4312
4313 Expected BitcodeReader::parseTriple() {
4314 // We expect a number of well-defined blocks, though we don't necessarily
4315 // need to understand them all.
4316 while (true) {
4317 BitstreamEntry Entry = Stream.advance();
4318
4319 switch (Entry.Kind) {
4320 case BitstreamEntry::Error:
4321 return error("Malformed block");
4322 case BitstreamEntry::EndBlock:
4323 return "";
4324
4325 case BitstreamEntry::SubBlock:
4326 if (Entry.ID == bitc::MODULE_BLOCK_ID)
4327 return parseModuleTriple();
4328
4329 // Ignore other sub-blocks.
4330 if (Stream.SkipBlock())
4331 return error("Malformed block");
4332 continue;
4333
4334 case BitstreamEntry::Record:
4335 Stream.skipRecord(Entry.ID);
4336 continue;
4337 }
4338 }
4339 }
4340
4341 Expected BitcodeReader::parseIdentificationBlock() {
4342 // We expect a number of well-defined blocks, though we don't necessarily
4343 // need to understand them all.
4344 while (true) {
4345 // This loop iterates at the top-level: since there is no enclosing block
4346 // we need to make sure we aren't at the end of the stream before calling
4347 // advance, otherwise we'll get an error.
4348 if (Stream.AtEndOfStream())
4349 return "";
4350
4351 BitstreamEntry Entry = Stream.advance();
4352 switch (Entry.Kind) {
4353 case BitstreamEntry::Error:
4354 return error("Malformed block");
4355 case BitstreamEntry::EndBlock:
4356 return "";
4357
4358 case BitstreamEntry::SubBlock:
4359 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4360 if (Error Err = parseBitcodeVersion())
4361 return std::move(Err);
4362 return ProducerIdentification;
4363 }
4364 // Ignore other sub-blocks.
4365 if (Stream.SkipBlock())
4366 return error("Malformed block");
4367 continue;
4368 case BitstreamEntry::Record:
4369 Stream.skipRecord(Entry.ID);
4370 continue;
4371 }
43724406 }
43734407 }
43744408
43854419 GO.addMetadata(K->second, *MD);
43864420 }
43874421 return Error::success();
4388 }
4389
4390 Expected BitcodeReader::hasObjCCategory() {
4391 // We expect a number of well-defined blocks, though we don't necessarily
4392 // need to understand them all.
4393 while (true) {
4394 BitstreamEntry Entry = Stream.advance();
4395
4396 switch (Entry.Kind) {
4397 case BitstreamEntry::Error:
4398 return error("Malformed block");
4399 case BitstreamEntry::EndBlock:
4400 return false;
4401
4402 case BitstreamEntry::SubBlock:
4403 if (Entry.ID == bitc::MODULE_BLOCK_ID)
4404 return hasObjCCategoryInModule();
4405
4406 // Ignore other sub-blocks.
4407 if (Stream.SkipBlock())
4408 return error("Malformed block");
4409 continue;
4410
4411 case BitstreamEntry::Record:
4412 Stream.skipRecord(Entry.ID);
4413 continue;
4414 }
4415 }
4416 }
4417
4418 Expected BitcodeReader::hasObjCCategoryInModule() {
4419 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4420 return error("Invalid record");
4421
4422 SmallVector Record;
4423 // Read all the records for this module.
4424
4425 while (true) {
4426 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4427
4428 switch (Entry.Kind) {
4429 case BitstreamEntry::SubBlock: // Handled for us already.
4430 case BitstreamEntry::Error:
4431 return error("Malformed block");
4432 case BitstreamEntry::EndBlock:
4433 return false;
4434 case BitstreamEntry::Record:
4435 // The interesting case.
4436 break;
4437 }
4438
4439 // Read a record.
4440 switch (Stream.readRecord(Entry.ID, Record)) {
4441 default:
4442 break; // Default behavior, ignore unknown content.
4443 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4444 std::string S;
4445 if (convertToString(Record, 0, S))
4446 return error("Invalid record");
4447 // Check for the i386 and other (x86_64, ARM) conventions
4448 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
4449 S.find("__OBJC,__category") != std::string::npos)
4450 return true;
4451 break;
4452 }
4453 }
4454 Record.clear();
4455 }
4456 llvm_unreachable("Exit infinite loop");
44574422 }
44584423
44594424 /// Parse metadata attachments.
66726637 // written. We must defer until the Module has been fully materialized.
66736638 }
66746639
6675 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6676 LLVMContext &Context) {
6677 ErrorOr StreamOrErr =
6678 expectedToErrorOrAndEmitErrors(Context, initStream(Buffer));
6640 Expected llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
6641 Expected StreamOrErr = initStream(Buffer);
66796642 if (!StreamOrErr)
6680 return "";
6681
6682 BitcodeReader R(std::move(*StreamOrErr), Context);
6683 ErrorOr Triple =
6684 expectedToErrorOrAndEmitErrors(Context, R.parseTriple());
6685 if (Triple.getError())
6686 return "";
6687 return Triple.get();
6688 }
6689
6690 bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer,
6691 LLVMContext &Context) {
6692 ErrorOr StreamOrErr =
6693 expectedToErrorOrAndEmitErrors(Context, initStream(Buffer));
6643 return StreamOrErr.takeError();
6644
6645 return readTriple(*StreamOrErr);
6646 }
6647
6648 Expected llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
6649 Expected StreamOrErr = initStream(Buffer);
66946650 if (!StreamOrErr)
6695 return false;
6696
6697 BitcodeReader R(std::move(*StreamOrErr), Context);
6698 ErrorOr hasObjCCategory =
6699 expectedToErrorOrAndEmitErrors(Context, R.hasObjCCategory());
6700 if (hasObjCCategory.getError())
6701 return false;
6702 return hasObjCCategory.get();
6703 }
6704
6705 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6706 LLVMContext &Context) {
6707 ErrorOr StreamOrErr =
6708 expectedToErrorOrAndEmitErrors(Context, initStream(Buffer));
6651 return StreamOrErr.takeError();
6652
6653 return hasObjCCategory(*StreamOrErr);
6654 }
6655
6656 Expected llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
6657 Expected StreamOrErr = initStream(Buffer);
67096658 if (!StreamOrErr)
6710 return "";
6711
6712 BitcodeReader R(std::move(*StreamOrErr), Context);
6713 ErrorOr ProducerString =
6714 expectedToErrorOrAndEmitErrors(Context, R.parseIdentificationBlock());
6715 if (ProducerString.getError())
6716 return "";
6717 return ProducerString.get();
6659 return StreamOrErr.takeError();
6660
6661 return readIdentificationCode(*StreamOrErr);
67186662 }
67196663
67206664 // Parse the specified bitcode buffer, returning the function info index.
67396683 }
67406684
67416685 // Check if the given bitcode buffer contains a global value summary block.
6742 bool llvm::hasGlobalValueSummary(
6743 MemoryBufferRef Buffer,
6744 const DiagnosticHandlerFunction &DiagnosticHandler) {
6745 ErrorOr StreamOrErr = expectedToErrorOrAndEmitErrors(
6746 DiagnosticHandler, initStream(Buffer));
6686 Expected llvm::hasGlobalValueSummary(MemoryBufferRef Buffer) {
6687 Expected StreamOrErr = initStream(Buffer);
67476688 if (!StreamOrErr)
6748 return false;
6689 return StreamOrErr.takeError();
67496690
67506691 ModuleSummaryIndexBitcodeReader R(std::move(*StreamOrErr), true);
6751 if (errorToErrorCodeAndEmitErrors(
6752 DiagnosticHandler,
6753 R.parseSummaryIndexInto(nullptr, Buffer.getBufferIdentifier())))
6754 return false;
6692
6693 if (Error Err =
6694 R.parseSummaryIndexInto(nullptr, Buffer.getBufferIdentifier()))
6695 return std::move(Err);
67556696
67566697 return R.foundGlobalValSummary();
67576698 }
327327 M.setTargetTriple(Conf.DefaultTriple);
328328
329329 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
330 bool HasThinLTOSummary = hasGlobalValueSummary(MBRef, Conf.DiagHandler);
331
332 if (HasThinLTOSummary)
330 Expected HasThinLTOSummary = hasGlobalValueSummary(MBRef);
331 if (!HasThinLTOSummary)
332 return HasThinLTOSummary.takeError();
333
334 if (*HasThinLTOSummary)
333335 return addThinLTO(std::move(Input), Res);
334336 else
335337 return addRegularLTO(std::move(Input), Res);
7575 bool LTOModule::isThinLTO() {
7676 // Right now the detection is only based on the summary presence. We may want
7777 // to add a dedicated flag at some point.
78 return hasGlobalValueSummary(IRFile->getMemoryBufferRef(),
79 [](const DiagnosticInfo &DI) {
80 DiagnosticPrinterRawOStream DP(errs());
81 DI.print(DP);
82 errs() << '\n';
83 return;
84 });
78 Expected Result = hasGlobalValueSummary(IRFile->getMemoryBufferRef());
79 if (!Result) {
80 logAllUnhandledErrors(Result.takeError(), errs(), "");
81 return false;
82 }
83 return *Result;
8584 }
8685
8786 bool LTOModule::isBitcodeForTarget(MemoryBuffer *Buffer,
9190 if (!BCOrErr)
9291 return false;
9392 LLVMContext Context;
94 std::string Triple = getBitcodeTargetTriple(*BCOrErr, Context);
95 return StringRef(Triple).startswith(TriplePrefix);
93 ErrorOr TripleOrErr =
94 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(*BCOrErr));
95 if (!TripleOrErr)
96 return false;
97 return StringRef(*TripleOrErr).startswith(TriplePrefix);
9698 }
9799
98100 std::string LTOModule::getProducerString(MemoryBuffer *Buffer) {
101103 if (!BCOrErr)
102104 return "";
103105 LLVMContext Context;
104 return getBitcodeProducerString(*BCOrErr, Context);
106 ErrorOr ProducerOrErr = expectedToErrorOrAndEmitErrors(
107 Context, getBitcodeProducerString(*BCOrErr));
108 if (!ProducerOrErr)
109 return "";
110 return *ProducerOrErr;
105111 }
106112
107113 ErrorOr>
452452 if (Modules.empty()) {
453453 // First module added, so initialize the triple and some options
454454 LLVMContext Context;
455 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
455 StringRef TripleStr;
456 ErrorOr TripleOrErr =
457 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
458 if (TripleOrErr)
459 TripleStr = *TripleOrErr;
460 Triple TheTriple(TripleStr);
456461 initTMBuilder(TMBuilder, Triple(TheTriple));
457462 }
458463 #ifndef NDEBUG
459464 else {
460465 LLVMContext Context;
461 assert(TMBuilder.TheTriple.str() ==
462 getBitcodeTargetTriple(Buffer, Context) &&
466 StringRef TripleStr;
467 ErrorOr TripleOrErr =
468 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
469 if (TripleOrErr)
470 TripleStr = *TripleOrErr;
471 assert(TMBuilder.TheTriple.str() == TripleStr &&
463472 "ThinLTO modules with different triple not supported");
464473 }
465474 #endif
6666 }
6767 }
6868
69 // Looks for module summary index in the given memory buffer.
70 // returns true if found, else false.
71 bool ModuleSummaryIndexObjectFile::hasGlobalValueSummaryInMemBuffer(
72 MemoryBufferRef Object,
73 const DiagnosticHandlerFunction &DiagnosticHandler) {
74 ErrorOr BCOrErr = findBitcodeInMemBuffer(Object);
75 if (!BCOrErr)
76 return false;
77
78 return hasGlobalValueSummary(BCOrErr.get(), DiagnosticHandler);
79 }
80
8169 // Parse module summary index in the given memory buffer.
8270 // Return new ModuleSummaryIndexObjectFile instance containing parsed
8371 // module summary/index.
772772
773773 if (CheckHasObjC) {
774774 for (auto &Filename : InputFilenames) {
775 ErrorOr> BufferOrErr =
776 MemoryBuffer::getFile(Filename);
777 error(BufferOrErr, "error loading file '" + Filename + "'");
775 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
776 Filename + "': ");
777 std::unique_ptr BufferOrErr =
778 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
778779 auto Buffer = std::move(BufferOrErr.get());
779 LLVMContext Ctx;
780 if (llvm::isBitcodeContainingObjCCategory(*Buffer, Ctx))
780 if (ExitOnErr(llvm::isBitcodeContainingObjCCategory(*Buffer)))
781781 outs() << "Bitcode " << Filename << " contains ObjC\n";
782782 else
783783 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
186186 if (!Buffer)
187187 return false;
188188 LLVMContext Ctx;
189 return llvm::isBitcodeContainingObjCCategory(*Buffer, Ctx);
189 ErrorOr Result = expectedToErrorOrAndEmitErrors(
190 Ctx, llvm::isBitcodeContainingObjCCategory(*Buffer));
191 return Result && *Result;
190192 }
191193
192194 bool lto_module_is_object_file_in_memory(const void* mem, size_t length) {