26 #include "llvm/Config/llvm-config.h" 84 #include <system_error> 94 "Print the global id for each value when reading the module summary"));
99 SWITCH_INST_MAGIC = 0x4B5
105 return make_error<StringError>(
113 Stream.
Read(8) !=
'B' ||
114 Stream.
Read(8) !=
'C' ||
115 Stream.
Read(4) != 0x0 ||
116 Stream.
Read(4) != 0xC ||
117 Stream.
Read(4) != 0xE ||
118 Stream.
Read(4) != 0xD)
124 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
125 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
128 return error(
"Invalid bitcode signature");
134 return error(
"Invalid bitcode wrapper header");
138 return error(
"Invalid bitcode signature");
140 return std::move(Stream);
144 template <
typename StrTy>
147 if (Idx > Record.
size())
150 for (
unsigned i = Idx, e = Record.
size(); i != e; ++i)
151 Result += (
char)Record[i];
158 if (
F.isMaterializable())
169 return error(
"Invalid record");
174 std::string ProducerIdentification;
179 switch (Entry.
Kind) {
182 return error(
"Malformed block");
184 return ProducerIdentification;
195 return error(
"Invalid value");
200 unsigned epoch = (
unsigned)Record[0];
203 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
219 switch (Entry.
Kind) {
222 return error(
"Malformed block");
230 return error(
"Malformed block");
241 return error(
"Invalid record");
249 switch (Entry.
Kind) {
252 return error(
"Malformed block");
267 return error(
"Invalid record");
269 if (S.find(
"__DATA,__objc_catlist") != std::string::npos ||
270 S.find(
"__OBJC,__category") != std::string::npos)
286 switch (Entry.
Kind) {
288 return error(
"Malformed block");
298 return error(
"Malformed block");
310 return error(
"Invalid record");
320 switch (Entry.
Kind) {
323 return error(
"Malformed block");
337 return error(
"Invalid record");
353 switch (Entry.
Kind) {
355 return error(
"Malformed block");
365 return error(
"Malformed block");
377 class BitcodeReaderBase {
380 : Stream(std::move(Stream)), Strtab(Strtab) {
390 bool UseStrtab =
false;
397 std::pair<StringRef, ArrayRef<uint64_t>>
400 bool readBlockInfo();
403 std::string ProducerIdentification;
411 std::string FullMsg = Message.
str();
412 if (!ProducerIdentification.empty())
413 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
414 LLVM_VERSION_STRING
"')";
421 return error(
"Invalid record");
422 unsigned ModuleVersion = Record[0];
423 if (ModuleVersion > 2)
424 return error(
"Invalid value");
425 UseStrtab = ModuleVersion >= 2;
426 return ModuleVersion;
429 std::pair<StringRef, ArrayRef<uint64_t>>
434 if (Record[0] + Record[1] > Strtab.
size())
436 return {
StringRef(Strtab.data() + Record[0], Record[1]), Record.
slice(2)};
441 class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
443 Module *TheModule =
nullptr;
445 uint64_t NextUnreadBit = 0;
447 uint64_t LastFunctionBlockBit = 0;
448 bool SeenValueSymbolTable =
false;
449 uint64_t VSTOffset = 0;
451 std::vector<std::string> SectionTable;
452 std::vector<std::string> GCTable;
454 std::vector<Type*> TypeList;
457 std::vector<Comdat *> ComdatList;
460 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
461 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
462 std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
463 std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
464 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
468 std::vector<AttributeList> MAttributes;
471 std::map<unsigned, AttributeList> MAttributeGroups;
475 std::vector<BasicBlock*> FunctionBBs;
479 std::vector<Function*> FunctionsWithBodies;
484 UpdatedIntrinsicMap UpgradedIntrinsics;
486 UpdatedIntrinsicMap RemangledIntrinsics;
491 bool SeenFirstFunctionBody =
false;
500 std::vector<uint64_t> DeferredMetadataInfo;
506 std::deque<Function *> BasicBlockFwdRefQueue;
514 bool UseRelativeIDs =
false;
518 bool WillMaterializeAllForwardRefs =
false;
523 std::vector<std::string> BundleTags;
530 Error materializeForwardReferencedFunctions();
533 Error materializeModule()
override;
534 std::vector<StructType *> getIdentifiedStructTypes()
const override;
538 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata =
false,
539 bool IsImporting =
false);
541 static uint64_t decodeSignRotatedValue(uint64_t V);
544 Error materializeMetadata()
override;
546 void setStripDebugInfo()
override;
549 std::vector<StructType *> IdentifiedStructTypes;
553 Type *getTypeByID(
unsigned ID);
555 Value *getFnValueByID(
unsigned ID,
Type *Ty) {
561 Metadata *getFnMetadataByID(
unsigned ID) {
565 BasicBlock *getBasicBlock(
unsigned ID)
const {
566 if (ID >= FunctionBBs.size())
return nullptr;
567 return FunctionBBs[
ID];
571 if (i-1 < MAttributes.size())
572 return MAttributes[i-1];
580 unsigned InstNum,
Value *&ResVal) {
581 if (Slot == Record.
size())
return true;
582 unsigned ValNo = (
unsigned)Record[Slot++];
585 ValNo = InstNum - ValNo;
586 if (ValNo < InstNum) {
589 ResVal = getFnValueByID(ValNo,
nullptr);
590 return ResVal ==
nullptr;
592 if (Slot == Record.
size())
595 unsigned TypeNo = (
unsigned)Record[Slot++];
596 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
597 return ResVal ==
nullptr;
604 unsigned InstNum,
Type *Ty,
Value *&ResVal) {
605 if (getValue(Record, Slot, InstNum, Ty, ResVal))
614 unsigned InstNum,
Type *Ty,
Value *&ResVal) {
615 ResVal = getValue(Record, Slot, InstNum, Ty);
616 return ResVal ==
nullptr;
622 unsigned InstNum,
Type *Ty) {
623 if (Slot == Record.
size())
return nullptr;
624 unsigned ValNo = (
unsigned)Record[Slot];
627 ValNo = InstNum - ValNo;
628 return getFnValueByID(ValNo, Ty);
633 unsigned InstNum,
Type *Ty) {
634 if (Slot == Record.
size())
return nullptr;
635 unsigned ValNo = (
unsigned)decodeSignRotatedValue(Record[Slot]);
638 ValNo = InstNum - ValNo;
639 return getFnValueByID(ValNo, Ty);
645 Error parseAlignmentValue(uint64_t
Exponent,
unsigned &Alignment);
652 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
655 Error parseAttributeBlock();
656 Error parseAttributeGroupBlock();
657 Error parseTypeTable();
658 Error parseTypeTableBody();
659 Error parseOperandBundleTags();
660 Error parseSyncScopeNames();
663 unsigned NameIndex,
Triple &TT);
664 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
Function *
F,
667 Error parseGlobalValueSymbolTable();
668 Error parseConstants();
669 Error rememberAndSkipFunctionBodies();
670 Error rememberAndSkipFunctionBody();
672 Error rememberAndSkipMetadata();
675 Error globalCleanup();
676 Error resolveGlobalAndIndirectSymbolInits();
677 Error parseUseLists();
678 Error findFunctionInStream(
687 class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
693 bool SeenGlobalValSummary =
false;
696 bool SeenValueSymbolTable =
false;
700 uint64_t VSTOffset = 0;
711 ValueIdToValueInfoMap;
720 std::string SourceFileName;
733 StringRef ModulePath,
unsigned ModuleId);
741 Error parseValueSymbolTable(
746 bool IsOldProfileFormat,
749 Error parseEntireSummary(
unsigned ID);
750 Error parseModuleStringTable();
752 std::pair<ValueInfo, GlobalValue::GUID>
753 getValueInfoFromValueId(
unsigned ValueId);
755 void addThisModule();
771 return std::error_code();
777 : BitcodeReaderBase(std::move(Stream), Strtab),
Context(Context),
779 this->ProducerIdentification = ProducerIdentification;
782 Error BitcodeReader::materializeForwardReferencedFunctions() {
783 if (WillMaterializeAllForwardRefs)
787 WillMaterializeAllForwardRefs =
true;
789 while (!BasicBlockFwdRefQueue.empty()) {
790 Function *
F = BasicBlockFwdRefQueue.front();
791 BasicBlockFwdRefQueue.pop_front();
792 assert(F &&
"Expected valid function");
793 if (!BasicBlockFwdRefs.count(F))
802 return error(
"Never resolved function from blockaddress");
805 if (
Error Err = materialize(F))
808 assert(BasicBlockFwdRefs.empty() &&
"Function missing from queue");
811 WillMaterializeAllForwardRefs =
false;
876 Flags.
ReadOnly = (RawFlags >> 1) & 0x1;
889 RawFlags = RawFlags >> 4;
890 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
894 bool Live = (RawFlags & 0x2) || Version < 3;
895 bool Local = (RawFlags & 0x4);
922 case 0:
return false;
978 return IsFP ? Instruction::FSub : Instruction::Sub;
980 return IsFP ? Instruction::FMul : Instruction::Mul;
982 return IsFP ? -1 : Instruction::UDiv;
984 return IsFP ? Instruction::FDiv : Instruction::SDiv;
986 return IsFP ? -1 : Instruction::URem;
988 return IsFP ? Instruction::FRem : Instruction::SRem;
990 return IsFP ? -1 : Instruction::Shl;
992 return IsFP ? -1 : Instruction::LShr;
994 return IsFP ? -1 : Instruction::AShr;
996 return IsFP ? -1 : Instruction::And;
998 return IsFP ? -1 : Instruction::Or;
1000 return IsFP ? -1 : Instruction::Xor;
1078 Type *BitcodeReader::getTypeByID(
unsigned ID) {
1080 if (ID >= TypeList.size())
1083 if (
Type *Ty = TypeList[ID])
1088 return TypeList[
ID] = createIdentifiedStructType(Context);
1094 IdentifiedStructTypes.push_back(
Ret);
1100 IdentifiedStructTypes.push_back(
Ret);
1114 case Attribute::ZExt:
return 1 << 0;
1115 case Attribute::SExt:
return 1 << 1;
1116 case Attribute::NoReturn:
return 1 << 2;
1117 case Attribute::InReg:
return 1 << 3;
1118 case Attribute::StructRet:
return 1 << 4;
1119 case Attribute::NoUnwind:
return 1 << 5;
1121 case Attribute::ByVal:
return 1 << 7;
1122 case Attribute::Nest:
return 1 << 8;
1123 case Attribute::ReadNone:
return 1 << 9;
1124 case Attribute::ReadOnly:
return 1 << 10;
1125 case Attribute::NoInline:
return 1 << 11;
1126 case Attribute::AlwaysInline:
return 1 << 12;
1127 case Attribute::OptimizeForSize:
return 1 << 13;
1128 case Attribute::StackProtect:
return 1 << 14;
1129 case Attribute::StackProtectReq:
return 1 << 15;
1130 case Attribute::Alignment:
return 31 << 16;
1131 case Attribute::NoCapture:
return 1 << 21;
1132 case Attribute::NoRedZone:
return 1 << 22;
1133 case Attribute::NoImplicitFloat:
return 1 << 23;
1134 case Attribute::Naked:
return 1 << 24;
1135 case Attribute::InlineHint:
return 1 << 25;
1136 case Attribute::StackAlignment:
return 7 << 26;
1137 case Attribute::ReturnsTwice:
return 1 << 29;
1138 case Attribute::UWTable:
return 1 << 30;
1139 case Attribute::NonLazyBind:
return 1U << 31;
1140 case Attribute::SanitizeAddress:
return 1ULL << 32;
1141 case Attribute::MinSize:
return 1ULL << 33;
1142 case Attribute::NoDuplicate:
return 1ULL << 34;
1143 case Attribute::StackProtectStrong:
return 1ULL << 35;
1144 case Attribute::SanitizeThread:
return 1ULL << 36;
1145 case Attribute::SanitizeMemory:
return 1ULL << 37;
1146 case Attribute::NoBuiltin:
return 1ULL << 38;
1147 case Attribute::Returned:
return 1ULL << 39;
1149 case Attribute::Builtin:
return 1ULL << 41;
1150 case Attribute::OptimizeNone:
return 1ULL << 42;
1151 case Attribute::InAlloca:
return 1ULL << 43;
1152 case Attribute::NonNull:
return 1ULL << 44;
1155 case Attribute::SafeStack:
return 1ULL << 47;
1156 case Attribute::NoRecurse:
return 1ULL << 48;
1157 case Attribute::InaccessibleMemOnly:
return 1ULL << 49;
1158 case Attribute::InaccessibleMemOrArgMemOnly:
return 1ULL << 50;
1159 case Attribute::SwiftSelf:
return 1ULL << 51;
1160 case Attribute::SwiftError:
return 1ULL << 52;
1161 case Attribute::WriteOnly:
return 1ULL << 53;
1162 case Attribute::Speculatable:
return 1ULL << 54;
1163 case Attribute::StrictFP:
return 1ULL << 55;
1164 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1165 case Attribute::NoCfCheck:
return 1ULL << 57;
1166 case Attribute::OptForFuzzing:
return 1ULL << 58;
1167 case Attribute::ShadowCallStack:
return 1ULL << 59;
1168 case Attribute::Dereferenceable:
1171 case Attribute::DereferenceableOrNull:
1175 case Attribute::ArgMemOnly:
1178 case Attribute::AllocSize:
1190 if (
I == Attribute::Dereferenceable ||
1191 I == Attribute::DereferenceableOrNull ||
1192 I == Attribute::ArgMemOnly ||
1193 I == Attribute::AllocSize)
1196 if (
I == Attribute::Alignment)
1198 else if (
I == Attribute::StackAlignment)
1210 uint64_t EncodedAttrs) {
1215 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1217 "Alignment must be a power of two.");
1222 (EncodedAttrs & 0xffff));
1225 Error BitcodeReader::parseAttributeBlock() {
1227 return error(
"Invalid record");
1229 if (!MAttributes.empty())
1230 return error(
"Invalid multiple blocks");
1240 switch (Entry.
Kind) {
1243 return error(
"Malformed block");
1258 if (Record.
size() & 1)
1259 return error(
"Invalid record");
1261 for (
unsigned i = 0, e = Record.
size(); i != e; i += 2) {
1271 for (
unsigned i = 0, e = Record.
size(); i != e; ++i)
1272 Attrs.
push_back(MAttributeGroups[Record[i]]);
1287 return Attribute::Alignment;
1289 return Attribute::AlwaysInline;
1291 return Attribute::ArgMemOnly;
1293 return Attribute::Builtin;
1295 return Attribute::ByVal;
1297 return Attribute::InAlloca;
1303 return Attribute::InaccessibleMemOnly;
1305 return Attribute::InaccessibleMemOrArgMemOnly;
1307 return Attribute::InlineHint;
1309 return Attribute::InReg;
1313 return Attribute::MinSize;
1315 return Attribute::Naked;
1317 return Attribute::Nest;
1321 return Attribute::NoBuiltin;
1323 return Attribute::NoCapture;
1325 return Attribute::NoDuplicate;
1327 return Attribute::NoImplicitFloat;
1329 return Attribute::NoInline;
1331 return Attribute::NoRecurse;
1333 return Attribute::NonLazyBind;
1335 return Attribute::NonNull;
1337 return Attribute::Dereferenceable;
1339 return Attribute::DereferenceableOrNull;
1341 return Attribute::AllocSize;
1343 return Attribute::NoRedZone;
1345 return Attribute::NoReturn;
1347 return Attribute::NoCfCheck;
1349 return Attribute::NoUnwind;
1351 return Attribute::OptForFuzzing;
1353 return Attribute::OptimizeForSize;
1355 return Attribute::OptimizeNone;
1357 return Attribute::ReadNone;
1359 return Attribute::ReadOnly;
1361 return Attribute::Returned;
1363 return Attribute::ReturnsTwice;
1365 return Attribute::SExt;
1367 return Attribute::Speculatable;
1369 return Attribute::StackAlignment;
1371 return Attribute::StackProtect;
1373 return Attribute::StackProtectReq;
1375 return Attribute::StackProtectStrong;
1377 return Attribute::SafeStack;
1379 return Attribute::ShadowCallStack;
1381 return Attribute::StrictFP;
1383 return Attribute::StructRet;
1385 return Attribute::SanitizeAddress;
1387 return Attribute::SanitizeHWAddress;
1389 return Attribute::SanitizeThread;
1391 return Attribute::SanitizeMemory;
1393 return Attribute::SwiftError;
1395 return Attribute::SwiftSelf;
1397 return Attribute::UWTable;
1399 return Attribute::WriteOnly;
1401 return Attribute::ZExt;
1406 unsigned &Alignment) {
1410 return error(
"Invalid alignment value");
1411 Alignment = (1 <<
static_cast<unsigned>(
Exponent)) >> 1;
1418 return error(
"Unknown attribute kind (" +
Twine(Code) +
")");
1422 Error BitcodeReader::parseAttributeGroupBlock() {
1424 return error(
"Invalid record");
1426 if (!MAttributeGroups.empty())
1427 return error(
"Invalid multiple blocks");
1435 switch (Entry.
Kind) {
1438 return error(
"Malformed block");
1452 if (Record.
size() < 3)
1453 return error(
"Invalid record");
1455 uint64_t GrpID = Record[0];
1456 uint64_t Idx = Record[1];
1459 for (
unsigned i = 2, e = Record.
size(); i != e; ++i) {
1460 if (Record[i] == 0) {
1466 }
else if (Record[i] == 1) {
1470 if (Kind == Attribute::Alignment)
1472 else if (Kind == Attribute::StackAlignment)
1474 else if (Kind == Attribute::Dereferenceable)
1476 else if (Kind == Attribute::DereferenceableOrNull)
1478 else if (Kind == Attribute::AllocSize)
1481 assert((Record[i] == 3 || Record[i] == 4) &&
1482 "Invalid attribute group entry");
1483 bool HasValue = (Record[i++] == 4);
1487 while (Record[i] != 0 && i != e)
1488 KindStr += Record[i++];
1489 assert(Record[i] == 0 &&
"Kind string not null terminated");
1494 while (Record[i] != 0 && i != e)
1495 ValStr += Record[i++];
1496 assert(Record[i] == 0 &&
"Value string not null terminated");
1510 Error BitcodeReader::parseTypeTable() {
1512 return error(
"Invalid record");
1514 return parseTypeTableBody();
1517 Error BitcodeReader::parseTypeTableBody() {
1518 if (!TypeList.empty())
1519 return error(
"Invalid multiple blocks");
1522 unsigned NumRecords = 0;
1530 switch (Entry.
Kind) {
1533 return error(
"Malformed block");
1535 if (NumRecords != TypeList.size())
1536 return error(
"Malformed block");
1545 Type *ResultTy =
nullptr;
1548 return error(
"Invalid value");
1552 if (Record.
size() < 1)
1553 return error(
"Invalid record");
1554 TypeList.resize(Record[0]);
1590 if (Record.
size() < 1)
1591 return error(
"Invalid record");
1593 uint64_t NumBits = Record[0];
1596 return error(
"Bitwidth for integer type out of range");
1602 if (Record.
size() < 1)
1603 return error(
"Invalid record");
1605 if (Record.
size() == 2)
1606 AddressSpace = Record[1];
1607 ResultTy = getTypeByID(Record[0]);
1610 return error(
"Invalid type");
1617 if (Record.
size() < 3)
1618 return error(
"Invalid record");
1620 for (
unsigned i = 3, e = Record.
size(); i != e; ++i) {
1621 if (
Type *
T = getTypeByID(Record[i]))
1627 ResultTy = getTypeByID(Record[2]);
1628 if (!ResultTy || ArgTys.
size() < Record.
size()-3)
1629 return error(
"Invalid type");
1636 if (Record.
size() < 2)
1637 return error(
"Invalid record");
1639 for (
unsigned i = 2, e = Record.
size(); i != e; ++i) {
1640 if (
Type *
T = getTypeByID(Record[i])) {
1642 return error(
"Invalid function argument type");
1649 ResultTy = getTypeByID(Record[1]);
1650 if (!ResultTy || ArgTys.
size() < Record.
size()-2)
1651 return error(
"Invalid type");
1657 if (Record.
size() < 1)
1658 return error(
"Invalid record");
1660 for (
unsigned i = 1, e = Record.
size(); i != e; ++i) {
1661 if (
Type *
T = getTypeByID(Record[i]))
1666 if (EltTys.
size() != Record.
size()-1)
1667 return error(
"Invalid type");
1673 return error(
"Invalid record");
1677 if (Record.
size() < 1)
1678 return error(
"Invalid record");
1680 if (NumRecords >= TypeList.size())
1681 return error(
"Invalid TYPE table");
1684 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1687 TypeList[NumRecords] =
nullptr;
1689 Res = createIdentifiedStructType(Context, TypeName);
1693 for (
unsigned i = 1, e = Record.
size(); i != e; ++i) {
1694 if (
Type *
T = getTypeByID(Record[i]))
1699 if (EltTys.
size() != Record.
size()-1)
1700 return error(
"Invalid record");
1701 Res->
setBody(EltTys, Record[0]);
1706 if (Record.
size() != 1)
1707 return error(
"Invalid record");
1709 if (NumRecords >= TypeList.size())
1710 return error(
"Invalid TYPE table");
1713 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1716 TypeList[NumRecords] =
nullptr;
1718 Res = createIdentifiedStructType(Context, TypeName);
1724 if (Record.
size() < 2)
1725 return error(
"Invalid record");
1726 ResultTy = getTypeByID(Record[1]);
1728 return error(
"Invalid type");
1732 if (Record.
size() < 2)
1733 return error(
"Invalid record");
1735 return error(
"Invalid vector length");
1736 ResultTy = getTypeByID(Record[1]);
1738 return error(
"Invalid type");
1743 if (NumRecords >= TypeList.size())
1744 return error(
"Invalid TYPE table");
1745 if (TypeList[NumRecords])
1747 "Invalid TYPE table: Only named structs can be forward referenced");
1748 assert(ResultTy &&
"Didn't read a type?");
1749 TypeList[NumRecords++] = ResultTy;
1753 Error BitcodeReader::parseOperandBundleTags() {
1755 return error(
"Invalid record");
1757 if (!BundleTags.empty())
1758 return error(
"Invalid multiple blocks");
1765 switch (Entry.
Kind) {
1768 return error(
"Malformed block");
1779 return error(
"Invalid record");
1782 BundleTags.emplace_back();
1784 return error(
"Invalid record");
1789 Error BitcodeReader::parseSyncScopeNames() {
1791 return error(
"Invalid record");
1794 return error(
"Invalid multiple synchronization scope names blocks");
1799 switch (Entry.
Kind) {
1802 return error(
"Malformed block");
1805 return error(
"Invalid empty synchronization scope names block");
1816 return error(
"Invalid record");
1820 return error(
"Invalid record");
1829 unsigned NameIndex,
Triple &TT) {
1832 return error(
"Invalid record");
1833 unsigned ValueID = Record[0];
1834 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1835 return error(
"Invalid record");
1836 Value *V = ValueList[ValueID];
1840 return error(
"Invalid value name");
1844 if (GO->getComdat() ==
reinterpret_cast<Comdat *
>(1)) {
1848 GO->setComdat(
nullptr);
1875 void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
1881 uint64_t FuncWordOffset = Record[1] - 1;
1882 uint64_t FuncBitOffset = FuncWordOffset * 32;
1883 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1887 if (FuncBitOffset > LastFunctionBlockBit)
1888 LastFunctionBlockBit = FuncBitOffset;
1892 Error BitcodeReader::parseGlobalValueSymbolTable() {
1893 unsigned FuncBitcodeOffsetDelta =
1897 return error(
"Invalid record");
1903 switch (Entry.
Kind) {
1906 return error(
"Malformed block");
1916 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1917 cast<Function>(ValueList[Record[0]]), Record);
1925 Error BitcodeReader::parseValueSymbolTable(uint64_t
Offset) {
1926 uint64_t CurrentBit;
1934 if (
Error Err = parseGlobalValueSymbolTable())
1954 unsigned FuncBitcodeOffsetDelta =
1958 return error(
"Invalid record");
1962 Triple TT(TheModule->getTargetTriple());
1970 switch (Entry.
Kind) {
1973 return error(
"Malformed block");
2004 if (
auto *F = dyn_cast<Function>(V))
2005 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2010 return error(
"Invalid record");
2013 return error(
"Invalid record");
2025 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2035 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2036 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2037 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2038 IndirectSymbolInitWorklist;
2039 std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2040 std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2041 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2043 GlobalInitWorklist.swap(GlobalInits);
2044 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2045 FunctionPrefixWorklist.swap(FunctionPrefixes);
2046 FunctionPrologueWorklist.swap(FunctionPrologues);
2047 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2049 while (!GlobalInitWorklist.empty()) {
2050 unsigned ValID = GlobalInitWorklist.back().second;
2051 if (ValID >= ValueList.size()) {
2053 GlobalInits.push_back(GlobalInitWorklist.back());
2055 if (
Constant *
C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2056 GlobalInitWorklist.back().first->setInitializer(
C);
2058 return error(
"Expected a constant");
2060 GlobalInitWorklist.pop_back();
2063 while (!IndirectSymbolInitWorklist.empty()) {
2064 unsigned ValID = IndirectSymbolInitWorklist.back().second;
2065 if (ValID >= ValueList.size()) {
2066 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2068 Constant *
C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2070 return error(
"Expected a constant");
2073 return error(
"Alias and aliasee types don't match");
2076 IndirectSymbolInitWorklist.pop_back();
2079 while (!FunctionPrefixWorklist.empty()) {
2080 unsigned ValID = FunctionPrefixWorklist.back().second;
2081 if (ValID >= ValueList.size()) {
2082 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2084 if (
Constant *
C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2085 FunctionPrefixWorklist.back().first->setPrefixData(
C);
2087 return error(
"Expected a constant");
2089 FunctionPrefixWorklist.pop_back();
2092 while (!FunctionPrologueWorklist.empty()) {
2093 unsigned ValID = FunctionPrologueWorklist.back().second;
2094 if (ValID >= ValueList.size()) {
2095 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2097 if (
Constant *
C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2098 FunctionPrologueWorklist.back().first->setPrologueData(
C);
2100 return error(
"Expected a constant");
2102 FunctionPrologueWorklist.pop_back();
2105 while (!FunctionPersonalityFnWorklist.empty()) {
2106 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2107 if (ValID >= ValueList.size()) {
2108 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2110 if (
Constant *
C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2111 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(
C);
2113 return error(
"Expected a constant");
2115 FunctionPersonalityFnWorklist.pop_back();
2124 BitcodeReader::decodeSignRotatedValue);
2126 return APInt(TypeBits, Words);
2129 Error BitcodeReader::parseConstants() {
2131 return error(
"Invalid record");
2137 unsigned NextCstNo = ValueList.size();
2142 switch (Entry.
Kind) {
2145 return error(
"Malformed block");
2147 if (NextCstNo != ValueList.size())
2148 return error(
"Invalid constant reference");
2152 ValueList.resolveConstantForwardRefs();
2163 unsigned BitCode = Stream.
readRecord(Entry.
ID, Record);
2171 return error(
"Invalid record");
2172 if (Record[0] >= TypeList.
size() || !TypeList[Record[0]])
2173 return error(
"Invalid record");
2174 if (TypeList[Record[0]] == VoidType)
2175 return error(
"Invalid constant type");
2176 CurTy = TypeList[Record[0]];
2183 return error(
"Invalid record");
2188 return error(
"Invalid record");
2198 return error(
"Invalid record");
2201 APInt(16, (uint16_t)Record[0])));
2207 APInt(64, Record[0])));
2210 uint64_t Rearrange[2];
2211 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2212 Rearrange[1] = Record[0] >> 48;
2214 APInt(80, Rearrange)));
2217 APInt(128, Record)));
2220 APInt(128, Record)));
2228 return error(
"Invalid record");
2230 unsigned Size = Record.size();
2233 if (
StructType *STy = dyn_cast<StructType>(CurTy)) {
2234 for (
unsigned i = 0; i !=
Size; ++i)
2235 Elts.
push_back(ValueList.getConstantFwdRef(Record[i],
2236 STy->getElementType(i)));
2238 }
else if (
ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2239 Type *EltTy = ATy->getElementType();
2240 for (
unsigned i = 0; i !=
Size; ++i)
2241 Elts.
push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2243 }
else if (
VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2244 Type *EltTy = VTy->getElementType();
2245 for (
unsigned i = 0; i !=
Size; ++i)
2246 Elts.
push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2256 return error(
"Invalid record");
2265 return error(
"Invalid record");
2267 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2270 if (isa<VectorType>(CurTy))
2276 if (isa<VectorType>(CurTy))
2282 if (isa<VectorType>(CurTy))
2288 if (isa<VectorType>(CurTy))
2294 if (isa<VectorType>(CurTy))
2300 if (isa<VectorType>(CurTy))
2306 if (isa<VectorType>(CurTy))
2311 return error(
"Invalid type for value");
2316 if (Record.size() < 3)
2317 return error(
"Invalid record");
2322 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2323 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2325 if (Record.size() >= 4) {
2327 Opc == Instruction::Sub ||
2328 Opc == Instruction::Mul ||
2329 Opc == Instruction::Shl) {
2334 }
else if (Opc == Instruction::SDiv ||
2335 Opc == Instruction::UDiv ||
2336 Opc == Instruction::LShr ||
2337 Opc == Instruction::AShr) {
2347 if (Record.size() < 3)
2348 return error(
"Invalid record");
2353 Type *OpTy = getTypeByID(Record[1]);
2355 return error(
"Invalid record");
2356 Constant *
Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2367 Type *PointeeType =
nullptr;
2370 PointeeType = getTypeByID(Record[OpNum++]);
2372 bool InBounds =
false;
2375 uint64_t
Op = Record[OpNum++];
2377 InRangeIndex = Op >> 1;
2382 while (OpNum != Record.size()) {
2383 Type *ElTy = getTypeByID(Record[OpNum++]);
2385 return error(
"Invalid record");
2386 Elts.
push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2391 cast<PointerType>(Elts[0]->
getType()->getScalarType())
2393 return error(
"Explicit gep operator type does not match pointee type " 2394 "of pointer operand");
2396 if (Elts.
size() < 1)
2397 return error(
"Invalid gep with no operands");
2401 InBounds, InRangeIndex);
2405 if (Record.size() < 3)
2406 return error(
"Invalid record");
2412 if (
VectorType *VTy = dyn_cast<VectorType>(CurTy))
2413 if (
Value *V = ValueList[Record[0]])
2414 if (SelectorTy != V->
getType())
2419 ValueList.getConstantFwdRef(Record[1],CurTy),
2420 ValueList.getConstantFwdRef(Record[2],CurTy));
2425 if (Record.size() < 3)
2426 return error(
"Invalid record");
2428 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2430 return error(
"Invalid record");
2431 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2433 if (Record.size() == 4) {
2434 Type *IdxTy = getTypeByID(Record[2]);
2436 return error(
"Invalid record");
2437 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2441 return error(
"Invalid record");
2448 if (Record.size() < 3 || !OpTy)
2449 return error(
"Invalid record");
2450 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2451 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2454 if (Record.size() == 4) {
2455 Type *IdxTy = getTypeByID(Record[2]);
2457 return error(
"Invalid record");
2458 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2462 return error(
"Invalid record");
2468 if (Record.size() < 3 || !OpTy)
2469 return error(
"Invalid record");
2470 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2471 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2474 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2481 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2482 if (Record.size() < 4 || !RTy || !OpTy)
2483 return error(
"Invalid record");
2484 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2485 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2488 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2493 if (Record.size() < 4)
2494 return error(
"Invalid record");
2495 Type *OpTy = getTypeByID(Record[0]);
2497 return error(
"Invalid record");
2498 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2499 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2510 if (Record.size() < 2)
2511 return error(
"Invalid record");
2512 std::string AsmStr, ConstrStr;
2513 bool HasSideEffects = Record[0] & 1;
2514 bool IsAlignStack = Record[0] >> 1;
2515 unsigned AsmStrSize = Record[1];
2516 if (2+AsmStrSize >= Record.size())
2517 return error(
"Invalid record");
2518 unsigned ConstStrSize = Record[2+AsmStrSize];
2519 if (3+AsmStrSize+ConstStrSize > Record.size())
2520 return error(
"Invalid record");
2522 for (
unsigned i = 0; i != AsmStrSize; ++i)
2523 AsmStr += (
char)Record[2+i];
2524 for (
unsigned i = 0; i != ConstStrSize; ++i)
2525 ConstrStr += (
char)Record[3+AsmStrSize+i];
2529 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2535 if (Record.size() < 2)
2536 return error(
"Invalid record");
2537 std::string AsmStr, ConstrStr;
2538 bool HasSideEffects = Record[0] & 1;
2539 bool IsAlignStack = (Record[0] >> 1) & 1;
2540 unsigned AsmDialect = Record[0] >> 2;
2541 unsigned AsmStrSize = Record[1];
2542 if (2+AsmStrSize >= Record.size())
2543 return error(
"Invalid record");
2544 unsigned ConstStrSize = Record[2+AsmStrSize];
2545 if (3+AsmStrSize+ConstStrSize > Record.size())
2546 return error(
"Invalid record");
2548 for (
unsigned i = 0; i != AsmStrSize; ++i)
2549 AsmStr += (
char)Record[2+i];
2550 for (
unsigned i = 0; i != ConstStrSize; ++i)
2551 ConstrStr += (
char)Record[3+AsmStrSize+i];
2555 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2560 if (Record.size() < 3)
2561 return error(
"Invalid record");
2562 Type *FnTy = getTypeByID(Record[0]);
2564 return error(
"Invalid record");
2566 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2568 return error(
"Invalid record");
2573 unsigned BBID = Record[2];
2576 return error(
"Invalid ID");
2579 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
2581 return error(
"Invalid ID");
2588 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2590 BasicBlockFwdRefQueue.push_back(Fn);
2591 if (FwdBBs.size() < BBID + 1)
2592 FwdBBs.resize(BBID + 1);
2602 ValueList.assignValue(V, NextCstNo);
2607 Error BitcodeReader::parseUseLists() {
2609 return error(
"Invalid record");
2617 switch (Entry.
Kind) {
2620 return error(
"Malformed block");
2638 unsigned RecordLength = Record.
size();
2639 if (RecordLength < 3)
2641 return error(
"Invalid record");
2642 unsigned ID = Record.
back();
2647 assert(ID < FunctionBBs.size() &&
"Basic block not found");
2648 V = FunctionBBs[
ID];
2651 unsigned NumUses = 0;
2654 if (++NumUses > Record.
size())
2656 Order[&U] = Record[NumUses - 1];
2658 if (Order.
size() != Record.
size() || NumUses > Record.
size())
2674 Error BitcodeReader::rememberAndSkipMetadata() {
2677 DeferredMetadataInfo.push_back(CurBit);
2681 return error(
"Invalid record");
2685 Error BitcodeReader::materializeMetadata() {
2686 for (uint64_t BitPos : DeferredMetadataInfo) {
2689 if (
Error Err = MDLoader->parseModuleMetadata())
2695 if (
Metadata *Val = TheModule->getModuleFlag(
"Linker Options")) {
2697 TheModule->getOrInsertNamedMetadata(
"llvm.linker.options");
2698 for (
const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2699 LinkerOpts->
addOperand(cast<MDNode>(MDOptions));
2702 DeferredMetadataInfo.clear();
2706 void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
2710 Error BitcodeReader::rememberAndSkipFunctionBody() {
2712 if (FunctionsWithBodies.empty())
2713 return error(
"Insufficient function protos");
2716 FunctionsWithBodies.pop_back();
2721 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2722 "Mismatch between VST and scanned function offsets");
2723 DeferredFunctionInfo[Fn] = CurBit;
2727 return error(
"Invalid record");
2731 Error BitcodeReader::globalCleanup() {
2733 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
2735 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2736 return error(
"Malformed global initializer set");
2740 MDLoader->upgradeDebugIntrinsics(F);
2743 UpgradedIntrinsics[&
F] = NewFn;
2748 RemangledIntrinsics[&
F] = Remangled.getValue();
2757 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
2758 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().
swap(
2759 IndirectSymbolInits);
2767 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2771 return error(
"Could not find function in stream");
2773 if (!SeenFirstFunctionBody)
2774 return error(
"Trying to materialize functions before seeing function blocks");
2778 assert(SeenValueSymbolTable);
2784 switch (Entry.
Kind) {
2786 return error(
"Expect SubBlock");
2790 return error(
"Expect function block");
2792 if (
Error Err = rememberAndSkipFunctionBody())
2801 bool BitcodeReaderBase::readBlockInfo() {
2805 BlockInfo = std::move(*NewBlockInfo);
2813 std::tie(Name, Record) = readNameFromStrtab(Record);
2816 return error(
"Invalid record");
2818 std::string OldFormatName;
2820 if (Record.
size() < 2)
2821 return error(
"Invalid record");
2822 unsigned ComdatNameSize = Record[1];
2823 OldFormatName.reserve(ComdatNameSize);
2824 for (
unsigned i = 0; i != ComdatNameSize; ++i)
2825 OldFormatName += (
char)Record[2 + i];
2826 Name = OldFormatName;
2828 Comdat *
C = TheModule->getOrInsertComdat(Name);
2830 ComdatList.push_back(C);
2847 std::tie(Name, Record) = readNameFromStrtab(Record);
2849 if (Record.
size() < 6)
2850 return error(
"Invalid record");
2851 Type *Ty = getTypeByID(Record[0]);
2853 return error(
"Invalid record");
2855 bool explicitType = Record[1] & 2;
2858 AddressSpace = Record[1] >> 2;
2861 return error(
"Invalid type for value");
2862 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2863 Ty = cast<PointerType>(Ty)->getElementType();
2866 uint64_t RawLinkage = Record[3];
2869 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
2873 if (Record[5] - 1 >= SectionTable.
size())
2874 return error(
"Invalid ID");
2875 Section = SectionTable[Record[5] - 1];
2884 if (Record.
size() > 7)
2888 if (Record.
size() > 8)
2891 bool ExternallyInitialized =
false;
2892 if (Record.
size() > 9)
2893 ExternallyInitialized = Record[9];
2896 new GlobalVariable(*TheModule, Ty, isConstant, Linkage,
nullptr, Name,
2897 nullptr, TLM, AddressSpace, ExternallyInitialized);
2899 if (!Section.empty())
2904 if (Record.
size() > 10)
2909 ValueList.push_back(NewGV);
2912 if (
unsigned InitID = Record[2])
2913 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2915 if (Record.
size() > 11) {
2916 if (
unsigned ComdatID = Record[11]) {
2917 if (ComdatID > ComdatList.size())
2918 return error(
"Invalid global variable comdat ID");
2919 NewGV->
setComdat(ComdatList[ComdatID - 1]);
2922 NewGV->
setComdat(reinterpret_cast<Comdat *>(1));
2925 if (Record.
size() > 12) {
2930 if (Record.
size() > 13) {
2944 std::tie(Name, Record) = readNameFromStrtab(Record);
2946 if (Record.
size() < 8)
2947 return error(
"Invalid record");
2948 Type *Ty = getTypeByID(Record[0]);
2950 return error(
"Invalid record");
2951 if (
auto *PTy = dyn_cast<PointerType>(Ty))
2952 Ty = PTy->getElementType();
2955 return error(
"Invalid type for value");
2958 return error(
"Invalid calling convention ID");
2964 bool isProto = Record[2];
2965 uint64_t RawLinkage = Record[3];
2970 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
2974 if (Record[6] - 1 >= SectionTable.
size())
2975 return error(
"Invalid ID");
2976 Func->
setSection(SectionTable[Record[6] - 1]);
2982 if (Record.
size() > 8 && Record[8]) {
2983 if (Record[8] - 1 >= GCTable.
size())
2984 return error(
"Invalid ID");
2985 Func->
setGC(GCTable[Record[8] - 1]);
2988 if (Record.
size() > 9)
2991 if (Record.
size() > 10 && Record[10] != 0)
2992 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2994 if (Record.
size() > 11)
2999 if (Record.
size() > 12) {
3000 if (
unsigned ComdatID = Record[12]) {
3001 if (ComdatID > ComdatList.size())
3002 return error(
"Invalid function comdat ID");
3003 Func->
setComdat(ComdatList[ComdatID - 1]);
3006 Func->
setComdat(reinterpret_cast<Comdat *>(1));
3009 if (Record.
size() > 13 && Record[13] != 0)
3010 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
3012 if (Record.
size() > 14 && Record[14] != 0)
3013 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3015 if (Record.
size() > 15) {
3020 ValueList.push_back(Func);
3026 FunctionsWithBodies.push_back(Func);
3027 DeferredFunctionInfo[Func] = 0;
3032 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3043 std::tie(Name, Record) = readNameFromStrtab(Record);
3047 return error(
"Invalid record");
3049 Type *Ty = getTypeByID(Record[OpNum++]);
3051 return error(
"Invalid record");
3057 return error(
"Invalid type for value");
3058 Ty = PTy->getElementType();
3059 AddrSpace = PTy->getAddressSpace();
3061 AddrSpace = Record[OpNum++];
3064 auto Val = Record[OpNum++];
3065 auto Linkage = Record[OpNum++];
3073 nullptr, TheModule);
3076 if (OpNum != Record.
size()) {
3077 auto VisInd = OpNum++;
3084 if (OpNum != Record.
size())
3088 if (OpNum != Record.
size())
3090 if (OpNum != Record.
size())
3093 if (OpNum != Record.
size())
3097 ValueList.push_back(NewGA);
3098 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3103 bool ShouldLazyLoadMetadata) {
3107 return error(
"Invalid record");
3115 switch (Entry.
Kind) {
3117 return error(
"Malformed block");
3119 return globalCleanup();
3125 return error(
"Invalid record");
3128 if (readBlockInfo())
3129 return error(
"Malformed block");
3132 if (
Error Err = parseAttributeBlock())
3136 if (
Error Err = parseAttributeGroupBlock())
3140 if (
Error Err = parseTypeTable())
3144 if (!SeenValueSymbolTable) {
3150 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3151 if (
Error Err = parseValueSymbolTable())
3153 SeenValueSymbolTable =
true;
3159 return error(
"Invalid record");
3163 if (
Error Err = parseConstants())
3165 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
3169 if (ShouldLazyLoadMetadata) {
3170 if (
Error Err = rememberAndSkipMetadata())
3174 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
3175 if (
Error Err = MDLoader->parseModuleMetadata())
3179 if (
Error Err = MDLoader->parseMetadataKinds())
3185 if (!SeenFirstFunctionBody) {
3186 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3187 if (
Error Err = globalCleanup())
3189 SeenFirstFunctionBody =
true;
3192 if (VSTOffset > 0) {
3196 if (!SeenValueSymbolTable) {
3197 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3199 SeenValueSymbolTable =
true;
3212 return error(
"Invalid record");
3221 if (
Error Err = rememberAndSkipFunctionBody())
3228 if (SeenValueSymbolTable) {
3232 return globalCleanup();
3236 if (
Error Err = parseUseLists())
3240 if (
Error Err = parseOperandBundleTags())
3244 if (
Error Err = parseSyncScopeNames())
3263 UseRelativeIDs = *VersionOrErr >= 1;
3269 return error(
"Invalid record");
3270 TheModule->setTargetTriple(S);
3276 return error(
"Invalid record");
3277 TheModule->setDataLayout(S);
3283 return error(
"Invalid record");
3284 TheModule->setModuleInlineAsm(S);
3291 return error(
"Invalid record");
3298 return error(
"Invalid record");
3299 SectionTable.push_back(S);
3305 return error(
"Invalid record");
3306 GCTable.push_back(S);
3310 if (
Error Err = parseComdatRecord(Record))
3314 if (
Error Err = parseGlobalVarRecord(Record))
3318 if (
Error Err = parseFunctionRecord(Record))
3324 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3329 if (Record.
size() < 1)
3330 return error(
"Invalid record");
3334 VSTOffset = Record[0] - 1;
3340 return error(
"Invalid record");
3341 TheModule->setSourceFileName(ValueName);
3348 Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
3352 [&](
unsigned ID) {
return getTypeByID(ID); });
3357 if (!isa<PointerType>(PtrType))
3358 return error(
"Load/Store operand is not a pointer type");
3359 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3361 if (ValType && ValType != ElemType)
3362 return error(
"Explicit load/store type does not match pointee " 3363 "type of pointer operand");
3365 return error(
"Cannot load/store from pointer");
3372 return error(
"Invalid record");
3375 if (MDLoader->hasFwdRefs())
3376 return error(
"Invalid function metadata: incoming forward references");
3378 InstructionList.clear();
3379 unsigned ModuleValueListSize = ValueList.size();
3380 unsigned ModuleMDLoaderSize = MDLoader->size();
3384 ValueList.push_back(&
I);
3386 unsigned NextValueNo = ValueList.size();
3388 unsigned CurBBNo = 0;
3391 auto getLastInstruction = [&]() ->
Instruction * {
3392 if (CurBB && !CurBB->
empty())
3393 return &CurBB->
back();
3394 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3395 !FunctionBBs[CurBBNo - 1]->empty())
3396 return &FunctionBBs[CurBBNo - 1]->back();
3400 std::vector<OperandBundleDef> OperandBundles;
3408 switch (Entry.
Kind) {
3410 return error(
"Malformed block");
3412 goto OutOfRecordLoop;
3418 return error(
"Invalid record");
3421 if (
Error Err = parseConstants())
3423 NextValueNo = ValueList.size();
3426 if (
Error Err = parseValueSymbolTable())
3430 if (
Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3434 assert(DeferredMetadataInfo.empty() &&
3435 "Must read all module-level metadata before function-level");
3436 if (
Error Err = MDLoader->parseFunctionMetadata())
3440 if (
Error Err = parseUseLists())
3454 unsigned BitCode = Stream.
readRecord(Entry.
ID, Record);
3457 return error(
"Invalid value");
3459 if (Record.
size() < 1 || Record[0] == 0)
3460 return error(
"Invalid record");
3462 FunctionBBs.resize(Record[0]);
3465 auto BBFRI = BasicBlockFwdRefs.find(F);
3466 if (BBFRI == BasicBlockFwdRefs.end()) {
3467 for (
unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3470 auto &BBRefs = BBFRI->second;
3472 if (BBRefs.size() > FunctionBBs.size())
3473 return error(
"Invalid ID");
3474 assert(!BBRefs.empty() &&
"Unexpected empty array");
3475 assert(!BBRefs.front() &&
"Invalid reference to entry block");
3476 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size(); I !=
E;
3478 if (I < RE && BBRefs[I]) {
3479 BBRefs[
I]->insertInto(F);
3480 FunctionBBs[
I] = BBRefs[
I];
3486 BasicBlockFwdRefs.erase(BBFRI);
3489 CurBB = FunctionBBs[0];
3496 I = getLastInstruction();
3499 return error(
"Invalid record");
3505 I = getLastInstruction();
3506 if (!I || Record.
size() < 4)
3507 return error(
"Invalid record");
3509 unsigned Line = Record[0], Col = Record[1];
3510 unsigned ScopeID = Record[2], IAID = Record[3];
3512 MDNode *Scope =
nullptr, *IA =
nullptr;
3514 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
3516 return error(
"Invalid record");
3519 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
3521 return error(
"Invalid record");
3532 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3533 popValue(Record, OpNum, NextValueNo, LHS->
getType(), RHS) ||
3534 OpNum+1 > Record.
size())
3535 return error(
"Invalid record");
3539 return error(
"Invalid record");
3541 InstructionList.push_back(I);
3542 if (OpNum < Record.
size()) {
3544 Opc == Instruction::Sub ||
3545 Opc == Instruction::Mul ||
3546 Opc == Instruction::Shl) {
3548 cast<BinaryOperator>(I)->setHasNoSignedWrap(
true);
3550 cast<BinaryOperator>(
I)->setHasNoUnsignedWrap(
true);
3551 }
else if (Opc == Instruction::SDiv ||
3552 Opc == Instruction::UDiv ||
3553 Opc == Instruction::LShr ||
3554 Opc == Instruction::AShr) {
3556 cast<BinaryOperator>(
I)->setIsExact(
true);
3557 }
else if (isa<FPMathOperator>(I)) {
3569 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3570 OpNum+2 != Record.
size())
3571 return error(
"Invalid record");
3573 Type *ResTy = getTypeByID(Record[OpNum]);
3575 if (Opc == -1 || !ResTy)
3576 return error(
"Invalid record");
3580 InstructionList.push_back(Temp);
3586 return error(
"Invalid cast");
3589 InstructionList.push_back(I);
3601 InBounds = Record[OpNum++];
3602 Ty = getTypeByID(Record[OpNum++]);
3609 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3610 return error(
"Invalid record");
3619 "Explicit gep type does not match pointee type of pointer operand");
3622 while (OpNum != Record.
size()) {
3624 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3625 return error(
"Invalid record");
3631 InstructionList.push_back(I);
3633 cast<GetElementPtrInst>(
I)->setIsInBounds(
true);
3641 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3642 return error(
"Invalid record");
3644 unsigned RecSize = Record.
size();
3645 if (OpNum == RecSize)
3646 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
3650 for (; OpNum != RecSize; ++OpNum) {
3653 uint64_t
Index = Record[OpNum];
3655 if (!IsStruct && !IsArray)
3656 return error(
"EXTRACTVAL: Invalid type");
3657 if ((
unsigned)Index != Index)
3658 return error(
"Invalid value");
3659 if (IsStruct && Index >= CurTy->
subtypes().size())
3660 return error(
"EXTRACTVAL: Invalid struct index");
3662 return error(
"EXTRACTVAL: Invalid array index");
3663 EXTRACTVALIdx.
push_back((
unsigned)Index);
3672 InstructionList.push_back(I);
3680 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3681 return error(
"Invalid record");
3683 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3684 return error(
"Invalid record");
3686 unsigned RecSize = Record.
size();
3687 if (OpNum == RecSize)
3688 return error(
"INSERTVAL: Invalid instruction with 0 indices");
3692 for (; OpNum != RecSize; ++OpNum) {
3695 uint64_t
Index = Record[OpNum];
3697 if (!IsStruct && !IsArray)
3698 return error(
"INSERTVAL: Invalid type");
3699 if ((
unsigned)Index != Index)
3700 return error(
"Invalid value");
3701 if (IsStruct && Index >= CurTy->
subtypes().size())
3702 return error(
"INSERTVAL: Invalid struct index");
3704 return error(
"INSERTVAL: Invalid array index");
3706 INSERTVALIdx.
push_back((
unsigned)Index);
3714 return error(
"Inserted value type doesn't match aggregate type");
3717 InstructionList.push_back(I);
3725 Value *TrueVal, *FalseVal, *Cond;
3726 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3727 popValue(Record, OpNum, NextValueNo, TrueVal->
getType(), FalseVal) ||
3729 return error(
"Invalid record");
3732 InstructionList.push_back(I);
3740 Value *TrueVal, *FalseVal, *Cond;
3741 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3742 popValue(Record, OpNum, NextValueNo, TrueVal->
getType(), FalseVal) ||
3743 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3744 return error(
"Invalid record");
3748 dyn_cast<VectorType>(Cond->
getType())) {
3751 return error(
"Invalid type for value");
3755 return error(
"Invalid type for value");
3759 InstructionList.push_back(I);
3766 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3767 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3768 return error(
"Invalid record");
3770 return error(
"Invalid type for value");
3772 InstructionList.push_back(I);
3778 Value *Vec, *Elt, *Idx;
3779 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3780 return error(
"Invalid record");
3782 return error(
"Invalid type for value");
3783 if (popValue(Record, OpNum, NextValueNo,
3784 cast<VectorType>(Vec->
getType())->getElementType(), Elt) ||
3785 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3786 return error(
"Invalid record");
3788 InstructionList.push_back(I);
3795 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3796 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec2))
3797 return error(
"Invalid record");
3799 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3800 return error(
"Invalid record");
3802 return error(
"Invalid type for value");
3804 InstructionList.push_back(I);
3817 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3818 popValue(Record, OpNum, NextValueNo, LHS->
getType(), RHS))
3819 return error(
"Invalid record");
3821 unsigned PredVal = Record[OpNum];
3824 if (IsFP && Record.
size() > OpNum+1)
3827 if (OpNum+1 != Record.
size())
3828 return error(
"Invalid record");
3837 InstructionList.push_back(I);
3846 InstructionList.push_back(I);
3852 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3853 return error(
"Invalid record");
3854 if (OpNum != Record.
size())
3855 return error(
"Invalid record");
3858 InstructionList.push_back(I);
3862 if (Record.
size() != 1 && Record.
size() != 3)
3863 return error(
"Invalid record");
3864 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3866 return error(
"Invalid record");
3868 if (Record.
size() == 1) {
3870 InstructionList.push_back(I);
3873 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3874 Value *Cond = getValue(Record, 2, NextValueNo,
3876 if (!FalseDest || !Cond)
3877 return error(
"Invalid record");
3879 InstructionList.push_back(I);
3884 if (Record.
size() != 1 && Record.
size() != 2)
3885 return error(
"Invalid record");
3890 return error(
"Invalid record");
3892 if (Record.
size() == 2) {
3893 UnwindDest = getBasicBlock(Record[Idx++]);
3895 return error(
"Invalid record");
3899 InstructionList.push_back(I);
3903 if (Record.
size() != 2)
3904 return error(
"Invalid record");
3909 return error(
"Invalid record");
3910 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3912 return error(
"Invalid record");
3915 InstructionList.push_back(I);
3920 if (Record.
size() < 2)
3921 return error(
"Invalid record");
3928 unsigned NumHandlers = Record[Idx++];
3931 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
3932 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3934 return error(
"Invalid record");
3939 if (Idx + 1 == Record.
size()) {
3940 UnwindDest = getBasicBlock(Record[Idx++]);
3942 return error(
"Invalid record");
3945 if (Record.
size() != Idx)
3946 return error(
"Invalid record");
3951 CatchSwitch->addHandler(Handler);
3953 InstructionList.push_back(I);
3959 if (Record.
size() < 2)
3960 return error(
"Invalid record");
3967 unsigned NumArgOperands = Record[Idx++];
3970 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
3972 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3973 return error(
"Invalid record");
3977 if (Record.
size() != Idx)
3978 return error(
"Invalid record");
3984 InstructionList.push_back(I);
3989 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3995 Type *OpTy = getTypeByID(Record[1]);
3996 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->
getBitWidth();
3998 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4000 if (!OpTy || !Cond || !Default)
4001 return error(
"Invalid record");
4003 unsigned NumCases = Record[4];
4006 InstructionList.push_back(SI);
4008 unsigned CurIdx = 5;
4009 for (
unsigned i = 0; i != NumCases; ++i) {
4011 unsigned NumItems = Record[CurIdx++];
4012 for (
unsigned ci = 0; ci != NumItems; ++ci) {
4013 bool isSingleNumber = Record[CurIdx++];
4016 unsigned ActiveWords = 1;
4017 if (ValueBitWidth > 64)
4018 ActiveWords = Record[CurIdx++];
4021 CurIdx += ActiveWords;
4023 if (!isSingleNumber) {
4025 if (ValueBitWidth > 64)
4026 ActiveWords = Record[CurIdx++];
4028 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4029 CurIdx += ActiveWords;
4035 for ( ; Low.
ule(High); ++Low)
4040 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4042 cve = CaseVals.
end(); cvi != cve; ++cvi)
4051 if (Record.
size() < 3 || (Record.
size() & 1) == 0)
4052 return error(
"Invalid record");
4053 Type *OpTy = getTypeByID(Record[0]);
4054 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4056 if (!OpTy || !Cond || !Default)
4057 return error(
"Invalid record");
4058 unsigned NumCases = (Record.
size()-3)/2;
4060 InstructionList.push_back(SI);
4061 for (
unsigned i = 0, e = NumCases; i != e; ++i) {
4063 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4064 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4065 if (!CaseVal || !DestBB) {
4067 return error(
"Invalid record");
4075 if (Record.
size() < 2)
4076 return error(
"Invalid record");
4077 Type *OpTy = getTypeByID(Record[0]);
4078 Value *
Address = getValue(Record, 1, NextValueNo, OpTy);
4079 if (!OpTy || !Address)
4080 return error(
"Invalid record");
4081 unsigned NumDests = Record.
size()-2;
4083 InstructionList.push_back(IBI);
4084 for (
unsigned i = 0, e = NumDests; i != e; ++i) {
4085 if (
BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4089 return error(
"Invalid record");
4098 if (Record.
size() < 4)
4099 return error(
"Invalid record");
4102 unsigned CCInfo = Record[OpNum++];
4103 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4104 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4107 if (CCInfo >> 13 & 1 &&
4108 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4109 return error(
"Explicit invoke type is not a function type");
4112 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4113 return error(
"Invalid record");
4117 return error(
"Callee is not a pointer");
4121 return error(
"Callee is not of pointer to function type");
4123 return error(
"Explicit invoke type does not match pointee type of " 4126 return error(
"Insufficient operands to call");
4129 for (
unsigned i = 0, e = FTy->
getNumParams(); i != e; ++i, ++OpNum) {
4130 Ops.
push_back(getValue(Record, OpNum, NextValueNo,
4133 return error(
"Invalid record");
4137 if (Record.
size() != OpNum)
4138 return error(
"Invalid record");
4141 while (OpNum != Record.
size()) {
4143 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4144 return error(
"Invalid record");
4150 OperandBundles.clear();
4151 InstructionList.push_back(I);
4152 cast<InvokeInst>(
I)->setCallingConv(
4154 cast<InvokeInst>(
I)->setAttributes(PAL);
4159 Value *Val =
nullptr;
4160 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4161 return error(
"Invalid record");
4163 InstructionList.push_back(I);
4168 InstructionList.push_back(I);
4171 if (Record.
size() < 1 || ((Record.
size()-1)&1))
4172 return error(
"Invalid record");
4173 Type *Ty = getTypeByID(Record[0]);
4175 return error(
"Invalid record");
4178 InstructionList.push_back(PN);
4180 for (
unsigned i = 0, e = Record.
size()-1; i != e; i += 2) {
4186 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4188 V = getValue(Record, 1+i, NextValueNo, Ty);
4191 return error(
"Invalid record");
4203 if (Record.
size() < 3)
4204 return error(
"Invalid record");
4207 if (Record.
size() < 4)
4208 return error(
"Invalid record");
4210 Type *Ty = getTypeByID(Record[Idx++]);
4212 return error(
"Invalid record");
4214 Value *PersFn =
nullptr;
4215 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4216 return error(
"Invalid record");
4221 return error(
"Personality function mismatch");
4224 bool IsCleanup = !!Record[Idx++];
4225 unsigned NumClauses = Record[Idx++];
4228 for (
unsigned J = 0; J != NumClauses; ++J) {
4233 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4235 return error(
"Invalid record");
4239 !isa<ArrayType>(Val->
getType())) &&
4240 "Catch clause has a invalid type!");
4242 isa<ArrayType>(Val->
getType())) &&
4243 "Filter clause has invalid type!");
4248 InstructionList.push_back(I);
4253 if (Record.
size() != 4)
4254 return error(
"Invalid record");
4255 uint64_t AlignRecord = Record[3];
4256 const uint64_t InAllocaMask = uint64_t(1) << 5;
4257 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4258 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4259 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4261 bool InAlloca = AlignRecord & InAllocaMask;
4262 bool SwiftError = AlignRecord & SwiftErrorMask;
4263 Type *Ty = getTypeByID(Record[0]);
4264 if ((AlignRecord & ExplicitTypeMask) == 0) {
4265 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4267 return error(
"Old-style alloca with a non-pointer type");
4268 Ty = PTy->getElementType();
4270 Type *OpTy = getTypeByID(Record[1]);
4271 Value *
Size = getFnValueByID(Record[2], OpTy);
4273 if (
Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4277 return error(
"Invalid record");
4280 const DataLayout &DL = TheModule->getDataLayout();
4287 InstructionList.push_back(I);
4293 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4294 (OpNum + 2 != Record.
size() && OpNum + 3 != Record.
size()))
4295 return error(
"Invalid record");
4298 if (OpNum + 3 == Record.
size())
4299 Ty = getTypeByID(Record[OpNum++]);
4300 if (
Error Err = typeCheckLoadStoreInst(Ty, Op->
getType()))
4303 Ty = cast<PointerType>(Op->
getType())->getElementType();
4306 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4308 I =
new LoadInst(Ty, Op,
"", Record[OpNum + 1], Align);
4310 InstructionList.push_back(I);
4317 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4318 (OpNum + 4 != Record.
size() && OpNum + 5 != Record.
size()))
4319 return error(
"Invalid record");
4322 if (OpNum + 5 == Record.
size())
4323 Ty = getTypeByID(Record[OpNum++]);
4324 if (
Error Err = typeCheckLoadStoreInst(Ty, Op->
getType()))
4327 Ty = cast<PointerType>(Op->
getType())->getElementType();
4333 return error(
"Invalid record");
4335 return error(
"Invalid record");
4336 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4339 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4341 I =
new LoadInst(Op,
"", Record[OpNum+1], Align, Ordering, SSID);
4343 InstructionList.push_back(I);
4350 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4352 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4353 : popValue(Record, OpNum, NextValueNo,
4354 cast<PointerType>(Ptr->
getType())->getElementType(),
4356 OpNum + 2 != Record.
size())
4357 return error(
"Invalid record");
4362 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4364 I =
new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4365 InstructionList.push_back(I);
4373 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4374 !isa<PointerType>(Ptr->
getType()) ||
4376 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4377 : popValue(Record, OpNum, NextValueNo,
4378 cast<PointerType>(Ptr->
getType())->getElementType(),
4380 OpNum + 4 != Record.
size())
4381 return error(
"Invalid record");
4389 return error(
"Invalid record");
4390 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4392 return error(
"Invalid record");
4395 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4397 I =
new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
4398 InstructionList.push_back(I);
4407 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4409 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4410 : popValue(Record, OpNum, NextValueNo,
4411 cast<PointerType>(Ptr->
getType())->getElementType(),
4413 popValue(Record, OpNum, NextValueNo, Cmp->
getType(), New) ||
4414 Record.
size() < OpNum + 3 || Record.
size() > OpNum + 5)
4415 return error(
"Invalid record");
4419 return error(
"Invalid record");
4420 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
4425 if (Record.
size() < 7)
4433 cast<AtomicCmpXchgInst>(
I)->setVolatile(Record[OpNum]);
4435 if (Record.
size() < 8) {
4442 cast<AtomicCmpXchgInst>(
I)->setWeak(Record[OpNum+4]);
4445 InstructionList.push_back(I);
4452 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4453 !isa<PointerType>(Ptr->
getType()) ||
4454 popValue(Record, OpNum, NextValueNo,
4455 cast<PointerType>(Ptr->
getType())->getElementType(), Val) ||
4456 OpNum+4 != Record.
size())
4457 return error(
"Invalid record");
4461 return error(
"Invalid record");
4465 return error(
"Invalid record");
4466 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4468 cast<AtomicRMWInst>(
I)->setVolatile(Record[OpNum+1]);
4469 InstructionList.push_back(I);
4473 if (2 != Record.
size())
4474 return error(
"Invalid record");
4479 return error(
"Invalid record");
4481 I =
new FenceInst(Context, Ordering, SSID);
4482 InstructionList.push_back(I);
4487 if (Record.
size() < 3)
4488 return error(
"Invalid record");
4492 unsigned CCInfo = Record[OpNum++];
4498 return error(
"Fast math flags indicator set for call with no FMF");
4503 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4504 return error(
"Explicit call type is not a function type");
4507 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4508 return error(
"Invalid record");
4512 return error(
"Callee is not a pointer type");
4516 return error(
"Callee is not of pointer to function type");
4518 return error(
"Explicit call type does not match pointee type of " 4521 return error(
"Insufficient operands to call");
4525 for (
unsigned i = 0, e = FTy->
getNumParams(); i != e; ++i, ++OpNum) {
4527 Args.
push_back(getBasicBlock(Record[OpNum]));
4529 Args.
push_back(getValue(Record, OpNum, NextValueNo,
4532 return error(
"Invalid record");
4537 if (OpNum != Record.
size())
4538 return error(
"Invalid record");
4540 while (OpNum != Record.
size()) {
4542 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4543 return error(
"Invalid record");
4549 OperandBundles.clear();
4550 InstructionList.push_back(I);
4551 cast<CallInst>(
I)->setCallingConv(
4560 cast<CallInst>(
I)->setTailCallKind(TCK);
4561 cast<CallInst>(
I)->setAttributes(PAL);
4563 if (!isa<FPMathOperator>(I))
4564 return error(
"Fast-math-flags specified for call without " 4565 "floating-point scalar or vector return type");
4571 if (Record.
size() < 3)
4572 return error(
"Invalid record");
4573 Type *OpTy = getTypeByID(Record[0]);
4574 Value *
Op = getValue(Record, 1, NextValueNo, OpTy);
4575 Type *ResTy = getTypeByID(Record[2]);
4576 if (!OpTy || !Op || !ResTy)
4577 return error(
"Invalid record");
4579 InstructionList.push_back(I);
4588 if (Record.
size() < 1 || Record[0] >= BundleTags.
size())
4589 return error(
"Invalid record");
4591 std::vector<Value *> Inputs;
4594 while (OpNum != Record.
size()) {
4596 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4597 return error(
"Invalid record");
4598 Inputs.push_back(Op);
4601 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4610 return error(
"Invalid instruction with no BB");
4612 if (!OperandBundles.empty()) {
4614 return error(
"Operand bundles found with no consumer");
4619 if (isa<TerminatorInst>(I)) {
4621 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
4626 ValueList.assignValue(I, NextValueNo++);
4631 if (!OperandBundles.empty())
4632 return error(
"Operand bundles found with no consumer");
4635 if (
Argument *A = dyn_cast<Argument>(ValueList.back())) {
4636 if (!A->getParent()) {
4638 for (
unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4639 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4644 return error(
"Never resolved value found in function");
4649 if (MDLoader->hasFwdRefs())
4650 return error(
"Invalid function metadata: outgoing forward refs");
4653 ValueList.shrinkTo(ModuleValueListSize);
4654 MDLoader->shrinkTo(ModuleMDLoaderSize);
4655 std::vector<BasicBlock*>().
swap(FunctionBBs);
4660 Error BitcodeReader::findFunctionInStream(
4663 while (DeferredFunctionInfoIterator->second == 0) {
4671 if (
Error Err = rememberAndSkipFunctionBodies())
4677 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
4680 if (Val >= SSIDs.size())
4696 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
4699 if (DFII->second == 0)
4700 if (
Error Err = findFunctionInStream(F, DFII))
4704 if (
Error Err = materializeMetadata())
4710 if (
Error Err = parseFunctionBody(F))
4718 for (
auto &
I : UpgradedIntrinsics) {
4719 for (
auto UI =
I.first->materialized_user_begin(), UE =
I.first->user_end();
4723 if (
CallInst *CI = dyn_cast<CallInst>(U))
4729 for (
auto &
I : RemangledIntrinsics)
4730 for (
auto UI =
I.first->materialized_user_begin(), UE =
I.first->user_end();
4740 if (!MDLoader->isStrippingTBAA()) {
4743 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(
I, TBAA))
4745 MDLoader->setStripTBAA(
true);
4752 return materializeForwardReferencedFunctions();
4755 Error BitcodeReader::materializeModule() {
4756 if (
Error Err = materializeMetadata())
4760 WillMaterializeAllForwardRefs =
true;
4765 if (
Error Err = materialize(&F))
4771 if (LastFunctionBlockBit || NextUnreadBit)
4773 ? LastFunctionBlockBit
4779 if (!BasicBlockFwdRefs.empty())
4780 return error(
"Never resolved function from blockaddress");
4786 for (
auto &
I : UpgradedIntrinsics) {
4787 for (
auto *U :
I.first->users()) {
4788 if (
CallInst *CI = dyn_cast<CallInst>(U))
4791 if (!
I.first->use_empty())
4792 I.first->replaceAllUsesWith(
I.second);
4793 I.first->eraseFromParent();
4795 UpgradedIntrinsics.clear();
4797 for (
auto &
I : RemangledIntrinsics) {
4798 I.first->replaceAllUsesWith(
I.second);
4799 I.first->eraseFromParent();
4801 RemangledIntrinsics.clear();
4812 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
4813 return IdentifiedStructTypes;
4816 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4818 StringRef ModulePath,
unsigned ModuleId)
4819 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4820 ModulePath(ModulePath), ModuleId(ModuleId) {}
4822 void ModuleSummaryIndexBitcodeReader::addThisModule() {
4823 TheIndex.
addModule(ModulePath, ModuleId);
4827 ModuleSummaryIndexBitcodeReader::getThisModule() {
4831 std::pair<ValueInfo, GlobalValue::GUID>
4832 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
4833 auto VGI = ValueIdToValueInfoMap[ValueId];
4838 void ModuleSummaryIndexBitcodeReader::setValueGUID(
4841 std::string GlobalId =
4844 auto OriginalNameID = ValueGUID;
4848 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is " 4849 << ValueName <<
"\n";
4854 ValueIdToValueInfoMap[ValueID] = std::make_pair(
4857 UseStrtab ? ValueName : TheIndex.
saveString(ValueName.str())),
4864 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
4871 assert(Offset > 0 &&
"Expected non-zero VST offset");
4875 return error(
"Invalid record");
4885 switch (Entry.
Kind) {
4888 return error(
"Malformed block");
4905 return error(
"Invalid record");
4906 unsigned ValueID = Record[0];
4908 auto VLI = ValueIdToLinkageMap.
find(ValueID);
4909 assert(VLI != ValueIdToLinkageMap.
end() &&
4910 "No linkage found for VST entry?");
4911 auto Linkage = VLI->second;
4912 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4919 return error(
"Invalid record");
4920 unsigned ValueID = Record[0];
4922 auto VLI = ValueIdToLinkageMap.
find(ValueID);
4923 assert(VLI != ValueIdToLinkageMap.
end() &&
4924 "No linkage found for VST entry?");
4925 auto Linkage = VLI->second;
4926 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4932 unsigned ValueID = Record[0];
4936 ValueIdToValueInfoMap[ValueID] =
4949 return error(
"Invalid record");
4953 unsigned ValueId = 0;
4959 switch (Entry.
Kind) {
4961 return error(
"Malformed block");
4969 return error(
"Invalid record");
4973 if (readBlockInfo())
4974 return error(
"Malformed block");
4979 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4980 !SeenGlobalValSummary) &&
4981 "Expected early VST parse via VSTOffset record");
4983 return error(
"Invalid record");
4988 if (!SourceFileName.
empty())
4990 assert(!SeenValueSymbolTable &&
4991 "Already read VST when parsing summary block?");
4996 if (VSTOffset > 0) {
4997 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4999 SeenValueSymbolTable =
true;
5001 SeenGlobalValSummary =
true;
5002 if (
Error Err = parseEntireSummary(Entry.
ID))
5006 if (
Error Err = parseModuleStringTable())
5019 if (
Error Err = parseVersionRecord(Record).takeError())
5027 return error(
"Invalid record");
5028 SourceFileName = ValueName.
c_str();
5033 if (Record.
size() != 5)
5034 return error(
"Invalid hash length " +
Twine(Record.
size()).str());
5035 auto &Hash = getThisModule()->second.second;
5037 for (
auto &Val : Record) {
5038 assert(!(Val >> 32) &&
"Unexpected high bits set");
5045 if (Record.
size() < 1)
5046 return error(
"Invalid record");
5050 VSTOffset = Record[0] - 1;
5061 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5062 if (GVRecord.
size() <= 3)
5063 return error(
"Invalid record");
5064 uint64_t RawLinkage = GVRecord[3];
5067 ValueIdToLinkageMap[ValueId++] = Linkage;
5071 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5081 std::vector<ValueInfo>
5083 std::vector<ValueInfo>
Ret;
5084 Ret.reserve(Record.
size());
5085 for (uint64_t RefValueId : Record)
5086 Ret.push_back(getValueInfoFromValueId(RefValueId).
first);
5090 std::vector<FunctionSummary::EdgeTy>
5092 bool IsOldProfileFormat,
5093 bool HasProfile,
bool HasRelBF) {
5094 std::vector<FunctionSummary::EdgeTy>
Ret;
5095 Ret.reserve(Record.
size());
5096 for (
unsigned I = 0,
E = Record.
size();
I !=
E; ++
I) {
5100 if (IsOldProfileFormat) {
5104 }
else if (HasProfile)
5107 RelBF = Record[++
I];
5116 uint64_t ArgNum = Record[Slot++];
5123 B.
Info = Record[Slot++];
5124 B.
Byte = Record[Slot++];
5125 B.
Bit = Record[Slot++];
5131 uint64_t
Id = Record[Slot++];
5136 static_cast<size_t>(Record[Slot + 1])};
5139 uint64_t ResByArgNum = Record[Slot++];
5140 for (uint64_t
I = 0;
I != ResByArgNum; ++
I)
5149 {Strtab.
data() + Record[Slot],
static_cast<size_t>(Record[Slot + 1])});
5159 while (Slot < Record.
size())
5165 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
5167 return error(
"Invalid record");
5174 return error(
"Invalid Summary Block: record for version expected");
5176 return error(
"Invalid Summary Block: version expected");
5178 const uint64_t
Version = Record[0];
5179 const bool IsOldProfileFormat = Version == 1;
5180 if (Version < 1 || Version > 4)
5181 return error(
"Invalid summary version " +
Twine(Version) +
5182 ", 1, 2, 3 or 4 expected");
5193 std::vector<GlobalValue::GUID> PendingTypeTests;
5194 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5195 PendingTypeCheckedLoadVCalls;
5196 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5197 PendingTypeCheckedLoadConstVCalls;
5202 switch (Entry.
Kind) {
5205 return error(
"Malformed block");
5226 uint64_t Flags = Record[0];
5228 assert(Flags <= 0x3 &&
"Unexpected bits in flag");
5239 uint64_t ValueID = Record[0];
5241 ValueIdToValueInfoMap[ValueID] =
5256 unsigned ValueID = Record[0];
5257 uint64_t RawFlags = Record[1];
5258 unsigned InstCount = Record[2];
5259 uint64_t RawFunFlags = 0;
5260 unsigned NumRefs = Record[3];
5261 int RefListStartIndex = 4;
5263 RawFunFlags = Record[3];
5264 NumRefs = Record[4];
5265 RefListStartIndex = 5;
5274 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5275 assert(Record.
size() >= RefListStartIndex + NumRefs &&
5276 "Record size inconsistent with number of references");
5277 std::vector<ValueInfo> Refs = makeRefList(
5281 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5283 IsOldProfileFormat, HasProfile, HasRelBF);
5284 auto FS = llvm::make_unique<FunctionSummary>(
5286 std::move(Calls), std::move(PendingTypeTests),
5287 std::move(PendingTypeTestAssumeVCalls),
5288 std::move(PendingTypeCheckedLoadVCalls),
5289 std::move(PendingTypeTestAssumeConstVCalls),
5290 std::move(PendingTypeCheckedLoadConstVCalls));
5291 PendingTypeTests.clear();
5292 PendingTypeTestAssumeVCalls.clear();
5293 PendingTypeCheckedLoadVCalls.clear();
5294 PendingTypeTestAssumeConstVCalls.clear();
5295 PendingTypeCheckedLoadConstVCalls.clear();
5296 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
5297 FS->setModulePath(getThisModule()->
first());
5298 FS->setOriginalName(VIAndOriginalGUID.second);
5306 unsigned ValueID = Record[0];
5307 uint64_t RawFlags = Record[1];
5308 unsigned AliaseeID = Record[2];
5310 auto AS = llvm::make_unique<AliasSummary>(Flags);
5316 AS->setModulePath(getThisModule()->
first());
5319 getValueInfoFromValueId(AliaseeID).first.getGUID();
5320 auto AliaseeInModule =
5322 if (!AliaseeInModule)
5323 return error(
"Alias expects aliasee summary to be parsed");
5324 AS->setAliasee(AliaseeInModule);
5325 AS->setAliaseeGUID(AliaseeGUID);
5327 auto GUID = getValueInfoFromValueId(ValueID);
5328 AS->setOriginalName(GUID.second);
5334 unsigned ValueID = Record[0];
5335 uint64_t RawFlags = Record[1];
5337 std::vector<ValueInfo> Refs =
5339 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5340 FS->setModulePath(getThisModule()->
first());
5341 auto GUID = getValueInfoFromValueId(ValueID);
5342 FS->setOriginalName(GUID.second);
5352 unsigned ValueID = Record[0];
5353 uint64_t ModuleId = Record[1];
5354 uint64_t RawFlags = Record[2];
5355 unsigned InstCount = Record[3];
5356 uint64_t RawFunFlags = 0;
5357 unsigned NumRefs = Record[4];
5358 int RefListStartIndex = 5;
5361 RawFunFlags = Record[4];
5362 NumRefs = Record[5];
5363 RefListStartIndex = 6;
5367 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5368 assert(Record.
size() >= RefListStartIndex + NumRefs &&
5369 "Record size inconsistent with number of references");
5370 std::vector<ValueInfo> Refs = makeRefList(
5373 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5375 IsOldProfileFormat, HasProfile,
false);
5376 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5377 auto FS = llvm::make_unique<FunctionSummary>(
5379 std::move(Edges), std::move(PendingTypeTests),
5380 std::move(PendingTypeTestAssumeVCalls),
5381 std::move(PendingTypeCheckedLoadVCalls),
5382 std::move(PendingTypeTestAssumeConstVCalls),
5383 std::move(PendingTypeCheckedLoadConstVCalls));
5384 PendingTypeTests.clear();
5385 PendingTypeTestAssumeVCalls.clear();
5386 PendingTypeCheckedLoadVCalls.clear();
5387 PendingTypeTestAssumeConstVCalls.clear();
5388 PendingTypeCheckedLoadConstVCalls.clear();
5389 LastSeenSummary = FS.get();
5391 FS->setModulePath(ModuleIdMap[ModuleId]);
5399 unsigned ValueID = Record[0];
5400 uint64_t ModuleId = Record[1];
5401 uint64_t RawFlags = Record[2];
5402 unsigned AliaseeValueId = Record[3];
5404 auto AS = llvm::make_unique<AliasSummary>(Flags);
5405 LastSeenSummary =
AS.get();
5406 AS->setModulePath(ModuleIdMap[ModuleId]);
5409 getValueInfoFromValueId(AliaseeValueId).first.getGUID();
5410 auto AliaseeInModule =
5412 AS->setAliasee(AliaseeInModule);
5413 AS->setAliaseeGUID(AliaseeGUID);
5415 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5422 unsigned ValueID = Record[0];
5423 uint64_t ModuleId = Record[1];
5424 uint64_t RawFlags = Record[2];
5426 std::vector<ValueInfo> Refs =
5428 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5429 LastSeenSummary = FS.get();
5431 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5438 uint64_t OriginalName = Record[0];
5439 if (!LastSeenSummary)
5440 return error(
"Name attachment that does not follow a combined record");
5444 LastSeenSummary =
nullptr;
5449 assert(PendingTypeTests.empty());
5450 PendingTypeTests.insert(PendingTypeTests.end(), Record.
begin(),
5455 assert(PendingTypeTestAssumeVCalls.empty());
5456 for (
unsigned I = 0;
I != Record.
size();
I += 2)
5457 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5461 assert(PendingTypeCheckedLoadVCalls.empty());
5462 for (
unsigned I = 0;
I != Record.
size();
I += 2)
5463 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5467 PendingTypeTestAssumeConstVCalls.push_back(
5468 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5472 PendingTypeCheckedLoadConstVCalls.push_back(
5473 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5478 for (
unsigned I = 0;
I != Record.
size();
I += 2)
5479 CfiFunctionDefs.insert(
5480 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5486 for (
unsigned I = 0;
I != Record.
size();
I += 2)
5487 CfiFunctionDecls.insert(
5488 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
5502 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5504 return error(
"Invalid record");
5514 switch (Entry.
Kind) {
5517 return error(
"Malformed block");
5531 uint64_t ModuleId = Record[0];
5534 return error(
"Invalid record");
5536 LastSeenModule = TheIndex.
addModule(ModulePath, ModuleId);
5537 ModuleIdMap[ModuleId] = LastSeenModule->
first();
5544 if (Record.
size() != 5)
5545 return error(
"Invalid hash length " +
Twine(Record.
size()).str());
5546 if (!LastSeenModule)
5547 return error(
"Invalid hash that does not follow a module path");
5549 for (
auto &Val : Record) {
5550 assert(!(Val >> 32) &&
"Unexpected high bits set");
5551 LastSeenModule->
second.second[Pos++] = Val;
5554 LastSeenModule =
nullptr;
5568 const char *
name()
const noexcept
override {
5569 return "llvm.bitcode";
5572 std::string message(
int IE)
const override {
5576 return "Corrupted bitcode";
5591 unsigned Block,
unsigned RecordID) {
5593 return error(
"Invalid record");
5598 switch (Entry.
Kind) {
5603 return error(
"Malformed block");
5607 return error(
"Malformed block");
5613 if (Stream.
readRecord(Entry.
ID, Record, &Blob) == RecordID)
5628 return FOrErr.takeError();
5629 return std::move(FOrErr->Mods);
5650 switch (Entry.
Kind) {
5653 return error(
"Malformed block");
5656 uint64_t IdentificationBit = -1ull;
5660 return error(
"Malformed block");
5665 return error(
"Malformed block");
5671 return error(
"Malformed block");
5689 for (
auto I = F.
Mods.rbegin(),
E = F.
Mods.rend();
I !=
E; ++
I) {
5690 if (!
I->Strtab.empty())
5692 I->Strtab = *Strtab;
5720 return error(
"Malformed block");
5739 BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
5740 bool ShouldLazyLoadMetadata,
bool IsImporting) {
5743 std::string ProducerIdentification;
5744 if (IdentificationBit != -1ull) {
5748 if (!ProducerIdentificationOrErr)
5749 return ProducerIdentificationOrErr.
takeError();
5751 ProducerIdentification = *ProducerIdentificationOrErr;
5755 auto *R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5758 std::unique_ptr<Module> M =
5759 llvm::make_unique<Module>(ModuleIdentifier,
Context);
5764 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5765 return std::move(Err);
5767 if (MaterializeAll) {
5769 if (
Error Err = M->materializeAll())
5770 return std::move(Err);
5773 if (
Error Err = R->materializeForwardReferencedFunctions())
5774 return std::move(Err);
5776 return std::move(M);
5782 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting);
5790 StringRef ModulePath, uint64_t ModuleId) {
5794 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
5795 ModulePath, ModuleId);
5796 return R.parseModule();
5804 auto Index = llvm::make_unique<ModuleSummaryIndex>(
false);
5805 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *
Index,
5806 ModuleIdentifier, 0);
5808 if (
Error Err = R.parseModule())
5809 return std::move(Err);
5811 return std::move(
Index);
5820 return error(
"Invalid record");
5825 switch (Entry.
Kind) {
5827 return error(
"Malformed block");
5840 return error(
"Malformed block");
5855 if (MsOrErr->size() != 1)
5856 return error(
"Expected a single module");
5858 return (*MsOrErr)[0];
5863 bool ShouldLazyLoadMetadata,
bool IsImporting) {
5868 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5872 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
5873 bool ShouldLazyLoadMetadata,
bool IsImporting) {
5877 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5883 return getModuleImpl(Context,
true,
false,
false);
5894 return BM->parseModule(Context);
5923 uint64_t ModuleId) {
5928 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
5937 return BM->getSummary();
5945 return BM->getLTOInfo();
5950 bool IgnoreEmptyThinLTOIndexFile) {
5955 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
void setVisibility(VisibilityTypes V)
static AtomicOrdering getDecodedOrdering(unsigned Val)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static const fltSemantics & IEEEquad() LLVM_READNONE
Synchronized with respect to signal handlers executing in the same thread.
void sortUseList(Compare Cmp)
Sort the use-list.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Tracking metadata reference owned by Metadata.
static APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
Maximum number of bits that can be specified.
ArrayRef< Type * > subtypes() const
Represents either an error or a value T.
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
static bool isConstant(const MachineInstr &MI)
static Type * getDoubleTy(LLVMContext &C)
static IntegerType * getInt1Ty(LLVMContext &C)
bool hasLocalLinkage() const
DILocation * get() const
Get the underlying DILocation.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Special purpose, only applies to global arrays.
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
*p = old <signed v ? old : v
This class represents an incoming formal argument to a Function.
void setFast(bool B=true)
static bool hasValidBitcodeHeader(BitstreamCursor &Stream)
Helper to read the header common to all bitcode files.
bool supportsCOMDAT() const
Tests whether the target supports comdat.
Atomic ordering constants.
bool isMetadataTy() const
Return true if this is 'metadata'.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Compute iterated dominance frontiers using a linear time algorithm.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
Type * getParamType(unsigned i) const
Parameter type accessors.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
Minimum number of bits that can be specified.
The highest possible calling convention ID. Must be some 2^k - 1.
static Expected< std::string > readTriple(BitstreamCursor &Stream)
A Module instance is used to store all the information related to an LLVM module. ...
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static ResumeInst * Create(Value *Exn, Instruction *InsertBefore=nullptr)
An instruction for ordering other memory operations.
Same, but only replaced by something equivalent.
GlobalValueSummary * findSummaryInModule(GlobalValue::GUID ValueGUID, StringRef ModuleId) const
Find the summary for global GUID in module ModuleId, or nullptr if not found.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
bool UpgradeRetainReleaseMarker(Module &M)
This checks for objc retain release marker which should be upgraded.
Available for inspection, not emission.
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
bool isFP128Ty() const
Return true if this is 'fp128'.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void setMaterializer(GVMaterializer *GVM)
Sets the GVMaterializer to GVM.
void addOperand(MDNode *M)
Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, uint64_t ModuleId)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
This class represents a function call, abstracting a target machine's calling convention.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID...
void setGC(std::string Str)
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
The two locations do not alias at all.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
*p = old <unsigned v ? old : v
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
uint64_t Info
Additional information for the resolution:
Like Internal, but omit from symbol table.
Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
void UpgradeInlineAsmString(std::string *AsmStr)
Upgrade comment in call to inline asm that represents an objc retain release marker.
*p = old >unsigned v ? old : v
virtual std::string message() const
Return the error message as a string.
This instruction constructs a fixed permutation of two input vectors.
const BasicBlock & back() const
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
Externally visible function.
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper...
void deleteValue()
Delete a pointer to a generic Value.
The data referenced by the COMDAT must be the same size.
static uint64_t jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
void setNoInfs(bool B=true)
AttrBuilder & addDereferenceableAttr(uint64_t Bytes)
This turns the number of dereferenceable bytes into the form used internally in Attribute.
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
bool stripDebugInfo(Function &F)
static bool isLoadableOrStorableType(Type *ElemTy)
Return true if we can load or store from a pointer to this type.
An instruction for reading from memory.
ELFYAML::ELF_STV Visibility
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
bool hasExternalWeakLinkage() const
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
static Type * getMetadataTy(LLVMContext &C)
Kind
Specifies which kind of type check we should emit for this byte array.
bool isVectorTy() const
True if this is an instance of VectorType.
Error takeError()
Take ownership of the stored error.
static bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
void UpgradeIntrinsicCall(CallInst *CI, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
void setAlignment(unsigned Align)
Base class for error info classes.
static Type * getX86_MMXTy(LLVMContext &C)
static bool convertToString(ArrayRef< uint64_t > Record, unsigned Idx, StrTy &Result)
Convert a string from a record into an std::string, return true on failure.
void setBlockInfo(BitstreamBlockInfo *BI)
Set the block info to be used by this BitstreamCursor to interpret abbreviated records.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
*p = old >signed v ? old : v
word_t Read(unsigned NumBits)
StringRef StrtabForSymtab
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair...
static Type * getX86_FP80Ty(LLVMContext &C)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
static bool isLocalLinkage(LinkageTypes Linkage)
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Value * getValueFwdRef(unsigned Idx, Type *Ty)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
bool canSkipToPos(size_t pos) const
void setIndirectSymbol(Constant *Symbol)
These methods set and retrieve indirect symbol.
static void inferDSOLocal(GlobalValue *GV)
unsigned getAllocaAddrSpace() const
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
GlobalValue::GUID getGUID() const
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
static Type * getTokenTy(LLVMContext &C)
Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
AttrBuilder & addDereferenceableOrNullAttr(uint64_t Bytes)
This turns the number of dereferenceable_or_null bytes into the form used internally in Attribute...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
static Type * getFloatTy(LLVMContext &C)
Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO, and whether it has a summary.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
uint64_t getArrayNumElements() const
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
static bool getDecodedDSOLocal(unsigned Val)
bool isIntegerTy() const
True if this is an instance of IntegerType.
void setThreadLocalMode(ThreadLocalMode Val)
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
void setSkipModuleByDistributedBackend()
std::error_code make_error_code(BitcodeError E)
This file contains the simple types necessary to represent the attributes associated with functions a...
No attributes have been set.
The linker may choose any COMDAT.
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
void setName(const Twine &Name)
Change the name of the value.
Tagged union holding either a T or a Error.
uint64_t getNumElements() const
static Type * getPPC_FP128Ty(LLVMContext &C)
void setDLLStorageClass(DLLStorageClassTypes C)
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
This file implements a class to represent arbitrary precision integral constant values and operations...
void setWithGlobalValueDeadStripping()
AtomicOrdering
Atomic ordering for LLVM's memory model.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
StringRef str() const
Explicit conversion to StringRef.
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
AttributeList getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
llvm::Optional< Function * > remangleIntrinsicFunction(Function *F)
Class to represent function types.
static Type * getLabelTy(LLVMContext &C)
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
Type * getType() const
All values are typed, get the type of this value.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Class to represent array types.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
Basic information extracted from a bitcode module to be used for LTO.
This instruction compares its operands according to the predicate given to the constructor.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
void setComdat(Comdat *C)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
static cl::opt< bool > PrintSummaryGUIDs("print-summary-global-ids", cl::init(false), cl::Hidden, cl::desc("Print the global id for each value when reading the module summary"))
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
This accessor should only be used when exporting because it can mutate the map.
bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn)
This is a more granular function that simply checks an intrinsic function for upgrading, and returns true if it requires upgrading.
An instruction for storing to memory.
ArrayRef< uint8_t > getBitcodeBytes() const
bool hasPersonalityFn() const
Check whether this function has a personality function.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
static const fltSemantics & IEEEdouble() LLVM_READNONE
BitstreamEntry advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
void setBody(ArrayRef< Type *> Elements, bool isPacked=false)
Specify a body for an opaque identified type.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
AttrBuilder & addAllocSizeAttrFromRawRepr(uint64_t RawAllocSizeRepr)
Add an allocsize attribute, using the representation returned by Attribute.getIntValue().
amdgpu Simplify well known AMD library false Value * Callee
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
void setIsMaterializable(bool V)
const std::error_category & BitcodeErrorCategory()
Class to represent pointers.
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
iterator find(const_arg_type_t< KeyT > Val)
bool isVoidTy() const
Return true if this is 'void'.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
ExternalWeak linkage description.
Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information...
void setCallingConv(CallingConv::ID CC)
Same, but only replaced by something equivalent.
initializer< Ty > init(const Ty &Val)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
No other Module may specify this COMDAT.
bool isLabelTy() const
Return true if this is 'label'.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void setNoSignedZeros(bool B=true)
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
uint64_t getCurrentByteNo() const
size_t getBufferSize() const
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
This is an important class for using LLVM in a threaded context.
static Constant * getFP(LLVMContext &Context, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant with array type with an element count and element type of fl...
PowerPC Reduce CR logical Operation
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
size_t size() const
size - Get the array size.
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
static bool hasImplicitComdat(size_t Val)
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
bool isPointerTy() const
True if this is an instance of PointerType.
Indirect Branch Instruction.
static Constant * getFP(LLVMContext &Context, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant with vector type with an element count and element type of f...
std::error_code getError() const
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
Class to accumulate and hold information about a callee.
iterator_range< use_iterator > materialized_uses()
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
static Constant * getShuffleVector(Constant *V1, Constant *V2, Constant *Mask, Type *OnlyIfReducedTy=nullptr)
static ManagedStatic< _object_error_category > error_category
This file declares a class to represent arbitrary precision floating point values and provide a varie...
static Type * getVoidTy(LLVMContext &C)
const Instruction & back() const
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
DLLStorageClassTypes
Storage classes of global values for PE targets.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Error error(const Twine &Message)
static Constant * get(StructType *T, ArrayRef< Constant *> V)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex, uint64_t ModuleId)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
static const fltSemantics & x87DoubleExtended() LLVM_READNONE
bool isMaterializable() const
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
The data referenced by the COMDAT must be the same.
Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
Sentinal value useful for loops.
Function and variable summary information to aid decisions and implementation of importing.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
void JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static Attribute::AttrKind parseAttrKind(StringRef Kind)
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
bool SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block...
static wasm::ValType getType(const TargetRegisterClass *RC)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, Instruction *InsertBefore=nullptr)
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
Triple - Helper class for working with autoconf configuration names.
static Type * getFP128Ty(LLVMContext &C)
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
Struct that holds a reference to a particular GUID in a global value summary.
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success...
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
static Type * getHalfTy(LLVMContext &C)
const InstListType & getInstList() const
Return the underlying instruction list container.
StringRef saveString(std::string String)
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
static const fltSemantics & IEEEsingle() LLVM_READNONE
Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
static ErrorSuccess success()
Create a success value.
ModuleInfo * addModule(StringRef ModPath, uint64_t ModId, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
Iterator for intrusive lists based on ilist_node.
Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it...
static const unsigned MaxAlignmentExponent
The maximum alignment for instructions.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
This is the shared class of boolean and integer constants.
void setSelectionKind(SelectionKind Val)
static void parseWholeProgramDevirtResolutionByArg(ArrayRef< uint64_t > Record, size_t &Slot, WholeProgramDevirtResolution &Wpd)
static const fltSemantics & IEEEhalf() LLVM_READNONE
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value *> Args=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
static Expected< std::string > readIdentificationBlock(BitstreamCursor &Stream)
Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the "epoch" encoded in the bit...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Keep one copy of function when linking (inline)
Module.h This file contains the declarations for the Module class.
bool UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
unsigned readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
void setApproxFunc(bool B=true)
This class maintains the abbreviations read from a block info block.
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
reference get()
Returns a reference to the stored T value.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
The linker will choose the largest COMDAT.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setLinkage(LinkageTypes LT)
std::string SingleImplName
enum llvm::TypeTestResolution::Kind TheKind
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
void setNoNaNs(bool B=true)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class to represent vector types.
unsigned skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found...
Class for arbitrary precision integers.
static int getDecodedCastOpcode(unsigned Val)
void push_back(pointer val)
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
LinkageTypes
An enumeration for the kinds of linkage for global values.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
StringRef getBufferIdentifier() const
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Optional< BitstreamBlockInfo > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
void setAttributes(AttributeSet A)
Set attribute list for this global.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value *> Args, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static const fltSemantics & PPCDoubleDouble() LLVM_READNONE
std::set< std::string > & cfiFunctionDefs()
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
enum llvm::BitstreamEntry::@140 Kind
static Expected< bool > hasObjCCategoryInModule(BitstreamCursor &Stream)
Function to be accessible from DLL.
Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val)
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument, "this"), where the key is the argument vector.
ValID - Represents a reference of a definition of some sort with no type.
pointer data()
Return a pointer to the vector's buffer, even if empty().
void setUnnamedAddr(UnnamedAddr Val)
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
static IntegerType * getInt32Ty(LLVMContext &C)
bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true if the block has an error...
LLVM_NODISCARD bool empty() const
void setAllowContract(bool B=true)
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
StringRef getName() const
Return a constant reference to the value's name.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
Keep one copy of named function when linking (weak)
Rename collisions when linking (static functions).
void setAllowReciprocal(bool B=true)
Function attribute flags.
StringMapEntry< Value * > ValueName
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
void setModulePath(StringRef ModPath)
Set the path to the module containing this function, for use in the combined index.
Function to be imported from DLL.
std::string str() const
Return the twine contents as a std::string.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
void addDestination(BasicBlock *Dest)
Add a destination.
Provides ErrorOr<T> smart pointer.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Synchronized with respect to all concurrently executing threads.
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful...
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::set< std::string > & cfiFunctionDecls()
static void stripTBAA(Module *M)
const char * getBufferStart() const
std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore=nullptr)
Module * getParent()
Get the module that this global value is contained inside of...
Verify that the TBAA Metadatas are valid.
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Lightweight error class with error context and mandatory checking.
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, Instruction *InsertBefore=nullptr)
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
AttributeSet getFnAttributes() const
The function attributes are returned.
AttrBuilder & addStackAlignmentAttr(unsigned Align)
This turns an int stack alignment (which must be a power of 2) into the form used internally in Attri...
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
bool hasDefaultVisibility() const
Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting)
Read the bitcode module and prepare for lazy deserialization of function bodies.
Type * getElementType() const
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context)
Read the entire bitcode module and return it.
BitstreamEntry advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
inst_range instructions(Function *F)
static ManagedStatic< BitcodeErrorCategoryType > ErrorCategory
AttrBuilder & addAlignmentAttr(unsigned Align)
This turns an int alignment (which must be a power of 2) into the form used internally in Attribute...
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
void setPersonalityFn(Constant *Fn)
Value * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
static Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
Decode the flags for GlobalValue in the summary.
void setAllowReassoc(bool B=true)
Flag setters.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
unsigned ReturnDoesNotAlias
void setSection(StringRef S)
Change the section for this global.
void setCalledFunction(Value *V)
Set the callee to the specified value.
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static Constant * get(ArrayRef< Constant *> V)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Type * getElementType() const
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
iterator_range< arg_iterator > args()
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
std::vector< BitcodeModule > Mods
bool isStructTy() const
True if this is an instance of StructType.
bool empty() const
empty - Check if the array is empty.
bool isArrayTy() const
True if this is an instance of ArrayType.
an instruction to allocate memory on the stack
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results...
static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags)
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)