24#include "llvm/Config/llvm-config.h"
54#include "llvm/IR/IntrinsicsAArch64.h"
55#include "llvm/IR/IntrinsicsARM.h"
87#include <system_error>
97 "Print the global id for each value when reading the module summary"));
102 "Expand constant expressions to instructions for testing purposes"));
107 SWITCH_INST_MAGIC = 0x4B5
120 "file too small to contain bitcode header");
121 for (
unsigned C : {
'B',
'C'})
125 "file doesn't start with bitcode header");
127 return Res.takeError();
128 for (
unsigned C : {0x0, 0xC, 0xE, 0xD})
132 "file doesn't start with bitcode header");
134 return Res.takeError();
139 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
140 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
143 return error(
"Invalid bitcode signature");
149 return error(
"Invalid bitcode wrapper header");
153 return std::move(Err);
155 return std::move(Stream);
159template <
typename StrTy>
172 if (
F.isMaterializable())
175 I.setMetadata(LLVMContext::MD_tbaa,
nullptr);
183 return std::move(Err);
188 std::string ProducerIdentification;
195 switch (Entry.Kind) {
198 return error(
"Malformed block");
200 return ProducerIdentification;
211 switch (MaybeBitCode.
get()) {
213 return error(
"Invalid value");
221 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
240 switch (Entry.Kind) {
243 return error(
"Malformed block");
251 return std::move(Err);
263 return std::move(Err);
274 switch (Entry.Kind) {
277 return error(
"Malformed block");
289 switch (MaybeRecord.
get()) {
295 return error(
"Invalid section name record");
300 Segment = Segment.trim();
301 Section = Section.trim();
303 if (Segment ==
"__DATA" && Section.starts_with(
"__objc_catlist"))
305 if (Segment ==
"__OBJC" && Section.starts_with(
"__category"))
307 if (Segment ==
"__TEXT" && Section.starts_with(
"__swift"))
325 switch (Entry.Kind) {
327 return error(
"Malformed block");
337 return std::move(Err);
350 return std::move(Err);
363 switch (Entry.Kind) {
366 return error(
"Malformed block");
378 switch (MaybeRecord.
get()) {
383 return error(
"Invalid triple record");
402 switch (Entry.Kind) {
404 return error(
"Malformed block");
414 return std::move(Err);
421 return Skipped.takeError();
428class BitcodeReaderBase {
430 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
431 : Stream(std::
move(Stream)), Strtab(Strtab) {
432 this->Stream.setBlockInfo(&BlockInfo);
435 BitstreamBlockInfo BlockInfo;
436 BitstreamCursor Stream;
441 bool UseStrtab =
false;
443 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
448 std::pair<StringRef, ArrayRef<uint64_t>>
449 readNameFromStrtab(ArrayRef<uint64_t> Record);
451 Error readBlockInfo();
454 std::string ProducerIdentification;
461Error BitcodeReaderBase::error(
const Twine &Message) {
462 std::string FullMsg = Message.
str();
463 if (!ProducerIdentification.empty())
464 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
465 LLVM_VERSION_STRING
"')";
466 return ::error(FullMsg);
470BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
472 return error(
"Invalid version record");
473 unsigned ModuleVersion =
Record[0];
474 if (ModuleVersion > 2)
475 return error(
"Invalid value");
476 UseStrtab = ModuleVersion >= 2;
477 return ModuleVersion;
480std::pair<StringRef, ArrayRef<uint64_t>>
481BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
485 if (Record[0] + Record[1] > Strtab.
size())
487 return {StringRef(Strtab.
data() + Record[0], Record[1]),
Record.slice(2)};
498class BitcodeConstant final :
public Value,
499 TrailingObjects<BitcodeConstant, unsigned> {
500 friend TrailingObjects;
503 static constexpr uint8_t SubclassID = 255;
511 static constexpr uint8_t ConstantStructOpcode = 255;
512 static constexpr uint8_t ConstantArrayOpcode = 254;
513 static constexpr uint8_t ConstantVectorOpcode = 253;
514 static constexpr uint8_t NoCFIOpcode = 252;
515 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
516 static constexpr uint8_t BlockAddressOpcode = 250;
517 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
518 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
525 unsigned BlockAddressBB = 0;
526 Type *SrcElemTy =
nullptr;
527 std::optional<ConstantRange>
InRange;
529 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0,
Type *SrcElemTy =
nullptr,
530 std::optional<ConstantRange>
InRange = std::nullopt)
531 : Opcode(Opcode),
Flags(
Flags), SrcElemTy(SrcElemTy),
534 ExtraInfo(uint8_t Opcode, uint8_t Flags,
unsigned BlockAddressBB)
535 : Opcode(Opcode),
Flags(
Flags), BlockAddressBB(BlockAddressBB) {}
540 unsigned NumOperands;
541 unsigned BlockAddressBB;
543 std::optional<ConstantRange>
InRange;
546 BitcodeConstant(
Type *Ty,
const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
548 NumOperands(OpIDs.
size()), BlockAddressBB(
Info.BlockAddressBB),
553 BitcodeConstant &operator=(
const BitcodeConstant &) =
delete;
557 const ExtraInfo &Info,
558 ArrayRef<unsigned> OpIDs) {
559 void *Mem =
A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.
size()),
560 alignof(BitcodeConstant));
561 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
564 static bool classof(
const Value *V) {
return V->getValueID() == SubclassID; }
566 ArrayRef<unsigned> getOperandIDs()
const {
567 return ArrayRef(getTrailingObjects(), NumOperands);
570 std::optional<ConstantRange> getInRange()
const {
571 assert(Opcode == Instruction::GetElementPtr);
580class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
582 Module *TheModule =
nullptr;
584 uint64_t NextUnreadBit = 0;
586 uint64_t LastFunctionBlockBit = 0;
587 bool SeenValueSymbolTable =
false;
588 uint64_t VSTOffset = 0;
590 std::vector<std::string> SectionTable;
591 std::vector<std::string> GCTable;
593 std::vector<Type *> TypeList;
597 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
604 DenseMap<std::pair<Type *, unsigned>,
unsigned> VirtualTypeIDs;
605 DenseMap<Function *, unsigned> FunctionTypeIDs;
610 BitcodeReaderValueList ValueList;
611 std::optional<MetadataLoader> MDLoader;
612 std::vector<Comdat *> ComdatList;
613 DenseSet<GlobalObject *> ImplicitComdatObjects;
616 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
617 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
619 struct FunctionOperandInfo {
621 unsigned PersonalityFn;
625 std::vector<FunctionOperandInfo> FunctionOperands;
629 std::vector<AttributeList> MAttributes;
632 std::map<unsigned, AttributeList> MAttributeGroups;
636 std::vector<BasicBlock*> FunctionBBs;
640 std::vector<Function*> FunctionsWithBodies;
644 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
645 UpdatedIntrinsicMap UpgradedIntrinsics;
650 bool SeenFirstFunctionBody =
false;
654 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
659 std::vector<uint64_t> DeferredMetadataInfo;
664 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
665 std::deque<Function *> BasicBlockFwdRefQueue;
672 std::vector<Function *> BackwardRefFunctions;
680 bool UseRelativeIDs =
false;
684 bool WillMaterializeAllForwardRefs =
false;
688 bool SeenDebugIntrinsic =
false;
689 bool SeenDebugRecord =
false;
692 TBAAVerifier TBAAVerifyHelper;
694 std::vector<std::string> BundleTags;
697 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
700 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
701 StringRef ProducerIdentification, LLVMContext &
Context);
703 Error materializeForwardReferencedFunctions();
705 Error materialize(GlobalValue *GV)
override;
706 Error materializeModule()
override;
707 std::vector<StructType *> getIdentifiedStructTypes()
const override;
711 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
712 bool IsImporting, ParserCallbacks Callbacks = {});
714 static uint64_t decodeSignRotatedValue(uint64_t V);
717 Error materializeMetadata()
override;
719 void setStripDebugInfo()
override;
722 std::vector<StructType *> IdentifiedStructTypes;
723 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
724 StructType *createIdentifiedStructType(LLVMContext &
Context);
726 static constexpr unsigned InvalidTypeID = ~0
u;
728 Type *getTypeByID(
unsigned ID);
729 Type *getPtrElementTypeByID(
unsigned ID);
730 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
731 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
734 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
735 Expected<Constant *> getValueForInitializer(
unsigned ID);
737 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
738 BasicBlock *ConstExprInsertBB) {
745 return MDLoader->getMetadataFwdRefOrLoad(
ID);
749 if (
ID >= FunctionBBs.size())
return nullptr;
750 return FunctionBBs[
ID];
754 if (i-1 < MAttributes.size())
755 return MAttributes[i-1];
756 return AttributeList();
762 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
763 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
764 BasicBlock *ConstExprInsertBB) {
765 if (Slot ==
Record.size())
return true;
766 unsigned ValNo = (unsigned)Record[Slot++];
769 ValNo = InstNum - ValNo;
770 if (ValNo < InstNum) {
774 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
776 "Incorrect type ID stored for value");
777 return ResVal ==
nullptr;
779 if (Slot ==
Record.size())
782 TypeID = (unsigned)Record[Slot++];
783 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
785 return ResVal ==
nullptr;
788 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
789 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
790 BasicBlock *ConstExprInsertBB) {
791 if (Slot ==
Record.size())
796 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
799 if (Slot ==
Record.size())
801 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
809 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
810 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
811 BasicBlock *ConstExprInsertBB) {
812 if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
820 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
821 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
822 BasicBlock *ConstExprInsertBB) {
823 ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
824 return ResVal ==
nullptr;
829 Value *getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
830 unsigned InstNum,
Type *Ty,
unsigned TyID,
831 BasicBlock *ConstExprInsertBB) {
832 if (Slot ==
Record.size())
return nullptr;
833 unsigned ValNo = (unsigned)Record[Slot];
836 ValNo = InstNum - ValNo;
837 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
841 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
842 unsigned InstNum,
Type *Ty,
unsigned TyID,
843 BasicBlock *ConstExprInsertBB) {
844 if (Slot ==
Record.size())
return nullptr;
845 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
848 ValNo = InstNum - ValNo;
849 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
852 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
855 if (
Record.size() - OpNum < 2)
856 return error(
"Too few records for range");
858 unsigned LowerActiveWords =
Record[OpNum];
859 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
860 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
861 return error(
"Too few records for range");
864 OpNum += LowerActiveWords;
867 OpNum += UpperActiveWords;
870 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
871 int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
872 return ConstantRange(APInt(
BitWidth, Start,
true),
877 Expected<ConstantRange>
878 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
879 if (
Record.size() - OpNum < 1)
880 return error(
"Too few records for range");
882 return readConstantRange(Record, OpNum,
BitWidth);
888 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
893 Error parseAlignmentValue(uint64_t
Exponent, MaybeAlign &Alignment);
894 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
896 ParserCallbacks Callbacks = {});
898 Error parseComdatRecord(ArrayRef<uint64_t> Record);
899 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
900 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
901 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
902 ArrayRef<uint64_t> Record);
904 Error parseAttributeBlock();
905 Error parseAttributeGroupBlock();
906 Error parseTypeTable();
907 Error parseTypeTableBody();
908 Error parseOperandBundleTags();
909 Error parseSyncScopeNames();
911 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
912 unsigned NameIndex, Triple &TT);
913 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta, Function *
F,
914 ArrayRef<uint64_t> Record);
916 Error parseGlobalValueSymbolTable();
917 Error parseConstants();
918 Error rememberAndSkipFunctionBodies();
919 Error rememberAndSkipFunctionBody();
921 Error rememberAndSkipMetadata();
923 Error parseFunctionBody(Function *
F);
924 Error globalCleanup();
925 Error resolveGlobalAndIndirectSymbolInits();
926 Error parseUseLists();
927 Error findFunctionInStream(
929 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
936class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
938 ModuleSummaryIndex &TheIndex;
942 bool SeenGlobalValSummary =
false;
945 bool SeenValueSymbolTable =
false;
949 uint64_t VSTOffset = 0;
959 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
960 ValueIdToValueInfoMap;
966 DenseMap<uint64_t, StringRef> ModuleIdMap;
969 std::string SourceFileName;
973 StringRef ModulePath;
981 std::vector<uint64_t> StackIds;
985 std::vector<uint64_t> RadixArray;
988 ModuleSummaryIndexBitcodeReader(
989 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
990 StringRef ModulePath,
996 void setValueGUID(uint64_t ValueID, StringRef
ValueName,
998 StringRef SourceFileName);
999 Error parseValueSymbolTable(
1001 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1004 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1005 bool HasProfile,
bool HasRelBF);
1006 Error parseEntireSummary(
unsigned ID);
1007 Error parseModuleStringTable();
1008 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1009 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1011 std::vector<FunctionSummary::ParamAccess>
1012 parseParamAccesses(ArrayRef<uint64_t> Record);
1013 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1016 template <
bool AllowNullValueInfo = false>
1017 std::pair<ValueInfo, GlobalValue::GUID>
1018 getValueInfoFromValueId(
unsigned ValueId);
1020 void addThisModule();
1036 return std::error_code();
1042 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1043 ValueList(this->Stream.SizeInBytes(),
1045 return materializeValue(
ValID, InsertBB);
1047 this->ProducerIdentification = std::string(ProducerIdentification);
1050Error BitcodeReader::materializeForwardReferencedFunctions() {
1051 if (WillMaterializeAllForwardRefs)
1055 WillMaterializeAllForwardRefs =
true;
1057 while (!BasicBlockFwdRefQueue.empty()) {
1058 Function *
F = BasicBlockFwdRefQueue.front();
1059 BasicBlockFwdRefQueue.pop_front();
1060 assert(
F &&
"Expected valid function");
1061 if (!BasicBlockFwdRefs.
count(
F))
1069 if (!
F->isMaterializable())
1070 return error(
"Never resolved function from blockaddress");
1073 if (
Error Err = materialize(
F))
1076 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1078 for (Function *
F : BackwardRefFunctions)
1079 if (
Error Err = materialize(
F))
1081 BackwardRefFunctions.clear();
1084 WillMaterializeAllForwardRefs =
false;
1149 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1150 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1151 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1152 Flags.NoInline = (RawFlags >> 4) & 0x1;
1153 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1154 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1155 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1156 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1157 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1173 RawFlags = RawFlags >> 4;
1174 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1178 bool Live = (RawFlags & 0x2) || Version < 3;
1179 bool Local = (RawFlags & 0x4);
1180 bool AutoHide = (RawFlags & 0x8);
1183 Live,
Local, AutoHide, IK);
1189 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1190 (RawFlags & 0x4) ?
true :
false,
1194static std::pair<CalleeInfo::HotnessType, bool>
1198 bool HasTailCall = (RawFlags & 0x8);
1199 return {Hotness, HasTailCall};
1204 bool &HasTailCall) {
1205 static constexpr unsigned RelBlockFreqBits = 28;
1206 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1207 RelBF = RawFlags & RelBlockFreqMask;
1208 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1233 case 0:
return false;
1234 case 1:
return true;
1296 bool IsFP = Ty->isFPOrFPVectorTy();
1298 if (!IsFP && !Ty->isIntOrIntVectorTy())
1305 return IsFP ? Instruction::FNeg : -1;
1310 bool IsFP = Ty->isFPOrFPVectorTy();
1312 if (!IsFP && !Ty->isIntOrIntVectorTy())
1319 return IsFP ? Instruction::FAdd : Instruction::Add;
1321 return IsFP ? Instruction::FSub : Instruction::Sub;
1323 return IsFP ? Instruction::FMul : Instruction::Mul;
1325 return IsFP ? -1 : Instruction::UDiv;
1327 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1329 return IsFP ? -1 : Instruction::URem;
1331 return IsFP ? Instruction::FRem : Instruction::SRem;
1333 return IsFP ? -1 : Instruction::Shl;
1335 return IsFP ? -1 : Instruction::LShr;
1337 return IsFP ? -1 : Instruction::AShr;
1339 return IsFP ? -1 : Instruction::And;
1341 return IsFP ? -1 : Instruction::Or;
1343 return IsFP ? -1 : Instruction::Xor;
1440Type *BitcodeReader::getTypeByID(
unsigned ID) {
1442 if (
ID >= TypeList.size())
1445 if (
Type *Ty = TypeList[
ID])
1450 return TypeList[
ID] = createIdentifiedStructType(
Context);
1453unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1454 auto It = ContainedTypeIDs.
find(
ID);
1455 if (It == ContainedTypeIDs.
end())
1456 return InvalidTypeID;
1458 if (Idx >= It->second.size())
1459 return InvalidTypeID;
1461 return It->second[Idx];
1464Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1465 if (
ID >= TypeList.size())
1472 return getTypeByID(getContainedTypeID(
ID, 0));
1475unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1476 ArrayRef<unsigned> ChildTypeIDs) {
1477 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1478 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1479 auto It = VirtualTypeIDs.
find(CacheKey);
1480 if (It != VirtualTypeIDs.
end()) {
1486 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1487 "Incorrect cached contained type IDs");
1491 unsigned TypeID = TypeList.size();
1492 TypeList.push_back(Ty);
1493 if (!ChildTypeIDs.
empty())
1514 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1528 if (Opcode == Instruction::GetElementPtr)
1532 case Instruction::FNeg:
1533 case Instruction::Select:
1534 case Instruction::ICmp:
1535 case Instruction::FCmp:
1542Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1543 BasicBlock *InsertBB) {
1545 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1547 return ValueList[StartValID];
1549 SmallDenseMap<unsigned, Value *> MaterializedValues;
1550 SmallVector<unsigned> Worklist;
1552 while (!Worklist.
empty()) {
1553 unsigned ValID = Worklist.
back();
1554 if (MaterializedValues.
count(ValID)) {
1560 if (ValID >= ValueList.
size() || !ValueList[ValID])
1561 return error(
"Invalid value ID");
1563 Value *
V = ValueList[ValID];
1566 MaterializedValues.
insert({ValID,
V});
1574 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1575 auto It = MaterializedValues.
find(OpID);
1576 if (It != MaterializedValues.
end())
1577 Ops.push_back(It->second);
1584 if (
Ops.size() != BC->getOperandIDs().size())
1586 std::reverse(
Ops.begin(),
Ops.end());
1603 switch (BC->Opcode) {
1604 case BitcodeConstant::ConstantPtrAuthOpcode: {
1607 return error(
"ptrauth key operand must be ConstantInt");
1611 return error(
"ptrauth disc operand must be ConstantInt");
1614 ConstOps.
size() > 4 ? ConstOps[4]
1619 "ptrauth deactivation symbol operand must be a pointer");
1622 DeactivationSymbol);
1625 case BitcodeConstant::NoCFIOpcode: {
1628 return error(
"no_cfi operand must be GlobalValue");
1632 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1635 return error(
"dso_local operand must be GlobalValue");
1639 case BitcodeConstant::BlockAddressOpcode: {
1642 return error(
"blockaddress operand must be a function");
1647 unsigned BBID = BC->BlockAddressBB;
1650 return error(
"Invalid ID");
1653 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1655 return error(
"Invalid ID");
1662 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1664 BasicBlockFwdRefQueue.push_back(Fn);
1665 if (FwdBBs.size() < BBID + 1)
1666 FwdBBs.resize(BBID + 1);
1674 case BitcodeConstant::ConstantStructOpcode: {
1676 if (
ST->getNumElements() != ConstOps.
size())
1677 return error(
"Invalid number of elements in struct initializer");
1679 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1680 if (
Op->getType() != Ty)
1681 return error(
"Incorrect type in struct initializer");
1686 case BitcodeConstant::ConstantArrayOpcode: {
1688 if (AT->getNumElements() != ConstOps.
size())
1689 return error(
"Invalid number of elements in array initializer");
1691 for (Constant *
Op : ConstOps)
1692 if (
Op->getType() != AT->getElementType())
1693 return error(
"Incorrect type in array initializer");
1698 case BitcodeConstant::ConstantVectorOpcode: {
1700 if (VT->getNumElements() != ConstOps.size())
1701 return error(
"Invalid number of elements in vector initializer");
1703 for (Constant *
Op : ConstOps)
1704 if (
Op->getType() != VT->getElementType())
1705 return error(
"Incorrect type in vector initializer");
1710 case Instruction::GetElementPtr:
1712 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1715 case Instruction::ExtractElement:
1718 case Instruction::InsertElement:
1722 case Instruction::ShuffleVector: {
1723 SmallVector<int, 16>
Mask;
1735 MaterializedValues.
insert({ValID,
C});
1741 return error(Twine(
"Value referenced by initializer is an unsupported "
1742 "constant expression of type ") +
1743 BC->getOpcodeName());
1749 BC->getType(),
"constexpr", InsertBB);
1752 "constexpr", InsertBB);
1755 Ops[1],
"constexpr", InsertBB);
1758 I->setHasNoSignedWrap();
1760 I->setHasNoUnsignedWrap();
1766 switch (BC->Opcode) {
1767 case BitcodeConstant::ConstantVectorOpcode: {
1768 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1771 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1778 case BitcodeConstant::ConstantStructOpcode:
1779 case BitcodeConstant::ConstantArrayOpcode: {
1783 "constexpr.ins", InsertBB);
1787 case Instruction::ICmp:
1788 case Instruction::FCmp:
1791 "constexpr", InsertBB);
1793 case Instruction::GetElementPtr:
1799 case Instruction::Select:
1802 case Instruction::ExtractElement:
1805 case Instruction::InsertElement:
1809 case Instruction::ShuffleVector:
1810 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1818 MaterializedValues.
insert({ValID,
I});
1822 return MaterializedValues[StartValID];
1825Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1826 Expected<Value *> MaybeV = materializeValue(
ID,
nullptr);
1834StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1837 IdentifiedStructTypes.push_back(Ret);
1841StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1843 IdentifiedStructTypes.push_back(Ret);
1859 case Attribute::ZExt:
return 1 << 0;
1860 case Attribute::SExt:
return 1 << 1;
1861 case Attribute::NoReturn:
return 1 << 2;
1862 case Attribute::InReg:
return 1 << 3;
1863 case Attribute::StructRet:
return 1 << 4;
1864 case Attribute::NoUnwind:
return 1 << 5;
1865 case Attribute::NoAlias:
return 1 << 6;
1866 case Attribute::ByVal:
return 1 << 7;
1867 case Attribute::Nest:
return 1 << 8;
1868 case Attribute::ReadNone:
return 1 << 9;
1869 case Attribute::ReadOnly:
return 1 << 10;
1870 case Attribute::NoInline:
return 1 << 11;
1871 case Attribute::AlwaysInline:
return 1 << 12;
1872 case Attribute::OptimizeForSize:
return 1 << 13;
1873 case Attribute::StackProtect:
return 1 << 14;
1874 case Attribute::StackProtectReq:
return 1 << 15;
1875 case Attribute::Alignment:
return 31 << 16;
1877 case Attribute::NoRedZone:
return 1 << 22;
1878 case Attribute::NoImplicitFloat:
return 1 << 23;
1879 case Attribute::Naked:
return 1 << 24;
1880 case Attribute::InlineHint:
return 1 << 25;
1881 case Attribute::StackAlignment:
return 7 << 26;
1882 case Attribute::ReturnsTwice:
return 1 << 29;
1883 case Attribute::UWTable:
return 1 << 30;
1884 case Attribute::NonLazyBind:
return 1U << 31;
1885 case Attribute::SanitizeAddress:
return 1ULL << 32;
1886 case Attribute::MinSize:
return 1ULL << 33;
1887 case Attribute::NoDuplicate:
return 1ULL << 34;
1888 case Attribute::StackProtectStrong:
return 1ULL << 35;
1889 case Attribute::SanitizeThread:
return 1ULL << 36;
1890 case Attribute::SanitizeMemory:
return 1ULL << 37;
1891 case Attribute::NoBuiltin:
return 1ULL << 38;
1892 case Attribute::Returned:
return 1ULL << 39;
1893 case Attribute::Cold:
return 1ULL << 40;
1894 case Attribute::Builtin:
return 1ULL << 41;
1895 case Attribute::OptimizeNone:
return 1ULL << 42;
1896 case Attribute::InAlloca:
return 1ULL << 43;
1897 case Attribute::NonNull:
return 1ULL << 44;
1898 case Attribute::JumpTable:
return 1ULL << 45;
1899 case Attribute::Convergent:
return 1ULL << 46;
1900 case Attribute::SafeStack:
return 1ULL << 47;
1901 case Attribute::NoRecurse:
return 1ULL << 48;
1904 case Attribute::SwiftSelf:
return 1ULL << 51;
1905 case Attribute::SwiftError:
return 1ULL << 52;
1906 case Attribute::WriteOnly:
return 1ULL << 53;
1907 case Attribute::Speculatable:
return 1ULL << 54;
1908 case Attribute::StrictFP:
return 1ULL << 55;
1909 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1910 case Attribute::NoCfCheck:
return 1ULL << 57;
1911 case Attribute::OptForFuzzing:
return 1ULL << 58;
1912 case Attribute::ShadowCallStack:
return 1ULL << 59;
1913 case Attribute::SpeculativeLoadHardening:
1915 case Attribute::ImmArg:
1917 case Attribute::WillReturn:
1919 case Attribute::NoFree:
1935 if (
I == Attribute::Alignment)
1936 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1937 else if (
I == Attribute::StackAlignment)
1938 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1940 B.addTypeAttr(
I,
nullptr);
1954 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1956 "Alignment must be a power of two.");
1959 B.addAlignmentAttr(Alignment);
1961 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1962 (EncodedAttrs & 0xffff);
1964 if (AttrIdx == AttributeList::FunctionIndex) {
1967 if (Attrs & (1ULL << 9)) {
1969 Attrs &= ~(1ULL << 9);
1972 if (Attrs & (1ULL << 10)) {
1974 Attrs &= ~(1ULL << 10);
1977 if (Attrs & (1ULL << 49)) {
1979 Attrs &= ~(1ULL << 49);
1982 if (Attrs & (1ULL << 50)) {
1984 Attrs &= ~(1ULL << 50);
1987 if (Attrs & (1ULL << 53)) {
1989 Attrs &= ~(1ULL << 53);
1993 B.addMemoryAttr(ME);
1997 if (Attrs & (1ULL << 21)) {
1998 Attrs &= ~(1ULL << 21);
2005Error BitcodeReader::parseAttributeBlock() {
2009 if (!MAttributes.empty())
2010 return error(
"Invalid multiple blocks");
2012 SmallVector<uint64_t, 64>
Record;
2018 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2021 BitstreamEntry
Entry = MaybeEntry.
get();
2023 switch (
Entry.Kind) {
2026 return error(
"Malformed block");
2036 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2039 switch (MaybeRecord.
get()) {
2045 return error(
"Invalid parameter attribute record");
2047 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2053 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2057 for (uint64_t Val : Record)
2058 Attrs.push_back(MAttributeGroups[Val]);
2060 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2073 return Attribute::Alignment;
2075 return Attribute::AlwaysInline;
2077 return Attribute::Builtin;
2079 return Attribute::ByVal;
2081 return Attribute::InAlloca;
2083 return Attribute::Cold;
2085 return Attribute::Convergent;
2087 return Attribute::DisableSanitizerInstrumentation;
2089 return Attribute::ElementType;
2091 return Attribute::FnRetThunkExtern;
2093 return Attribute::InlineHint;
2095 return Attribute::InReg;
2097 return Attribute::JumpTable;
2099 return Attribute::Memory;
2101 return Attribute::NoFPClass;
2103 return Attribute::MinSize;
2105 return Attribute::Naked;
2107 return Attribute::Nest;
2109 return Attribute::NoAlias;
2111 return Attribute::NoBuiltin;
2113 return Attribute::NoCallback;
2115 return Attribute::NoDivergenceSource;
2117 return Attribute::NoDuplicate;
2119 return Attribute::NoFree;
2121 return Attribute::NoImplicitFloat;
2123 return Attribute::NoInline;
2125 return Attribute::NoRecurse;
2127 return Attribute::NoMerge;
2129 return Attribute::NonLazyBind;
2131 return Attribute::NonNull;
2133 return Attribute::Dereferenceable;
2135 return Attribute::DereferenceableOrNull;
2137 return Attribute::AllocAlign;
2139 return Attribute::AllocKind;
2141 return Attribute::AllocSize;
2143 return Attribute::AllocatedPointer;
2145 return Attribute::NoRedZone;
2147 return Attribute::NoReturn;
2149 return Attribute::NoSync;
2151 return Attribute::NoCfCheck;
2153 return Attribute::NoProfile;
2155 return Attribute::SkipProfile;
2157 return Attribute::NoUnwind;
2159 return Attribute::NoSanitizeBounds;
2161 return Attribute::NoSanitizeCoverage;
2163 return Attribute::NullPointerIsValid;
2165 return Attribute::OptimizeForDebugging;
2167 return Attribute::OptForFuzzing;
2169 return Attribute::OptimizeForSize;
2171 return Attribute::OptimizeNone;
2173 return Attribute::ReadNone;
2175 return Attribute::ReadOnly;
2177 return Attribute::Returned;
2179 return Attribute::ReturnsTwice;
2181 return Attribute::SExt;
2183 return Attribute::Speculatable;
2185 return Attribute::StackAlignment;
2187 return Attribute::StackProtect;
2189 return Attribute::StackProtectReq;
2191 return Attribute::StackProtectStrong;
2193 return Attribute::SafeStack;
2195 return Attribute::ShadowCallStack;
2197 return Attribute::StrictFP;
2199 return Attribute::StructRet;
2201 return Attribute::SanitizeAddress;
2203 return Attribute::SanitizeHWAddress;
2205 return Attribute::SanitizeThread;
2207 return Attribute::SanitizeType;
2209 return Attribute::SanitizeMemory;
2211 return Attribute::SanitizeNumericalStability;
2213 return Attribute::SanitizeRealtime;
2215 return Attribute::SanitizeRealtimeBlocking;
2217 return Attribute::SanitizeAllocToken;
2219 return Attribute::SpeculativeLoadHardening;
2221 return Attribute::SwiftError;
2223 return Attribute::SwiftSelf;
2225 return Attribute::SwiftAsync;
2227 return Attribute::UWTable;
2229 return Attribute::VScaleRange;
2231 return Attribute::WillReturn;
2233 return Attribute::WriteOnly;
2235 return Attribute::ZExt;
2237 return Attribute::ImmArg;
2239 return Attribute::SanitizeMemTag;
2241 return Attribute::Preallocated;
2243 return Attribute::NoUndef;
2245 return Attribute::ByRef;
2247 return Attribute::MustProgress;
2249 return Attribute::Hot;
2251 return Attribute::PresplitCoroutine;
2253 return Attribute::Writable;
2255 return Attribute::CoroDestroyOnlyWhenComplete;
2257 return Attribute::DeadOnUnwind;
2259 return Attribute::Range;
2261 return Attribute::Initializes;
2263 return Attribute::CoroElideSafe;
2265 return Attribute::NoExt;
2267 return Attribute::Captures;
2269 return Attribute::DeadOnReturn;
2271 return Attribute::NoCreateUndefOrPoison;
2276 MaybeAlign &Alignment) {
2279 if (
Exponent > Value::MaxAlignmentExponent + 1)
2280 return error(
"Invalid alignment value");
2285Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2287 if (*Kind == Attribute::None)
2288 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2293 switch (EncodedKind) {
2317Error BitcodeReader::parseAttributeGroupBlock() {
2321 if (!MAttributeGroups.empty())
2322 return error(
"Invalid multiple blocks");
2324 SmallVector<uint64_t, 64>
Record;
2328 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2331 BitstreamEntry
Entry = MaybeEntry.
get();
2333 switch (
Entry.Kind) {
2336 return error(
"Malformed block");
2346 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2349 switch (MaybeRecord.
get()) {
2354 return error(
"Invalid grp record");
2356 uint64_t GrpID =
Record[0];
2357 uint64_t Idx =
Record[1];
2361 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2362 if (Record[i] == 0) {
2363 Attribute::AttrKind
Kind;
2364 uint64_t EncodedKind =
Record[++i];
2365 if (Idx == AttributeList::FunctionIndex &&
2374 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2380 if (Kind == Attribute::ByVal)
2381 B.addByValAttr(
nullptr);
2382 else if (Kind == Attribute::StructRet)
2383 B.addStructRetAttr(
nullptr);
2384 else if (Kind == Attribute::InAlloca)
2385 B.addInAllocaAttr(
nullptr);
2386 else if (Kind == Attribute::UWTable)
2387 B.addUWTableAttr(UWTableKind::Default);
2388 else if (Kind == Attribute::DeadOnReturn)
2389 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2390 else if (Attribute::isEnumAttrKind(Kind))
2391 B.addAttribute(Kind);
2393 return error(
"Not an enum attribute");
2394 }
else if (Record[i] == 1) {
2395 Attribute::AttrKind
Kind;
2396 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2398 if (!Attribute::isIntAttrKind(Kind))
2399 return error(
"Not an int attribute");
2400 if (Kind == Attribute::Alignment)
2401 B.addAlignmentAttr(Record[++i]);
2402 else if (Kind == Attribute::StackAlignment)
2403 B.addStackAlignmentAttr(Record[++i]);
2404 else if (Kind == Attribute::Dereferenceable)
2405 B.addDereferenceableAttr(Record[++i]);
2406 else if (Kind == Attribute::DereferenceableOrNull)
2407 B.addDereferenceableOrNullAttr(Record[++i]);
2408 else if (Kind == Attribute::DeadOnReturn)
2409 B.addDeadOnReturnAttr(
2411 else if (Kind == Attribute::AllocSize)
2412 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2413 else if (Kind == Attribute::VScaleRange)
2414 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2415 else if (Kind == Attribute::UWTable)
2417 else if (Kind == Attribute::AllocKind)
2418 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2419 else if (Kind == Attribute::Memory) {
2420 uint64_t EncodedME =
Record[++i];
2421 const uint8_t
Version = (EncodedME >> 56);
2433 B.addMemoryAttr(ME);
2438 EncodedME & 0x00FFFFFFFFFFFFFFULL));
2440 }
else if (Kind == Attribute::Captures)
2442 else if (Kind == Attribute::NoFPClass)
2445 }
else if (Record[i] == 3 || Record[i] == 4) {
2447 SmallString<64> KindStr;
2448 SmallString<64> ValStr;
2450 while (Record[i] != 0 && i != e)
2452 assert(Record[i] == 0 &&
"Kind string not null terminated");
2457 while (Record[i] != 0 && i != e)
2459 assert(Record[i] == 0 &&
"Value string not null terminated");
2462 B.addAttribute(KindStr.
str(), ValStr.
str());
2463 }
else if (Record[i] == 5 || Record[i] == 6) {
2464 bool HasType =
Record[i] == 6;
2465 Attribute::AttrKind
Kind;
2466 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2468 if (!Attribute::isTypeAttrKind(Kind))
2469 return error(
"Not a type attribute");
2471 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2472 }
else if (Record[i] == 7) {
2473 Attribute::AttrKind
Kind;
2476 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2478 if (!Attribute::isConstantRangeAttrKind(Kind))
2479 return error(
"Not a ConstantRange attribute");
2481 Expected<ConstantRange> MaybeCR =
2482 readBitWidthAndConstantRange(Record, i);
2487 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2488 }
else if (Record[i] == 8) {
2489 Attribute::AttrKind
Kind;
2492 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2494 if (!Attribute::isConstantRangeListAttrKind(Kind))
2495 return error(
"Not a constant range list attribute");
2499 return error(
"Too few records for constant range list");
2500 unsigned RangeSize =
Record[i++];
2502 for (
unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2503 Expected<ConstantRange> MaybeCR =
2504 readConstantRange(Record, i,
BitWidth);
2512 return error(
"Invalid (unordered or overlapping) range list");
2513 B.addConstantRangeListAttr(Kind, Val);
2515 return error(
"Invalid attribute group entry");
2520 B.addMemoryAttr(ME);
2523 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2530Error BitcodeReader::parseTypeTable() {
2534 return parseTypeTableBody();
2537Error BitcodeReader::parseTypeTableBody() {
2538 if (!TypeList.empty())
2539 return error(
"Invalid multiple blocks");
2541 SmallVector<uint64_t, 64>
Record;
2542 unsigned NumRecords = 0;
2548 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2551 BitstreamEntry
Entry = MaybeEntry.
get();
2553 switch (
Entry.Kind) {
2556 return error(
"Malformed block");
2558 if (NumRecords != TypeList.size())
2559 return error(
"Malformed block");
2568 Type *ResultTy =
nullptr;
2569 SmallVector<unsigned> ContainedIDs;
2570 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2573 switch (MaybeRecord.
get()) {
2575 return error(
"Invalid value");
2580 return error(
"Invalid numentry record");
2581 TypeList.resize(Record[0]);
2584 ResultTy = Type::getVoidTy(
Context);
2587 ResultTy = Type::getHalfTy(
Context);
2590 ResultTy = Type::getBFloatTy(
Context);
2593 ResultTy = Type::getFloatTy(
Context);
2596 ResultTy = Type::getDoubleTy(
Context);
2599 ResultTy = Type::getX86_FP80Ty(
Context);
2602 ResultTy = Type::getFP128Ty(
Context);
2605 ResultTy = Type::getPPC_FP128Ty(
Context);
2608 ResultTy = Type::getLabelTy(
Context);
2611 ResultTy = Type::getMetadataTy(
Context);
2619 ResultTy = Type::getX86_AMXTy(
Context);
2622 ResultTy = Type::getTokenTy(
Context);
2626 return error(
"Invalid integer record");
2628 uint64_t NumBits =
Record[0];
2631 return error(
"Bitwidth for integer type out of range");
2638 return error(
"Invalid pointer record");
2642 ResultTy = getTypeByID(Record[0]);
2644 !PointerType::isValidElementType(ResultTy))
2645 return error(
"Invalid type");
2652 return error(
"Invalid opaque pointer record");
2661 return error(
"Invalid function record");
2663 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2664 if (
Type *
T = getTypeByID(Record[i]))
2670 ResultTy = getTypeByID(Record[2]);
2671 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2672 return error(
"Invalid type");
2675 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2681 return error(
"Invalid function record");
2683 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2684 if (
Type *
T = getTypeByID(Record[i])) {
2685 if (!FunctionType::isValidArgumentType(
T))
2686 return error(
"Invalid function argument type");
2693 ResultTy = getTypeByID(Record[1]);
2694 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2695 return error(
"Invalid type");
2698 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2703 return error(
"Invalid anon struct record");
2705 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2706 if (
Type *
T = getTypeByID(Record[i]))
2712 return error(
"Invalid type");
2719 return error(
"Invalid struct name record");
2724 return error(
"Invalid named struct record");
2726 if (NumRecords >= TypeList.size())
2727 return error(
"Invalid TYPE table");
2733 TypeList[NumRecords] =
nullptr;
2735 Res = createIdentifiedStructType(
Context, TypeName);
2739 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2740 if (
Type *
T = getTypeByID(Record[i]))
2746 return error(
"Invalid named struct record");
2755 return error(
"Invalid opaque type record");
2757 if (NumRecords >= TypeList.size())
2758 return error(
"Invalid TYPE table");
2764 TypeList[NumRecords] =
nullptr;
2766 Res = createIdentifiedStructType(
Context, TypeName);
2773 return error(
"Invalid target extension type record");
2775 if (NumRecords >= TypeList.size())
2776 return error(
"Invalid TYPE table");
2778 if (Record[0] >=
Record.size())
2779 return error(
"Too many type parameters");
2781 unsigned NumTys =
Record[0];
2783 SmallVector<unsigned, 8> IntParams;
2784 for (
unsigned i = 0; i < NumTys; i++) {
2785 if (
Type *
T = getTypeByID(Record[i + 1]))
2788 return error(
"Invalid type");
2791 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2792 if (Record[i] > UINT_MAX)
2793 return error(
"Integer parameter too large");
2798 if (
auto E = TTy.takeError())
2806 return error(
"Invalid array type record");
2807 ResultTy = getTypeByID(Record[1]);
2808 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2809 return error(
"Invalid type");
2811 ResultTy = ArrayType::get(ResultTy, Record[0]);
2816 return error(
"Invalid vector type record");
2818 return error(
"Invalid vector length");
2819 ResultTy = getTypeByID(Record[1]);
2820 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2821 return error(
"Invalid type");
2824 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2828 if (NumRecords >= TypeList.size())
2829 return error(
"Invalid TYPE table");
2830 if (TypeList[NumRecords])
2832 "Invalid TYPE table: Only named structs can be forward referenced");
2833 assert(ResultTy &&
"Didn't read a type?");
2834 TypeList[NumRecords] = ResultTy;
2835 if (!ContainedIDs.
empty())
2836 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2841Error BitcodeReader::parseOperandBundleTags() {
2845 if (!BundleTags.empty())
2846 return error(
"Invalid multiple blocks");
2848 SmallVector<uint64_t, 64>
Record;
2851 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2854 BitstreamEntry
Entry = MaybeEntry.
get();
2856 switch (
Entry.Kind) {
2859 return error(
"Malformed block");
2869 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2873 return error(
"Invalid operand bundle record");
2876 BundleTags.emplace_back();
2878 return error(
"Invalid operand bundle record");
2883Error BitcodeReader::parseSyncScopeNames() {
2888 return error(
"Invalid multiple synchronization scope names blocks");
2890 SmallVector<uint64_t, 64>
Record;
2892 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2895 BitstreamEntry
Entry = MaybeEntry.
get();
2897 switch (
Entry.Kind) {
2900 return error(
"Malformed block");
2903 return error(
"Invalid empty synchronization scope names block");
2913 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2917 return error(
"Invalid sync scope record");
2919 SmallString<16> SSN;
2921 return error(
"Invalid sync scope record");
2929Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2930 unsigned NameIndex, Triple &TT) {
2933 return error(
"Invalid record");
2934 unsigned ValueID =
Record[0];
2935 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
2936 return error(
"Invalid record");
2937 Value *
V = ValueList[ValueID];
2940 if (NameStr.contains(0))
2941 return error(
"Invalid value name");
2942 V->setName(NameStr);
2944 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
2957 return std::move(JumpFailed);
2963 return error(
"Expected value symbol table subblock");
2967void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
2969 ArrayRef<uint64_t> Record) {
2973 uint64_t FuncWordOffset =
Record[1] - 1;
2974 uint64_t FuncBitOffset = FuncWordOffset * 32;
2975 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2979 if (FuncBitOffset > LastFunctionBlockBit)
2980 LastFunctionBlockBit = FuncBitOffset;
2984Error BitcodeReader::parseGlobalValueSymbolTable() {
2985 unsigned FuncBitcodeOffsetDelta =
2991 SmallVector<uint64_t, 64>
Record;
2993 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2996 BitstreamEntry
Entry = MaybeEntry.
get();
2998 switch (
Entry.Kind) {
3001 return error(
"Malformed block");
3009 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
3012 switch (MaybeRecord.
get()) {
3014 unsigned ValueID =
Record[0];
3015 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3016 return error(
"Invalid value reference in symbol table");
3017 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3027Error BitcodeReader::parseValueSymbolTable(uint64_t
Offset) {
3028 uint64_t CurrentBit;
3034 if (!MaybeCurrentBit)
3036 CurrentBit = MaybeCurrentBit.
get();
3039 if (
Error Err = parseGlobalValueSymbolTable())
3041 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
3060 unsigned FuncBitcodeOffsetDelta =
3066 SmallVector<uint64_t, 64>
Record;
3074 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3077 BitstreamEntry
Entry = MaybeEntry.
get();
3079 switch (
Entry.Kind) {
3082 return error(
"Malformed block");
3085 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
3095 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
3098 switch (MaybeRecord.
get()) {
3102 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3110 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3118 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3123 return error(
"Invalid bbentry record");
3126 return error(
"Invalid bbentry record");
3138uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3148Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3149 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3150 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3151 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3153 GlobalInitWorklist.swap(GlobalInits);
3154 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3155 FunctionOperandWorklist.swap(FunctionOperands);
3157 while (!GlobalInitWorklist.empty()) {
3158 unsigned ValID = GlobalInitWorklist.back().second;
3159 if (ValID >= ValueList.
size()) {
3161 GlobalInits.push_back(GlobalInitWorklist.back());
3163 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3166 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3168 GlobalInitWorklist.pop_back();
3171 while (!IndirectSymbolInitWorklist.empty()) {
3172 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3173 if (ValID >= ValueList.
size()) {
3174 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3176 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3180 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3183 return error(
"Alias and aliasee types don't match");
3188 return error(
"Expected an alias or an ifunc");
3191 IndirectSymbolInitWorklist.pop_back();
3194 while (!FunctionOperandWorklist.empty()) {
3195 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3196 if (
Info.PersonalityFn) {
3197 unsigned ValID =
Info.PersonalityFn - 1;
3198 if (ValID < ValueList.
size()) {
3199 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3202 Info.F->setPersonalityFn(MaybeC.
get());
3203 Info.PersonalityFn = 0;
3207 unsigned ValID =
Info.Prefix - 1;
3208 if (ValID < ValueList.
size()) {
3209 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3212 Info.F->setPrefixData(MaybeC.
get());
3216 if (
Info.Prologue) {
3217 unsigned ValID =
Info.Prologue - 1;
3218 if (ValID < ValueList.
size()) {
3219 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3222 Info.F->setPrologueData(MaybeC.
get());
3226 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3227 FunctionOperands.push_back(Info);
3228 FunctionOperandWorklist.pop_back();
3237 BitcodeReader::decodeSignRotatedValue);
3239 return APInt(TypeBits, Words);
3242Error BitcodeReader::parseConstants() {
3250 unsigned Int32TyID = getVirtualTypeID(CurTy);
3251 unsigned CurTyID = Int32TyID;
3252 Type *CurElemTy =
nullptr;
3253 unsigned NextCstNo = ValueList.
size();
3261 switch (Entry.Kind) {
3264 return error(
"Malformed block");
3266 if (NextCstNo != ValueList.
size())
3267 return error(
"Invalid constant reference");
3278 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
3281 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3291 return error(
"Invalid settype record");
3292 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3293 return error(
"Invalid settype record");
3294 if (TypeList[Record[0]] == VoidType)
3295 return error(
"Invalid constant type");
3297 CurTy = TypeList[CurTyID];
3298 CurElemTy = getPtrElementTypeByID(CurTyID);
3302 return error(
"Invalid type for a constant null value");
3305 return error(
"Invalid type for a constant null value");
3310 return error(
"Invalid integer const record");
3315 return error(
"Invalid wide integer const record");
3318 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3319 V = ConstantInt::get(CurTy, VInt);
3324 return error(
"Invalid float const record");
3327 if (ScalarTy->isHalfTy())
3328 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3329 APInt(16, (uint16_t)Record[0])));
3330 else if (ScalarTy->isBFloatTy())
3331 V = ConstantFP::get(
3332 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3333 else if (ScalarTy->isFloatTy())
3334 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3335 APInt(32, (uint32_t)Record[0])));
3336 else if (ScalarTy->isDoubleTy())
3337 V = ConstantFP::get(
3338 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3339 else if (ScalarTy->isX86_FP80Ty()) {
3341 uint64_t Rearrange[2];
3342 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3343 Rearrange[1] =
Record[0] >> 48;
3344 V = ConstantFP::get(
3345 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3346 }
else if (ScalarTy->isFP128Ty())
3347 V = ConstantFP::get(CurTy,
3348 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3349 else if (ScalarTy->isPPC_FP128Ty())
3350 V = ConstantFP::get(
3351 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3359 return error(
"Invalid aggregate record");
3361 SmallVector<unsigned, 16> Elts;
3365 V = BitcodeConstant::create(
3366 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3368 V = BitcodeConstant::create(
Alloc, CurTy,
3369 BitcodeConstant::ConstantArrayOpcode, Elts);
3371 V = BitcodeConstant::create(
3372 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3381 return error(
"Invalid string record");
3390 return error(
"Invalid data record");
3394 EltTy =
Array->getElementType();
3404 SmallVector<uint16_t, 16> Elts(
Record.begin(),
Record.end());
3410 SmallVector<uint32_t, 16> Elts(
Record.begin(),
Record.end());
3416 SmallVector<uint64_t, 16> Elts(
Record.begin(),
Record.end());
3422 SmallVector<uint16_t, 16> Elts(
Record.begin(),
Record.end());
3428 SmallVector<uint16_t, 16> Elts(
Record.begin(),
Record.end());
3434 SmallVector<uint32_t, 16> Elts(
Record.begin(),
Record.end());
3440 SmallVector<uint64_t, 16> Elts(
Record.begin(),
Record.end());
3446 return error(
"Invalid type for value");
3452 return error(
"Invalid unary op constexpr record");
3457 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3463 return error(
"Invalid binary op constexpr record");
3469 if (
Record.size() >= 4) {
3470 if (
Opc == Instruction::Add ||
3471 Opc == Instruction::Sub ||
3472 Opc == Instruction::Mul ||
3473 Opc == Instruction::Shl) {
3478 }
else if (
Opc == Instruction::SDiv ||
3479 Opc == Instruction::UDiv ||
3480 Opc == Instruction::LShr ||
3481 Opc == Instruction::AShr) {
3486 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3487 {(unsigned)Record[1], (
unsigned)
Record[2]});
3493 return error(
"Invalid cast constexpr record");
3498 unsigned OpTyID =
Record[1];
3499 Type *OpTy = getTypeByID(OpTyID);
3501 return error(
"Invalid cast constexpr record");
3502 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3514 return error(
"Constant GEP record must have at least two elements");
3516 Type *PointeeType =
nullptr;
3520 PointeeType = getTypeByID(Record[OpNum++]);
3523 std::optional<ConstantRange>
InRange;
3527 unsigned InRangeIndex =
Op >> 1;
3533 Expected<ConstantRange> MaybeInRange =
3534 readBitWidthAndConstantRange(Record, OpNum);
3543 SmallVector<unsigned, 16> Elts;
3544 unsigned BaseTypeID =
Record[OpNum];
3545 while (OpNum !=
Record.size()) {
3546 unsigned ElTyID =
Record[OpNum++];
3547 Type *ElTy = getTypeByID(ElTyID);
3549 return error(
"Invalid getelementptr constexpr record");
3553 if (Elts.
size() < 1)
3554 return error(
"Invalid gep with no operands");
3558 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3559 BaseType = getTypeByID(BaseTypeID);
3564 return error(
"GEP base operand must be pointer or vector of pointer");
3567 PointeeType = getPtrElementTypeByID(BaseTypeID);
3569 return error(
"Missing element type for old-style constant GEP");
3572 V = BitcodeConstant::create(
3574 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3580 return error(
"Invalid select constexpr record");
3582 V = BitcodeConstant::create(
3583 Alloc, CurTy, Instruction::Select,
3584 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3590 return error(
"Invalid extractelement constexpr record");
3591 unsigned OpTyID =
Record[0];
3595 return error(
"Invalid extractelement constexpr record");
3597 if (
Record.size() == 4) {
3598 unsigned IdxTyID =
Record[2];
3599 Type *IdxTy = getTypeByID(IdxTyID);
3601 return error(
"Invalid extractelement constexpr record");
3607 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3608 {(unsigned)Record[1], IdxRecord});
3614 if (
Record.size() < 3 || !OpTy)
3615 return error(
"Invalid insertelement constexpr record");
3617 if (
Record.size() == 4) {
3618 unsigned IdxTyID =
Record[2];
3619 Type *IdxTy = getTypeByID(IdxTyID);
3621 return error(
"Invalid insertelement constexpr record");
3627 V = BitcodeConstant::create(
3628 Alloc, CurTy, Instruction::InsertElement,
3629 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3634 if (
Record.size() < 3 || !OpTy)
3635 return error(
"Invalid shufflevector constexpr record");
3636 V = BitcodeConstant::create(
3637 Alloc, CurTy, Instruction::ShuffleVector,
3638 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3645 if (
Record.size() < 4 || !RTy || !OpTy)
3646 return error(
"Invalid shufflevector constexpr record");
3647 V = BitcodeConstant::create(
3648 Alloc, CurTy, Instruction::ShuffleVector,
3649 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3654 return error(
"Invalid cmp constexpt record");
3655 unsigned OpTyID =
Record[0];
3656 Type *OpTy = getTypeByID(OpTyID);
3658 return error(
"Invalid cmp constexpr record");
3659 V = BitcodeConstant::create(
3662 : Instruction::ICmp),
3663 (uint8_t)Record[3]},
3664 {(unsigned)Record[1], (
unsigned)
Record[2]});
3671 return error(
"Invalid inlineasm record");
3672 std::string AsmStr, ConstrStr;
3673 bool HasSideEffects =
Record[0] & 1;
3674 bool IsAlignStack =
Record[0] >> 1;
3675 unsigned AsmStrSize =
Record[1];
3676 if (2+AsmStrSize >=
Record.size())
3677 return error(
"Invalid inlineasm record");
3678 unsigned ConstStrSize =
Record[2+AsmStrSize];
3679 if (3+AsmStrSize+ConstStrSize >
Record.size())
3680 return error(
"Invalid inlineasm record");
3682 for (
unsigned i = 0; i != AsmStrSize; ++i)
3683 AsmStr += (
char)
Record[2+i];
3684 for (
unsigned i = 0; i != ConstStrSize; ++i)
3685 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3688 return error(
"Missing element type for old-style inlineasm");
3690 HasSideEffects, IsAlignStack);
3697 return error(
"Invalid inlineasm record");
3698 std::string AsmStr, ConstrStr;
3699 bool HasSideEffects =
Record[0] & 1;
3700 bool IsAlignStack = (
Record[0] >> 1) & 1;
3701 unsigned AsmDialect =
Record[0] >> 2;
3702 unsigned AsmStrSize =
Record[1];
3703 if (2+AsmStrSize >=
Record.size())
3704 return error(
"Invalid inlineasm record");
3705 unsigned ConstStrSize =
Record[2+AsmStrSize];
3706 if (3+AsmStrSize+ConstStrSize >
Record.size())
3707 return error(
"Invalid inlineasm record");
3709 for (
unsigned i = 0; i != AsmStrSize; ++i)
3710 AsmStr += (
char)
Record[2+i];
3711 for (
unsigned i = 0; i != ConstStrSize; ++i)
3712 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3715 return error(
"Missing element type for old-style inlineasm");
3717 HasSideEffects, IsAlignStack,
3724 return error(
"Invalid inlineasm record");
3726 std::string AsmStr, ConstrStr;
3727 bool HasSideEffects =
Record[OpNum] & 1;
3728 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3729 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3730 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3732 unsigned AsmStrSize =
Record[OpNum];
3734 if (OpNum + AsmStrSize >=
Record.size())
3735 return error(
"Invalid inlineasm record");
3736 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3737 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3738 return error(
"Invalid inlineasm record");
3740 for (
unsigned i = 0; i != AsmStrSize; ++i)
3741 AsmStr += (
char)
Record[OpNum + i];
3743 for (
unsigned i = 0; i != ConstStrSize; ++i)
3744 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3747 return error(
"Missing element type for old-style inlineasm");
3749 HasSideEffects, IsAlignStack,
3756 return error(
"Invalid inlineasm record");
3761 return error(
"Invalid inlineasm record");
3762 std::string AsmStr, ConstrStr;
3763 bool HasSideEffects =
Record[OpNum] & 1;
3764 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3765 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3766 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3768 unsigned AsmStrSize =
Record[OpNum];
3770 if (OpNum + AsmStrSize >=
Record.size())
3771 return error(
"Invalid inlineasm record");
3772 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3773 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3774 return error(
"Invalid inlineasm record");
3776 for (
unsigned i = 0; i != AsmStrSize; ++i)
3777 AsmStr += (
char)
Record[OpNum + i];
3779 for (
unsigned i = 0; i != ConstStrSize; ++i)
3780 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3782 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3788 return error(
"Invalid blockaddress record");
3789 unsigned FnTyID =
Record[0];
3790 Type *FnTy = getTypeByID(FnTyID);
3792 return error(
"Invalid blockaddress record");
3793 V = BitcodeConstant::create(
3795 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3801 return error(
"Invalid dso_local record");
3802 unsigned GVTyID =
Record[0];
3803 Type *GVTy = getTypeByID(GVTyID);
3805 return error(
"Invalid dso_local record");
3806 V = BitcodeConstant::create(
3807 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3812 return error(
"Invalid no_cfi record");
3813 unsigned GVTyID =
Record[0];
3814 Type *GVTy = getTypeByID(GVTyID);
3816 return error(
"Invalid no_cfi record");
3817 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3823 return error(
"Invalid ptrauth record");
3825 V = BitcodeConstant::create(
Alloc, CurTy,
3826 BitcodeConstant::ConstantPtrAuthOpcode,
3827 {(unsigned)Record[0], (
unsigned)
Record[1],
3828 (unsigned)Record[2], (
unsigned)
Record[3]});
3833 return error(
"Invalid ptrauth record");
3835 V = BitcodeConstant::create(
3836 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3837 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3838 (
unsigned)
Record[3], (unsigned)Record[4]});
3843 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3850Error BitcodeReader::parseUseLists() {
3855 SmallVector<uint64_t, 64>
Record;
3858 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3861 BitstreamEntry
Entry = MaybeEntry.
get();
3863 switch (
Entry.Kind) {
3866 return error(
"Malformed block");
3877 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
3880 switch (MaybeRecord.
get()) {
3888 if (RecordLength < 3)
3890 return error(
"Invalid uselist record");
3891 unsigned ID =
Record.pop_back_val();
3895 assert(
ID < FunctionBBs.size() &&
"Basic block not found");
3896 V = FunctionBBs[
ID];
3900 if (!
V->hasUseList())
3903 unsigned NumUses = 0;
3904 SmallDenseMap<const Use *, unsigned, 16> Order;
3905 for (
const Use &U :
V->materialized_uses()) {
3906 if (++NumUses >
Record.size())
3908 Order[&
U] =
Record[NumUses - 1];
3915 V->sortUseList([&](
const Use &L,
const Use &R) {
3926Error BitcodeReader::rememberAndSkipMetadata() {
3928 uint64_t CurBit = Stream.GetCurrentBitNo();
3929 DeferredMetadataInfo.push_back(CurBit);
3932 if (
Error Err = Stream.SkipBlock())
3937Error BitcodeReader::materializeMetadata() {
3938 for (uint64_t BitPos : DeferredMetadataInfo) {
3940 if (
Error JumpFailed = Stream.JumpToBit(BitPos))
3942 if (
Error Err = MDLoader->parseModuleMetadata())
3951 NamedMDNode *LinkerOpts =
3953 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
3958 DeferredMetadataInfo.clear();
3962void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
3966Error BitcodeReader::rememberAndSkipFunctionBody() {
3968 if (FunctionsWithBodies.empty())
3969 return error(
"Insufficient function protos");
3971 Function *Fn = FunctionsWithBodies.back();
3972 FunctionsWithBodies.pop_back();
3975 uint64_t CurBit = Stream.GetCurrentBitNo();
3977 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3978 "Mismatch between VST and scanned function offsets");
3979 DeferredFunctionInfo[Fn] = CurBit;
3982 if (
Error Err = Stream.SkipBlock())
3987Error BitcodeReader::globalCleanup() {
3989 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
3991 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3992 return error(
"Malformed global initializer set");
3996 for (Function &
F : *TheModule) {
3997 MDLoader->upgradeDebugIntrinsics(
F);
4000 UpgradedIntrinsics[&
F] = NewFn;
4006 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4007 for (GlobalVariable &GV : TheModule->globals())
4009 UpgradedVariables.emplace_back(&GV, Upgraded);
4010 for (
auto &Pair : UpgradedVariables) {
4011 Pair.first->eraseFromParent();
4012 TheModule->insertGlobalVariable(Pair.second);
4017 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4018 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4026Error BitcodeReader::rememberAndSkipFunctionBodies() {
4027 if (
Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
4030 if (Stream.AtEndOfStream())
4031 return error(
"Could not find function in stream");
4033 if (!SeenFirstFunctionBody)
4034 return error(
"Trying to materialize functions before seeing function blocks");
4038 assert(SeenValueSymbolTable);
4041 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4044 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4046 switch (
Entry.Kind) {
4048 return error(
"Expect SubBlock");
4052 return error(
"Expect function block");
4054 if (
Error Err = rememberAndSkipFunctionBody())
4056 NextUnreadBit = Stream.GetCurrentBitNo();
4063Error BitcodeReaderBase::readBlockInfo() {
4064 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4066 if (!MaybeNewBlockInfo)
4068 std::optional<BitstreamBlockInfo> NewBlockInfo =
4069 std::move(MaybeNewBlockInfo.
get());
4071 return error(
"Malformed block");
4072 BlockInfo = std::move(*NewBlockInfo);
4076Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4080 std::tie(Name, Record) = readNameFromStrtab(Record);
4083 return error(
"Invalid comdat record");
4085 std::string OldFormatName;
4088 return error(
"Invalid comdat record");
4089 unsigned ComdatNameSize =
Record[1];
4090 if (ComdatNameSize >
Record.size() - 2)
4091 return error(
"Comdat name size too large");
4092 OldFormatName.reserve(ComdatNameSize);
4093 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4094 OldFormatName += (
char)
Record[2 + i];
4095 Name = OldFormatName;
4097 Comdat *
C = TheModule->getOrInsertComdat(Name);
4098 C->setSelectionKind(SK);
4099 ComdatList.push_back(
C);
4113 Meta.NoAddress =
true;
4115 Meta.NoHWAddress =
true;
4119 Meta.IsDynInit =
true;
4123Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4131 std::tie(Name, Record) = readNameFromStrtab(Record);
4134 return error(
"Invalid global variable record");
4135 unsigned TyID =
Record[0];
4136 Type *Ty = getTypeByID(TyID);
4138 return error(
"Invalid global variable record");
4140 bool explicitType =
Record[1] & 2;
4146 return error(
"Invalid type for value");
4148 TyID = getContainedTypeID(TyID);
4149 Ty = getTypeByID(TyID);
4151 return error(
"Missing element type for old-style global");
4154 uint64_t RawLinkage =
Record[3];
4156 MaybeAlign Alignment;
4157 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4161 if (Record[5] - 1 >= SectionTable.size())
4162 return error(
"Invalid ID");
4171 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4179 bool ExternallyInitialized =
false;
4181 ExternallyInitialized =
Record[9];
4183 GlobalVariable *NewGV =
4193 if (
Record.size() > 10) {
4205 if (
unsigned InitID = Record[2])
4206 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4208 if (
Record.size() > 11) {
4209 if (
unsigned ComdatID = Record[11]) {
4210 if (ComdatID > ComdatList.size())
4211 return error(
"Invalid global variable comdat ID");
4212 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4215 ImplicitComdatObjects.
insert(NewGV);
4218 if (
Record.size() > 12) {
4223 if (
Record.size() > 13) {
4230 NewGV->
setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
4232 if (
Record.size() > 16 && Record[16]) {
4233 llvm::GlobalValue::SanitizerMetadata
Meta =
4238 if (
Record.size() > 17 && Record[17]) {
4242 return error(
"Invalid global variable code model");
4248void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4249 if (ValueTypeCallback) {
4250 (*ValueTypeCallback)(
4251 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4252 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4256Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4262 std::tie(Name, Record) = readNameFromStrtab(Record);
4265 return error(
"Invalid function record");
4266 unsigned FTyID =
Record[0];
4267 Type *FTy = getTypeByID(FTyID);
4269 return error(
"Invalid function record");
4271 FTyID = getContainedTypeID(FTyID, 0);
4272 FTy = getTypeByID(FTyID);
4274 return error(
"Missing element type for old-style function");
4278 return error(
"Invalid type for value");
4279 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4280 if (CC & ~CallingConv::MaxID)
4281 return error(
"Invalid calling convention ID");
4283 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4289 AddrSpace, Name, TheModule);
4292 "Incorrect fully specified type provided for function");
4293 FunctionTypeIDs[
Func] = FTyID;
4295 Func->setCallingConv(CC);
4296 bool isProto =
Record[2];
4297 uint64_t RawLinkage =
Record[3];
4300 callValueTypeCallback(Func, FTyID);
4305 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4306 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4307 Attribute::InAlloca}) {
4308 if (!
Func->hasParamAttribute(i, Kind))
4311 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4314 Func->removeParamAttr(i, Kind);
4316 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4317 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4319 return error(
"Missing param element type for attribute upgrade");
4323 case Attribute::ByVal:
4324 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4326 case Attribute::StructRet:
4327 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4329 case Attribute::InAlloca:
4330 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4336 Func->addParamAttr(i, NewAttr);
4340 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4341 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4342 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4343 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4345 return error(
"Missing param element type for x86_intrcc upgrade");
4347 Func->addParamAttr(0, NewAttr);
4350 MaybeAlign Alignment;
4351 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4354 Func->setAlignment(*Alignment);
4356 if (Record[6] - 1 >= SectionTable.size())
4357 return error(
"Invalid ID");
4358 Func->setSection(SectionTable[Record[6] - 1]);
4362 if (!
Func->hasLocalLinkage())
4364 if (
Record.size() > 8 && Record[8]) {
4365 if (Record[8] - 1 >= GCTable.size())
4366 return error(
"Invalid ID");
4367 Func->setGC(GCTable[Record[8] - 1]);
4372 Func->setUnnamedAddr(UnnamedAddr);
4374 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4376 OperandInfo.Prologue =
Record[10];
4378 if (
Record.size() > 11) {
4380 if (!
Func->hasLocalLinkage()) {
4387 if (
Record.size() > 12) {
4388 if (
unsigned ComdatID = Record[12]) {
4389 if (ComdatID > ComdatList.size())
4390 return error(
"Invalid function comdat ID");
4391 Func->setComdat(ComdatList[ComdatID - 1]);
4394 ImplicitComdatObjects.
insert(Func);
4398 OperandInfo.Prefix =
Record[13];
4401 OperandInfo.PersonalityFn =
Record[14];
4403 if (
Record.size() > 15) {
4412 if (
Record.size() > 18 && Strtab.data() &&
4413 Record[17] + Record[18] <= Strtab.size()) {
4414 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4417 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4419 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4420 FunctionOperands.push_back(OperandInfo);
4425 Func->setIsMaterializable(
true);
4426 FunctionsWithBodies.push_back(Func);
4427 DeferredFunctionInfo[
Func] = 0;
4432Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4433 unsigned BitCode, ArrayRef<uint64_t> Record) {
4443 std::tie(Name, Record) = readNameFromStrtab(Record);
4446 if (
Record.size() < (3 + (
unsigned)NewRecord))
4447 return error(
"Invalid global indirect symbol record");
4452 return error(
"Invalid global indirect symbol record");
4458 return error(
"Invalid type for value");
4459 AddrSpace = PTy->getAddressSpace();
4461 Ty = getTypeByID(
TypeID);
4463 return error(
"Missing element type for old-style indirect symbol");
4465 AddrSpace =
Record[OpNum++];
4468 auto Val =
Record[OpNum++];
4477 nullptr, TheModule);
4481 if (OpNum !=
Record.size()) {
4482 auto VisInd = OpNum++;
4488 if (OpNum !=
Record.size()) {
4489 auto S =
Record[OpNum++];
4496 if (OpNum !=
Record.size())
4498 if (OpNum !=
Record.size())
4501 if (OpNum !=
Record.size())
4506 if (OpNum + 1 <
Record.size()) {
4508 if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
4509 return error(
"Malformed partition, too large.");
4511 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4515 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4519Error BitcodeReader::parseModule(uint64_t ResumeBit,
4520 bool ShouldLazyLoadMetadata,
4521 ParserCallbacks Callbacks) {
4522 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4524 if (
Error JumpFailed = Stream.JumpToBit(ResumeBit))
4529 SmallVector<uint64_t, 64>
Record;
4533 bool ResolvedDataLayout =
false;
4538 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4540 auto ResolveDataLayout = [&]() ->
Error {
4541 if (ResolvedDataLayout)
4545 ResolvedDataLayout =
true;
4549 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4553 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4554 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4555 TentativeDataLayoutStr = *LayoutOverride;
4563 TheModule->setDataLayout(MaybeDL.
get());
4569 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4572 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4574 switch (
Entry.Kind) {
4576 return error(
"Malformed block");
4578 if (
Error Err = ResolveDataLayout())
4580 return globalCleanup();
4585 if (
Error Err = Stream.SkipBlock())
4589 if (
Error Err = readBlockInfo())
4593 if (
Error Err = parseAttributeBlock())
4597 if (
Error Err = parseAttributeGroupBlock())
4601 if (
Error Err = parseTypeTable())
4605 if (!SeenValueSymbolTable) {
4611 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4612 if (
Error Err = parseValueSymbolTable())
4614 SeenValueSymbolTable =
true;
4619 if (
Error Err = Stream.SkipBlock())
4624 if (
Error Err = parseConstants())
4626 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4630 if (ShouldLazyLoadMetadata) {
4631 if (
Error Err = rememberAndSkipMetadata())
4635 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4636 if (
Error Err = MDLoader->parseModuleMetadata())
4640 if (
Error Err = MDLoader->parseMetadataKinds())
4644 if (
Error Err = ResolveDataLayout())
4649 if (!SeenFirstFunctionBody) {
4650 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4651 if (
Error Err = globalCleanup())
4653 SeenFirstFunctionBody =
true;
4656 if (VSTOffset > 0) {
4660 if (!SeenValueSymbolTable) {
4661 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4663 SeenValueSymbolTable =
true;
4675 if (
Error Err = Stream.SkipBlock())
4685 if (
Error Err = rememberAndSkipFunctionBody())
4692 if (SeenValueSymbolTable) {
4693 NextUnreadBit = Stream.GetCurrentBitNo();
4696 return globalCleanup();
4700 if (
Error Err = parseUseLists())
4704 if (
Error Err = parseOperandBundleTags())
4708 if (
Error Err = parseSyncScopeNames())
4720 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
4723 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4726 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4729 UseRelativeIDs = *VersionOrErr >= 1;
4733 if (ResolvedDataLayout)
4734 return error(
"target triple too late in module");
4737 return error(
"Invalid triple record");
4738 TheModule->setTargetTriple(Triple(std::move(S)));
4742 if (ResolvedDataLayout)
4743 return error(
"datalayout too late in module");
4745 return error(
"Invalid data layout record");
4751 return error(
"Invalid asm record");
4752 TheModule->setModuleInlineAsm(S);
4759 return error(
"Invalid deplib record");
4766 return error(
"Invalid section name record");
4767 SectionTable.push_back(S);
4773 return error(
"Invalid gcname record");
4774 GCTable.push_back(S);
4778 if (
Error Err = parseComdatRecord(Record))
4787 if (
Error Err = parseGlobalVarRecord(Record))
4791 if (
Error Err = ResolveDataLayout())
4793 if (
Error Err = parseFunctionRecord(Record))
4799 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4805 return error(
"Invalid vstoffset record");
4809 VSTOffset =
Record[0] - 1;
4815 return error(
"Invalid source filename record");
4816 TheModule->setSourceFileName(
ValueName);
4821 this->ValueTypeCallback = std::nullopt;
4825Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4827 ParserCallbacks Callbacks) {
4829 MetadataLoaderCallbacks MDCallbacks;
4830 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(
ID); };
4832 return getContainedTypeID(
I, J);
4835 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4836 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4839Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4841 return error(
"Load/Store operand is not a pointer type");
4842 if (!PointerType::isLoadableOrStorableType(ValType))
4843 return error(
"Cannot load/store from pointer");
4847Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4848 ArrayRef<unsigned> ArgTyIDs) {
4850 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4851 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4852 Attribute::InAlloca}) {
4853 if (!
Attrs.hasParamAttr(i, Kind) ||
4854 Attrs.getParamAttr(i, Kind).getValueAsType())
4857 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4859 return error(
"Missing element type for typed attribute upgrade");
4863 case Attribute::ByVal:
4864 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4866 case Attribute::StructRet:
4867 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4869 case Attribute::InAlloca:
4870 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4883 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
4887 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
4888 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4890 return error(
"Missing element type for inline asm upgrade");
4893 Attribute::get(
Context, Attribute::ElementType, ElemTy));
4901 case Intrinsic::preserve_array_access_index:
4902 case Intrinsic::preserve_struct_access_index:
4903 case Intrinsic::aarch64_ldaxr:
4904 case Intrinsic::aarch64_ldxr:
4905 case Intrinsic::aarch64_stlxr:
4906 case Intrinsic::aarch64_stxr:
4907 case Intrinsic::arm_ldaex:
4908 case Intrinsic::arm_ldrex:
4909 case Intrinsic::arm_stlex:
4910 case Intrinsic::arm_strex: {
4913 case Intrinsic::aarch64_stlxr:
4914 case Intrinsic::aarch64_stxr:
4915 case Intrinsic::arm_stlex:
4916 case Intrinsic::arm_strex:
4923 if (!
Attrs.getParamElementType(ArgNo)) {
4924 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4926 return error(
"Missing element type for elementtype upgrade");
4941Error BitcodeReader::parseFunctionBody(Function *
F) {
4946 if (MDLoader->hasFwdRefs())
4947 return error(
"Invalid function metadata: incoming forward references");
4949 InstructionList.
clear();
4950 unsigned ModuleValueListSize = ValueList.
size();
4951 unsigned ModuleMDLoaderSize = MDLoader->size();
4955 unsigned FTyID = FunctionTypeIDs[
F];
4956 for (Argument &
I :
F->args()) {
4957 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4958 assert(
I.getType() == getTypeByID(ArgTyID) &&
4959 "Incorrect fully specified type for Function Argument");
4963 unsigned NextValueNo = ValueList.
size();
4965 unsigned CurBBNo = 0;
4970 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
4974 auto getLastInstruction = [&]() -> Instruction * {
4975 if (CurBB && !CurBB->
empty())
4976 return &CurBB->
back();
4977 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4978 !FunctionBBs[CurBBNo - 1]->
empty())
4979 return &FunctionBBs[CurBBNo - 1]->back();
4983 std::vector<OperandBundleDef> OperandBundles;
4986 SmallVector<uint64_t, 64>
Record;
4989 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4992 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4994 switch (
Entry.Kind) {
4996 return error(
"Malformed block");
4998 goto OutOfRecordLoop;
5003 if (
Error Err = Stream.SkipBlock())
5007 if (
Error Err = parseConstants())
5009 NextValueNo = ValueList.
size();
5012 if (
Error Err = parseValueSymbolTable())
5016 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5020 assert(DeferredMetadataInfo.empty() &&
5021 "Must read all module-level metadata before function-level");
5022 if (
Error Err = MDLoader->parseFunctionMetadata())
5026 if (
Error Err = parseUseLists())
5040 unsigned ResTypeID = InvalidTypeID;
5041 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
5044 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5046 return error(
"Invalid value");
5048 if (
Record.empty() || Record[0] == 0)
5049 return error(
"Invalid declareblocks record");
5051 FunctionBBs.resize(Record[0]);
5054 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5055 if (BBFRI == BasicBlockFwdRefs.
end()) {
5056 for (BasicBlock *&BB : FunctionBBs)
5059 auto &BBRefs = BBFRI->second;
5061 if (BBRefs.size() > FunctionBBs.size())
5062 return error(
"Invalid ID");
5063 assert(!BBRefs.empty() &&
"Unexpected empty array");
5064 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5065 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5067 if (
I < RE && BBRefs[
I]) {
5068 BBRefs[
I]->insertInto(
F);
5069 FunctionBBs[
I] = BBRefs[
I];
5075 BasicBlockFwdRefs.
erase(BBFRI);
5078 CurBB = FunctionBBs[0];
5085 return error(
"Invalid blockaddr users record");
5099 for (uint64_t ValID : Record)
5101 BackwardRefFunctions.push_back(
F);
5103 return error(
"Invalid blockaddr users record");
5110 I = getLastInstruction();
5113 return error(
"Invalid debug_loc_again record");
5114 I->setDebugLoc(LastLoc);
5119 I = getLastInstruction();
5121 return error(
"Invalid debug loc record");
5126 uint64_t AtomGroup =
Record.size() == 7 ?
Record[5] : 0;
5129 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5132 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5134 return error(
"Invalid debug loc record");
5138 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5140 return error(
"Invalid debug loc record");
5143 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5144 isImplicitCode, AtomGroup, AtomRank);
5145 I->setDebugLoc(LastLoc);
5153 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5155 return error(
"Invalid unary operator record");
5159 return error(
"Invalid unary operator record");
5163 if (OpNum <
Record.size()) {
5167 I->setFastMathFlags(FMF);
5176 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5180 return error(
"Invalid binary operator record");
5184 return error(
"Invalid binary operator record");
5188 if (OpNum <
Record.size()) {
5189 if (
Opc == Instruction::Add ||
5190 Opc == Instruction::Sub ||
5191 Opc == Instruction::Mul ||
5192 Opc == Instruction::Shl) {
5197 }
else if (
Opc == Instruction::SDiv ||
5198 Opc == Instruction::UDiv ||
5199 Opc == Instruction::LShr ||
5200 Opc == Instruction::AShr) {
5203 }
else if (
Opc == Instruction::Or) {
5209 I->setFastMathFlags(FMF);
5218 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5219 OpNum + 1 >
Record.size())
5220 return error(
"Invalid cast record");
5222 ResTypeID =
Record[OpNum++];
5223 Type *ResTy = getTypeByID(ResTypeID);
5226 if (
Opc == -1 || !ResTy)
5227 return error(
"Invalid cast record");
5232 assert(CurBB &&
"No current BB?");
5238 return error(
"Invalid cast");
5242 if (OpNum <
Record.size()) {
5243 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5246 }
else if (
Opc == Instruction::Trunc) {
5255 I->setFastMathFlags(FMF);
5274 Ty = getTypeByID(TyID);
5278 TyID = InvalidTypeID;
5283 unsigned BasePtrTypeID;
5284 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5286 return error(
"Invalid gep record");
5289 TyID = getContainedTypeID(BasePtrTypeID);
5290 if (
BasePtr->getType()->isVectorTy())
5291 TyID = getContainedTypeID(TyID);
5292 Ty = getTypeByID(TyID);
5295 SmallVector<Value*, 16> GEPIdx;
5296 while (OpNum !=
Record.size()) {
5299 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5300 return error(
"Invalid gep record");
5311 unsigned SubType = 0;
5312 if (GTI.isStruct()) {
5314 Idx->getType()->isVectorTy()
5316 :
cast<ConstantInt>(Idx);
5319 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5326 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5327 if (
I->getType()->isVectorTy())
5328 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5331 GEP->setNoWrapFlags(NW);
5340 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5341 return error(
"Invalid extractvalue record");
5344 unsigned RecSize =
Record.size();
5345 if (OpNum == RecSize)
5346 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5348 SmallVector<unsigned, 4> EXTRACTVALIdx;
5349 ResTypeID = AggTypeID;
5350 for (; OpNum != RecSize; ++OpNum) {
5355 if (!IsStruct && !IsArray)
5356 return error(
"EXTRACTVAL: Invalid type");
5357 if ((
unsigned)Index != Index)
5358 return error(
"Invalid value");
5360 return error(
"EXTRACTVAL: Invalid struct index");
5362 return error(
"EXTRACTVAL: Invalid array index");
5363 EXTRACTVALIdx.
push_back((
unsigned)Index);
5367 ResTypeID = getContainedTypeID(ResTypeID, Index);
5370 ResTypeID = getContainedTypeID(ResTypeID);
5384 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5385 return error(
"Invalid insertvalue record");
5388 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5389 return error(
"Invalid insertvalue record");
5391 unsigned RecSize =
Record.size();
5392 if (OpNum == RecSize)
5393 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5395 SmallVector<unsigned, 4> INSERTVALIdx;
5397 for (; OpNum != RecSize; ++OpNum) {
5402 if (!IsStruct && !IsArray)
5403 return error(
"INSERTVAL: Invalid type");
5404 if ((
unsigned)Index != Index)
5405 return error(
"Invalid value");
5407 return error(
"INSERTVAL: Invalid struct index");
5409 return error(
"INSERTVAL: Invalid array index");
5411 INSERTVALIdx.
push_back((
unsigned)Index);
5419 return error(
"Inserted value type doesn't match aggregate type");
5422 ResTypeID = AggTypeID;
5434 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5436 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5438 popValue(Record, OpNum, NextValueNo, CondType,
5439 getVirtualTypeID(CondType),
Cond, CurBB))
5440 return error(
"Invalid select record");
5453 unsigned ValTypeID, CondTypeID;
5454 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5456 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5458 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5459 return error(
"Invalid vector select record");
5462 if (VectorType* vector_type =
5465 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5466 return error(
"Invalid type for value");
5470 return error(
"Invalid type for value");
5474 ResTypeID = ValTypeID;
5479 I->setFastMathFlags(FMF);
5487 unsigned VecTypeID, IdxTypeID;
5488 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5489 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5490 return error(
"Invalid extractelement record");
5492 return error(
"Invalid type for value");
5494 ResTypeID = getContainedTypeID(VecTypeID);
5501 Value *Vec, *Elt, *Idx;
5502 unsigned VecTypeID, IdxTypeID;
5503 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5504 return error(
"Invalid insertelement record");
5506 return error(
"Invalid type for value");
5507 if (popValue(Record, OpNum, NextValueNo,
5509 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5510 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5511 return error(
"Invalid insert element record");
5513 ResTypeID = VecTypeID;
5521 unsigned Vec1TypeID;
5522 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5524 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5526 return error(
"Invalid shufflevector record");
5528 unsigned MaskTypeID;
5529 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5530 return error(
"Invalid shufflevector record");
5532 return error(
"Invalid type for value");
5534 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5536 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5551 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5552 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5554 return error(
"Invalid comparison record");
5556 if (OpNum >=
Record.size())
5558 "Invalid record: operand number exceeded available operands");
5563 if (IsFP &&
Record.size() > OpNum+1)
5568 return error(
"Invalid fcmp predicate");
5569 I =
new FCmpInst(PredVal,
LHS,
RHS);
5572 return error(
"Invalid icmp predicate");
5573 I =
new ICmpInst(PredVal,
LHS,
RHS);
5574 if (
Record.size() > OpNum + 1 &&
5579 if (OpNum + 1 !=
Record.size())
5580 return error(
"Invalid comparison record");
5582 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5584 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5587 I->setFastMathFlags(FMF);
5604 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5605 return error(
"Invalid ret record");
5606 if (OpNum !=
Record.size())
5607 return error(
"Invalid ret record");
5615 return error(
"Invalid br record");
5616 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5618 return error(
"Invalid br record");
5620 if (
Record.size() == 1) {
5625 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5627 Value *
Cond = getValue(Record, 2, NextValueNo, CondType,
5628 getVirtualTypeID(CondType), CurBB);
5629 if (!FalseDest || !
Cond)
5630 return error(
"Invalid br record");
5638 return error(
"Invalid cleanupret record");
5641 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5642 getVirtualTypeID(TokenTy), CurBB);
5644 return error(
"Invalid cleanupret record");
5646 if (
Record.size() == 2) {
5647 UnwindDest = getBasicBlock(Record[Idx++]);
5649 return error(
"Invalid cleanupret record");
5658 return error(
"Invalid catchret record");
5661 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5662 getVirtualTypeID(TokenTy), CurBB);
5664 return error(
"Invalid catchret record");
5665 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5667 return error(
"Invalid catchret record");
5676 return error(
"Invalid catchswitch record");
5681 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5682 getVirtualTypeID(TokenTy), CurBB);
5684 return error(
"Invalid catchswitch record");
5686 unsigned NumHandlers =
Record[Idx++];
5689 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5690 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5692 return error(
"Invalid catchswitch record");
5697 if (Idx + 1 ==
Record.size()) {
5698 UnwindDest = getBasicBlock(Record[Idx++]);
5700 return error(
"Invalid catchswitch record");
5703 if (
Record.size() != Idx)
5704 return error(
"Invalid catchswitch record");
5708 for (BasicBlock *Handler : Handlers)
5709 CatchSwitch->addHandler(Handler);
5711 ResTypeID = getVirtualTypeID(
I->getType());
5719 return error(
"Invalid catchpad/cleanuppad record");
5724 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5725 getVirtualTypeID(TokenTy), CurBB);
5727 return error(
"Invalid catchpad/cleanuppad record");
5729 unsigned NumArgOperands =
Record[Idx++];
5731 SmallVector<Value *, 2>
Args;
5732 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5735 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5736 return error(
"Invalid catchpad/cleanuppad record");
5737 Args.push_back(Val);
5740 if (
Record.size() != Idx)
5741 return error(
"Invalid catchpad/cleanuppad record");
5747 ResTypeID = getVirtualTypeID(
I->getType());
5753 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5759 unsigned OpTyID =
Record[1];
5760 Type *OpTy = getTypeByID(OpTyID);
5763 Value *
Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5766 return error(
"Invalid switch record");
5768 unsigned NumCases =
Record[4];
5773 unsigned CurIdx = 5;
5774 for (
unsigned i = 0; i != NumCases; ++i) {
5776 unsigned NumItems =
Record[CurIdx++];
5777 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5778 bool isSingleNumber =
Record[CurIdx++];
5781 unsigned ActiveWords = 1;
5782 if (ValueBitWidth > 64)
5783 ActiveWords =
Record[CurIdx++];
5786 CurIdx += ActiveWords;
5788 if (!isSingleNumber) {
5790 if (ValueBitWidth > 64)
5791 ActiveWords =
Record[CurIdx++];
5794 CurIdx += ActiveWords;
5805 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5806 for (ConstantInt *Cst : CaseVals)
5807 SI->addCase(Cst, DestBB);
5816 return error(
"Invalid switch record");
5817 unsigned OpTyID =
Record[0];
5818 Type *OpTy = getTypeByID(OpTyID);
5819 Value *
Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5822 return error(
"Invalid switch record");
5823 unsigned NumCases = (
Record.size()-3)/2;
5826 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5828 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
5829 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5830 if (!CaseVal || !DestBB) {
5832 return error(
"Invalid switch record");
5834 SI->addCase(CaseVal, DestBB);
5841 return error(
"Invalid indirectbr record");
5842 unsigned OpTyID =
Record[0];
5843 Type *OpTy = getTypeByID(OpTyID);
5844 Value *
Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5846 return error(
"Invalid indirectbr record");
5847 unsigned NumDests =
Record.size()-2;
5850 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5851 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5855 return error(
"Invalid indirectbr record");
5865 return error(
"Invalid invoke record");
5868 unsigned CCInfo =
Record[OpNum++];
5869 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5870 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5872 unsigned FTyID = InvalidTypeID;
5873 FunctionType *FTy =
nullptr;
5874 if ((CCInfo >> 13) & 1) {
5878 return error(
"Explicit invoke type is not a function type");
5882 unsigned CalleeTypeID;
5883 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5885 return error(
"Invalid invoke record");
5889 return error(
"Callee is not a pointer");
5891 FTyID = getContainedTypeID(CalleeTypeID);
5894 return error(
"Callee is not of pointer to function type");
5896 if (
Record.size() < FTy->getNumParams() + OpNum)
5897 return error(
"Insufficient operands to call");
5899 SmallVector<Value*, 16>
Ops;
5900 SmallVector<unsigned, 16> ArgTyIDs;
5901 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5902 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5903 Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5907 return error(
"Invalid invoke record");
5910 if (!FTy->isVarArg()) {
5911 if (
Record.size() != OpNum)
5912 return error(
"Invalid invoke record");
5915 while (OpNum !=
Record.size()) {
5918 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5919 return error(
"Invalid invoke record");
5926 if (!OperandBundles.empty())
5931 ResTypeID = getContainedTypeID(FTyID);
5932 OperandBundles.clear();
5935 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
5946 Value *Val =
nullptr;
5948 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5949 return error(
"Invalid resume record");
5958 unsigned CCInfo =
Record[OpNum++];
5960 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5961 unsigned NumIndirectDests =
Record[OpNum++];
5962 SmallVector<BasicBlock *, 16> IndirectDests;
5963 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
5964 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
5966 unsigned FTyID = InvalidTypeID;
5967 FunctionType *FTy =
nullptr;
5972 return error(
"Explicit call type is not a function type");
5976 unsigned CalleeTypeID;
5977 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5979 return error(
"Invalid callbr record");
5983 return error(
"Callee is not a pointer type");
5985 FTyID = getContainedTypeID(CalleeTypeID);
5988 return error(
"Callee is not of pointer to function type");
5990 if (
Record.size() < FTy->getNumParams() + OpNum)
5991 return error(
"Insufficient operands to call");
5993 SmallVector<Value*, 16>
Args;
5994 SmallVector<unsigned, 16> ArgTyIDs;
5996 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5998 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5999 if (FTy->getParamType(i)->isLabelTy())
6000 Arg = getBasicBlock(Record[OpNum]);
6002 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6005 return error(
"Invalid callbr record");
6006 Args.push_back(Arg);
6011 if (!FTy->isVarArg()) {
6012 if (OpNum !=
Record.size())
6013 return error(
"Invalid callbr record");
6015 while (OpNum !=
Record.size()) {
6018 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6019 return error(
"Invalid callbr record");
6026 if (!OperandBundles.empty())
6031 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6034 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6039 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6040 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6041 unsigned LabelNo = ArgNo - FirstBlockArg;
6043 if (!BA || BA->getFunction() !=
F ||
6044 LabelNo > IndirectDests.
size() ||
6045 BA->getBasicBlock() != IndirectDests[LabelNo])
6046 return error(
"callbr argument does not match indirect dest");
6051 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6055 for (
Value *Arg : Args)
6058 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6061 std::string Constraints =
IA->getConstraintString().str();
6064 for (
const auto &CI : ConstraintInfo) {
6066 if (ArgNo >= FirstBlockArg)
6067 Constraints.insert(Pos,
"!");
6072 Pos = Constraints.find(
',', Pos);
6073 if (Pos == std::string::npos)
6079 IA->hasSideEffects(),
IA->isAlignStack(),
6080 IA->getDialect(),
IA->canThrow());
6086 ResTypeID = getContainedTypeID(FTyID);
6087 OperandBundles.clear();
6104 return error(
"Invalid phi record");
6106 unsigned TyID =
Record[0];
6107 Type *Ty = getTypeByID(TyID);
6109 return error(
"Invalid phi record");
6114 size_t NumArgs = (
Record.size() - 1) / 2;
6118 return error(
"Invalid phi record");
6122 SmallDenseMap<BasicBlock *, Value *>
Args;
6123 for (
unsigned i = 0; i != NumArgs; i++) {
6124 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6127 return error(
"Invalid phi BB");
6134 auto It =
Args.find(BB);
6136 if (It !=
Args.end()) {
6150 if (!PhiConstExprBB)
6152 EdgeBB = PhiConstExprBB;
6160 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6162 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6166 return error(
"Invalid phi record");
6169 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6170 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6171 PhiConstExprBB =
nullptr;
6174 Args.insert({BB,
V});
6180 if (
Record.size() % 2 == 0) {
6184 I->setFastMathFlags(FMF);
6196 return error(
"Invalid landingpad record");
6200 return error(
"Invalid landingpad record");
6202 ResTypeID =
Record[Idx++];
6203 Type *Ty = getTypeByID(ResTypeID);
6205 return error(
"Invalid landingpad record");
6207 Value *PersFn =
nullptr;
6208 unsigned PersFnTypeID;
6209 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6211 return error(
"Invalid landingpad record");
6213 if (!
F->hasPersonalityFn())
6216 return error(
"Personality function mismatch");
6219 bool IsCleanup = !!
Record[Idx++];
6220 unsigned NumClauses =
Record[Idx++];
6223 for (
unsigned J = 0; J != NumClauses; ++J) {
6229 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6232 return error(
"Invalid landingpad record");
6237 "Catch clause has a invalid type!");
6240 "Filter clause has invalid type!");
6251 return error(
"Invalid alloca record");
6252 using APV = AllocaPackedValues;
6253 const uint64_t Rec =
Record[3];
6256 unsigned TyID =
Record[0];
6257 Type *Ty = getTypeByID(TyID);
6259 TyID = getContainedTypeID(TyID);
6260 Ty = getTypeByID(TyID);
6262 return error(
"Missing element type for old-style alloca");
6264 unsigned OpTyID =
Record[1];
6265 Type *OpTy = getTypeByID(OpTyID);
6266 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6271 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6275 return error(
"Invalid alloca record");
6277 const DataLayout &
DL = TheModule->getDataLayout();
6278 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6280 SmallPtrSet<Type *, 4> Visited;
6281 if (!Align && !Ty->
isSized(&Visited))
6282 return error(
"alloca of unsized type");
6284 Align =
DL.getPrefTypeAlign(Ty);
6286 if (!
Size->getType()->isIntegerTy())
6287 return error(
"alloca element count must have integer type");
6289 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6293 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6301 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6302 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6303 return error(
"Invalid load record");
6306 return error(
"Load operand is not a pointer type");
6309 if (OpNum + 3 ==
Record.size()) {
6310 ResTypeID =
Record[OpNum++];
6311 Ty = getTypeByID(ResTypeID);
6313 ResTypeID = getContainedTypeID(OpTypeID);
6314 Ty = getTypeByID(ResTypeID);
6318 return error(
"Missing load type");
6320 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6324 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6326 SmallPtrSet<Type *, 4> Visited;
6327 if (!Align && !Ty->
isSized(&Visited))
6328 return error(
"load of unsized type");
6330 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6331 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6340 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6341 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size()))
6342 return error(
"Invalid load atomic record");
6345 return error(
"Load operand is not a pointer type");
6348 if (OpNum + 5 ==
Record.size()) {
6349 ResTypeID =
Record[OpNum++];
6350 Ty = getTypeByID(ResTypeID);
6352 ResTypeID = getContainedTypeID(OpTypeID);
6353 Ty = getTypeByID(ResTypeID);
6357 return error(
"Missing atomic load type");
6359 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6363 if (Ordering == AtomicOrdering::NotAtomic ||
6364 Ordering == AtomicOrdering::Release ||
6365 Ordering == AtomicOrdering::AcquireRelease)
6366 return error(
"Invalid load atomic record");
6367 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6368 return error(
"Invalid load atomic record");
6369 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6372 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6375 return error(
"Alignment missing from atomic load");
6376 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align, Ordering, SSID);
6384 unsigned PtrTypeID, ValTypeID;
6385 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6386 return error(
"Invalid store record");
6389 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6390 return error(
"Invalid store record");
6392 ValTypeID = getContainedTypeID(PtrTypeID);
6393 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6394 ValTypeID, Val, CurBB))
6395 return error(
"Invalid store record");
6398 if (OpNum + 2 !=
Record.size())
6399 return error(
"Invalid store record");
6404 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6406 SmallPtrSet<Type *, 4> Visited;
6408 return error(
"store of unsized type");
6410 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6411 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6420 unsigned PtrTypeID, ValTypeID;
6421 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6423 return error(
"Invalid store atomic record");
6425 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6426 return error(
"Invalid store atomic record");
6428 ValTypeID = getContainedTypeID(PtrTypeID);
6429 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6430 ValTypeID, Val, CurBB))
6431 return error(
"Invalid store atomic record");
6434 if (OpNum + 4 !=
Record.size())
6435 return error(
"Invalid store atomic record");
6440 if (Ordering == AtomicOrdering::NotAtomic ||
6441 Ordering == AtomicOrdering::Acquire ||
6442 Ordering == AtomicOrdering::AcquireRelease)
6443 return error(
"Invalid store atomic record");
6444 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6445 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6446 return error(
"Invalid store atomic record");
6449 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6452 return error(
"Alignment missing from atomic store");
6453 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6460 const size_t NumRecords =
Record.size();
6462 Value *Ptr =
nullptr;
6464 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6465 return error(
"Invalid cmpxchg record");
6468 return error(
"Cmpxchg operand is not a pointer type");
6471 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6472 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6473 CmpTypeID, Cmp, CurBB))
6474 return error(
"Invalid cmpxchg record");
6477 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6479 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6480 return error(
"Invalid cmpxchg record");
6484 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6485 SuccessOrdering == AtomicOrdering::Unordered)
6486 return error(
"Invalid cmpxchg record");
6488 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6490 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6498 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6499 FailureOrdering == AtomicOrdering::Unordered)
6500 return error(
"Invalid cmpxchg record");
6502 const Align Alignment(
6503 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6505 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6506 FailureOrdering, SSID);
6509 if (NumRecords < 8) {
6513 I->insertInto(CurBB, CurBB->
end());
6515 ResTypeID = CmpTypeID;
6518 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6519 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6528 const size_t NumRecords =
Record.size();
6530 Value *Ptr =
nullptr;
6532 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6533 return error(
"Invalid cmpxchg record");
6536 return error(
"Cmpxchg operand is not a pointer type");
6540 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6541 return error(
"Invalid cmpxchg record");
6543 Value *Val =
nullptr;
6544 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6546 return error(
"Invalid cmpxchg record");
6548 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6549 return error(
"Invalid cmpxchg record");
6551 const bool IsVol =
Record[OpNum];
6556 return error(
"Invalid cmpxchg success ordering");
6558 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6560 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6566 return error(
"Invalid cmpxchg failure ordering");
6568 const bool IsWeak =
Record[OpNum + 4];
6570 MaybeAlign Alignment;
6572 if (NumRecords == (OpNum + 6)) {
6573 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6578 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6580 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6581 FailureOrdering, SSID);
6585 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6586 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6595 const size_t NumRecords =
Record.size();
6598 Value *Ptr =
nullptr;
6600 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6601 return error(
"Invalid atomicrmw record");
6604 return error(
"Invalid atomicrmw record");
6606 Value *Val =
nullptr;
6607 unsigned ValTypeID = InvalidTypeID;
6609 ValTypeID = getContainedTypeID(PtrTypeID);
6610 if (popValue(Record, OpNum, NextValueNo,
6611 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6612 return error(
"Invalid atomicrmw record");
6614 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6615 return error(
"Invalid atomicrmw record");
6618 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6619 return error(
"Invalid atomicrmw record");
6625 return error(
"Invalid atomicrmw record");
6627 const bool IsVol =
Record[OpNum + 1];
6630 if (Ordering == AtomicOrdering::NotAtomic ||
6631 Ordering == AtomicOrdering::Unordered)
6632 return error(
"Invalid atomicrmw record");
6634 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6636 MaybeAlign Alignment;
6638 if (NumRecords == (OpNum + 5)) {
6639 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6645 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6647 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID);
6648 ResTypeID = ValTypeID;
6656 return error(
"Invalid fence record");
6658 if (Ordering == AtomicOrdering::NotAtomic ||
6659 Ordering == AtomicOrdering::Unordered ||
6660 Ordering == AtomicOrdering::Monotonic)
6661 return error(
"Invalid fence record");
6663 I =
new FenceInst(
Context, Ordering, SSID);
6670 SeenDebugRecord =
true;
6673 return error(
"Invalid dbg record: missing instruction");
6676 Inst->
getParent()->insertDbgRecordBefore(
6687 SeenDebugRecord =
true;
6690 return error(
"Invalid dbg record: missing instruction");
6707 DILocalVariable *Var =
6709 DIExpression *Expr =
6722 unsigned SlotBefore =
Slot;
6723 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6724 return error(
"Invalid dbg record: invalid value");
6726 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6729 RawLocation = getFnMetadataByID(Record[Slot++]);
6732 DbgVariableRecord *DVR =
nullptr;
6736 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6737 DbgVariableRecord::LocationType::Value);
6740 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6741 DbgVariableRecord::LocationType::Declare);
6744 DVR =
new DbgVariableRecord(
6745 RawLocation, Var, Expr, DIL,
6746 DbgVariableRecord::LocationType::DeclareValue);
6750 DIExpression *AddrExpr =
6752 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6753 DVR =
new DbgVariableRecord(RawLocation, Var, Expr,
ID, Addr, AddrExpr,
6766 return error(
"Invalid call record");
6770 unsigned CCInfo =
Record[OpNum++];
6776 return error(
"Fast math flags indicator set for call with no FMF");
6779 unsigned FTyID = InvalidTypeID;
6780 FunctionType *FTy =
nullptr;
6785 return error(
"Explicit call type is not a function type");
6789 unsigned CalleeTypeID;
6790 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6792 return error(
"Invalid call record");
6796 return error(
"Callee is not a pointer type");
6798 FTyID = getContainedTypeID(CalleeTypeID);
6801 return error(
"Callee is not of pointer to function type");
6803 if (
Record.size() < FTy->getNumParams() + OpNum)
6804 return error(
"Insufficient operands to call");
6806 SmallVector<Value*, 16>
Args;
6807 SmallVector<unsigned, 16> ArgTyIDs;
6809 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6810 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6811 if (FTy->getParamType(i)->isLabelTy())
6812 Args.push_back(getBasicBlock(Record[OpNum]));
6814 Args.push_back(getValue(Record, OpNum, NextValueNo,
6815 FTy->getParamType(i), ArgTyID, CurBB));
6818 return error(
"Invalid call record");
6822 if (!FTy->isVarArg()) {
6823 if (OpNum !=
Record.size())
6824 return error(
"Invalid call record");
6826 while (OpNum !=
Record.size()) {
6829 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6830 return error(
"Invalid call record");
6837 if (!OperandBundles.empty())
6841 ResTypeID = getContainedTypeID(FTyID);
6842 OperandBundles.clear();
6856 SeenDebugIntrinsic =
true;
6863 return error(
"Fast-math-flags specified for call without "
6864 "floating-point scalar or vector return type");
6865 I->setFastMathFlags(FMF);
6871 return error(
"Invalid va_arg record");
6872 unsigned OpTyID =
Record[0];
6873 Type *OpTy = getTypeByID(OpTyID);
6874 Value *
Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6876 Type *ResTy = getTypeByID(ResTypeID);
6877 if (!OpTy || !
Op || !ResTy)
6878 return error(
"Invalid va_arg record");
6879 I =
new VAArgInst(
Op, ResTy);
6889 if (
Record.empty() || Record[0] >= BundleTags.size())
6890 return error(
"Invalid operand bundle record");
6892 std::vector<Value *> Inputs;
6895 while (OpNum !=
Record.size()) {
6897 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
6898 return error(
"Invalid operand bundle record");
6899 Inputs.push_back(
Op);
6902 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6910 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6911 return error(
"Invalid freeze record");
6912 if (OpNum !=
Record.size())
6913 return error(
"Invalid freeze record");
6915 I =
new FreezeInst(
Op);
6916 ResTypeID = OpTypeID;
6926 return error(
"Invalid instruction with no BB");
6928 if (!OperandBundles.empty()) {
6930 return error(
"Operand bundles found with no consumer");
6932 I->insertInto(CurBB, CurBB->
end());
6935 if (
I->isTerminator()) {
6937 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
6941 if (!
I->getType()->isVoidTy()) {
6942 assert(
I->getType() == getTypeByID(ResTypeID) &&
6943 "Incorrect result type ID");
6951 if (!OperandBundles.empty())
6952 return error(
"Operand bundles found with no consumer");
6956 if (!
A->getParent()) {
6958 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
6964 return error(
"Never resolved value found in function");
6969 if (MDLoader->hasFwdRefs())
6970 return error(
"Invalid function metadata: outgoing forward refs");
6975 for (
const auto &Pair : ConstExprEdgeBBs) {
6986 ValueList.
shrinkTo(ModuleValueListSize);
6987 MDLoader->shrinkTo(ModuleMDLoaderSize);
6988 std::vector<BasicBlock*>().swap(FunctionBBs);
6993Error BitcodeReader::findFunctionInStream(
6995 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
6996 while (DeferredFunctionInfoIterator->second == 0) {
7001 assert(VSTOffset == 0 || !
F->hasName());
7004 if (
Error Err = rememberAndSkipFunctionBodies())
7010SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7013 if (Val >= SSIDs.
size())
7022Error BitcodeReader::materialize(GlobalValue *GV) {
7025 if (!
F || !
F->isMaterializable())
7028 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.
find(
F);
7029 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7032 if (DFII->second == 0)
7033 if (
Error Err = findFunctionInStream(
F, DFII))
7037 if (
Error Err = materializeMetadata())
7041 if (
Error JumpFailed = Stream.JumpToBit(DFII->second))
7044 if (
Error Err = parseFunctionBody(
F))
7046 F->setIsMaterializable(
false);
7050 if (SeenDebugIntrinsic && SeenDebugRecord)
7051 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7057 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7058 F->setSubprogram(SP);
7061 if (!MDLoader->isStrippingTBAA()) {
7063 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7066 MDLoader->setStripTBAA(
true);
7073 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7074 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7080 unsigned ExpectedNumOperands = 0;
7082 ExpectedNumOperands = BI->getNumSuccessors();
7084 ExpectedNumOperands =
SI->getNumSuccessors();
7086 ExpectedNumOperands = 1;
7090 ExpectedNumOperands = 2;
7097 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7098 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7104 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7105 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7107 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7108 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7109 CI->getArgOperand(ArgNo)->getType(),
7110 CI->getParamAttributes(ArgNo)));
7113 if (Function *OldFn = CI->getCalledFunction()) {
7114 auto It = UpgradedIntrinsics.find(OldFn);
7115 if (It != UpgradedIntrinsics.end())
7126 return materializeForwardReferencedFunctions();
7129Error BitcodeReader::materializeModule() {
7130 if (
Error Err = materializeMetadata())
7134 WillMaterializeAllForwardRefs =
true;
7138 for (Function &
F : *TheModule) {
7139 if (
Error Err = materialize(&
F))
7145 if (LastFunctionBlockBit || NextUnreadBit)
7147 ? LastFunctionBlockBit
7153 if (!BasicBlockFwdRefs.
empty())
7154 return error(
"Never resolved function from blockaddress");
7160 for (
auto &
I : UpgradedIntrinsics) {
7161 for (
auto *U :
I.first->users()) {
7165 if (
I.first !=
I.second) {
7166 if (!
I.first->use_empty())
7167 I.first->replaceAllUsesWith(
I.second);
7168 I.first->eraseFromParent();
7171 UpgradedIntrinsics.clear();
7186std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7187 return IdentifiedStructTypes;
7190ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7191 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7193 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7194 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7196void ModuleSummaryIndexBitcodeReader::addThisModule() {
7201ModuleSummaryIndexBitcodeReader::getThisModule() {
7205template <
bool AllowNullValueInfo>
7206std::pair<ValueInfo, GlobalValue::GUID>
7207ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7208 auto VGI = ValueIdToValueInfoMap[ValueId];
7215 assert(AllowNullValueInfo || std::get<0>(VGI));
7219void ModuleSummaryIndexBitcodeReader::setValueGUID(
7221 StringRef SourceFileName) {
7222 std::string GlobalId =
7225 auto OriginalNameID = ValueGUID;
7229 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7235 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7244Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7246 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7253 if (!MaybeCurrentBit)
7255 uint64_t CurrentBit = MaybeCurrentBit.
get();
7260 SmallVector<uint64_t, 64>
Record;
7266 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7269 BitstreamEntry
Entry = MaybeEntry.
get();
7271 switch (
Entry.Kind) {
7274 return error(
"Malformed block");
7277 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
7287 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
7290 switch (MaybeRecord.
get()) {
7295 return error(
"Invalid vst_code_entry record");
7296 unsigned ValueID =
Record[0];
7298 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7299 assert(VLI != ValueIdToLinkageMap.
end() &&
7300 "No linkage found for VST entry?");
7309 return error(
"Invalid vst_code_fnentry record");
7310 unsigned ValueID =
Record[0];
7312 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7313 assert(VLI != ValueIdToLinkageMap.
end() &&
7314 "No linkage found for VST entry?");
7322 unsigned ValueID =
Record[0];
7326 ValueIdToValueInfoMap[ValueID] =
7337Error ModuleSummaryIndexBitcodeReader::parseModule() {
7341 SmallVector<uint64_t, 64>
Record;
7342 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7343 unsigned ValueId = 0;
7347 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7350 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7352 switch (
Entry.Kind) {
7354 return error(
"Malformed block");
7361 if (
Error Err = Stream.SkipBlock())
7366 if (
Error Err = readBlockInfo())
7372 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7373 !SeenGlobalValSummary) &&
7374 "Expected early VST parse via VSTOffset record");
7375 if (
Error Err = Stream.SkipBlock())
7381 if (!SourceFileName.
empty())
7383 assert(!SeenValueSymbolTable &&
7384 "Already read VST when parsing summary block?");
7389 if (VSTOffset > 0) {
7390 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7392 SeenValueSymbolTable =
true;
7394 SeenGlobalValSummary =
true;
7395 if (
Error Err = parseEntireSummary(
Entry.ID))
7399 if (
Error Err = parseModuleStringTable())
7407 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
7410 switch (MaybeBitCode.
get()) {
7414 if (
Error Err = parseVersionRecord(Record).takeError())
7422 return error(
"Invalid source filename record");
7429 return error(
"Invalid hash length " + Twine(
Record.size()).str());
7430 auto &Hash = getThisModule()->second;
7432 for (
auto &Val : Record) {
7433 assert(!(Val >> 32) &&
"Unexpected high bits set");
7441 return error(
"Invalid vstoffset record");
7445 VSTOffset =
Record[0] - 1;
7455 ArrayRef<uint64_t> GVRecord;
7456 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7457 if (GVRecord.
size() <= 3)
7458 return error(
"Invalid global record");
7459 uint64_t RawLinkage = GVRecord[3];
7462 ValueIdToLinkageMap[ValueId++] =
Linkage;
7466 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7477ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7480 for (uint64_t RefValueId : Record)
7481 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7486ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7487 bool IsOldProfileFormat,
7488 bool HasProfile,
bool HasRelBF) {
7492 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7497 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7499 bool HasTailCall =
false;
7501 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7502 if (IsOldProfileFormat) {
7506 }
else if (HasProfile)
7507 std::tie(Hotness, HasTailCall) =
7541 static_cast<size_t>(
Record[Slot + 1])};
7564 while (Slot <
Record.size())
7568std::vector<FunctionSummary::ParamAccess>
7569ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7570 auto ReadRange = [&]() {
7572 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7574 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7581 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7582 while (!
Record.empty()) {
7583 PendingParamAccesses.emplace_back();
7584 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7586 ParamAccess.
Use = ReadRange();
7591 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7592 Call.Offsets = ReadRange();
7595 return PendingParamAccesses;
7598void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7599 ArrayRef<uint64_t> Record,
size_t &Slot,
7602 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7606void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7607 ArrayRef<uint64_t> Record) {
7615 while (Slot <
Record.size())
7616 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7619SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7620 ArrayRef<uint64_t> Record,
unsigned &
I) {
7621 SmallVector<unsigned> StackIdList;
7625 if (RadixArray.empty()) {
7626 unsigned NumStackEntries =
Record[
I++];
7628 StackIdList.
reserve(NumStackEntries);
7629 for (
unsigned J = 0; J < NumStackEntries; J++) {
7630 assert(Record[
I] < StackIds.size());
7635 unsigned RadixIndex =
Record[
I++];
7641 assert(RadixIndex < RadixArray.size());
7642 unsigned NumStackIds = RadixArray[RadixIndex++];
7643 StackIdList.
reserve(NumStackIds);
7644 while (NumStackIds--) {
7645 assert(RadixIndex < RadixArray.size());
7646 unsigned Elem = RadixArray[RadixIndex];
7647 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7648 RadixIndex = RadixIndex - Elem;
7649 assert(RadixIndex < RadixArray.size());
7650 Elem = RadixArray[RadixIndex];
7652 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7665 unsigned FirstWORef = Refs.
size() - WOCnt;
7666 unsigned RefNo = FirstWORef - ROCnt;
7667 for (; RefNo < FirstWORef; ++RefNo)
7668 Refs[RefNo].setReadOnly();
7669 for (; RefNo < Refs.
size(); ++RefNo)
7670 Refs[RefNo].setWriteOnly();
7675Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7676 if (
Error Err = Stream.EnterSubBlock(
ID))
7678 SmallVector<uint64_t, 64>
Record;
7682 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7685 BitstreamEntry
Entry = MaybeEntry.
get();
7688 return error(
"Invalid Summary Block: record for version expected");
7689 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
7693 return error(
"Invalid Summary Block: version expected");
7696 const bool IsOldProfileFormat =
Version == 1;
7698 return error(
"Invalid summary version " + Twine(
Version) +
7699 ". Version should be in the range [1-" +
7706 GlobalValueSummary *LastSeenSummary =
nullptr;
7712 std::vector<GlobalValue::GUID> PendingTypeTests;
7713 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7714 PendingTypeCheckedLoadVCalls;
7715 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7716 PendingTypeCheckedLoadConstVCalls;
7717 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7719 std::vector<CallsiteInfo> PendingCallsites;
7720 std::vector<AllocInfo> PendingAllocs;
7721 std::vector<uint64_t> PendingContextIds;
7724 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7727 BitstreamEntry
Entry = MaybeEntry.
get();
7729 switch (
Entry.Kind) {
7732 return error(
"Malformed block");
7748 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
7751 switch (
unsigned BitCode = MaybeBitCode.
get()) {
7759 uint64_t ValueID =
Record[0];
7766 ValueIdToValueInfoMap[ValueID] =
7784 unsigned ValueID =
Record[0];
7785 uint64_t RawFlags =
Record[1];
7786 unsigned InstCount =
Record[2];
7787 uint64_t RawFunFlags = 0;
7788 unsigned NumRefs =
Record[3];
7789 unsigned NumRORefs = 0, NumWORefs = 0;
7790 int RefListStartIndex = 4;
7794 RefListStartIndex = 5;
7797 RefListStartIndex = 6;
7800 RefListStartIndex = 7;
7811 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7813 "Record size inconsistent with number of references");
7815 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7820 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7821 IsOldProfileFormat, HasProfile, HasRelBF);
7823 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7829 !IsPrevailing(VIAndOriginalGUID.first.getGUID())) {
7830 PendingCallsites.clear();
7831 PendingAllocs.clear();
7833 auto FS = std::make_unique<FunctionSummary>(
7835 std::move(Calls), std::move(PendingTypeTests),
7836 std::move(PendingTypeTestAssumeVCalls),
7837 std::move(PendingTypeCheckedLoadVCalls),
7838 std::move(PendingTypeTestAssumeConstVCalls),
7839 std::move(PendingTypeCheckedLoadConstVCalls),
7840 std::move(PendingParamAccesses), std::move(PendingCallsites),
7841 std::move(PendingAllocs));
7842 FS->setModulePath(getThisModule()->first());
7843 FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7852 unsigned ValueID =
Record[0];
7853 uint64_t RawFlags =
Record[1];
7854 unsigned AliaseeID =
Record[2];
7856 auto AS = std::make_unique<AliasSummary>(Flags);
7862 AS->setModulePath(getThisModule()->first());
7864 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7866 if (!AliaseeInModule)
7867 return error(
"Alias expects aliasee summary to be parsed");
7868 AS->setAliasee(AliaseeVI, AliaseeInModule);
7870 auto GUID = getValueInfoFromValueId(ValueID);
7871 AS->setOriginalName(std::get<1>(GUID));
7877 unsigned ValueID =
Record[0];
7878 uint64_t RawFlags =
Record[1];
7879 unsigned RefArrayStart = 2;
7880 GlobalVarSummary::GVarFlags GVF(
false,
7890 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7892 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7893 FS->setModulePath(getThisModule()->first());
7894 auto GUID = getValueInfoFromValueId(ValueID);
7895 FS->setOriginalName(std::get<1>(GUID));
7903 unsigned ValueID =
Record[0];
7904 uint64_t RawFlags =
Record[1];
7906 unsigned NumRefs =
Record[3];
7907 unsigned RefListStartIndex = 4;
7908 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7911 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7913 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
7914 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7919 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7920 VS->setModulePath(getThisModule()->first());
7921 VS->setVTableFuncs(VTableFuncs);
7922 auto GUID = getValueInfoFromValueId(ValueID);
7923 VS->setOriginalName(std::get<1>(GUID));
7935 unsigned ValueID =
Record[0];
7936 uint64_t ModuleId =
Record[1];
7937 uint64_t RawFlags =
Record[2];
7938 unsigned InstCount =
Record[3];
7939 uint64_t RawFunFlags = 0;
7940 unsigned NumRefs =
Record[4];
7941 unsigned NumRORefs = 0, NumWORefs = 0;
7942 int RefListStartIndex = 5;
7946 RefListStartIndex = 6;
7947 size_t NumRefsIndex = 5;
7949 unsigned NumRORefsOffset = 1;
7950 RefListStartIndex = 7;
7953 RefListStartIndex = 8;
7955 RefListStartIndex = 9;
7957 NumRORefsOffset = 2;
7960 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
7962 NumRefs =
Record[NumRefsIndex];
7966 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7968 "Record size inconsistent with number of references");
7970 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7973 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7974 IsOldProfileFormat, HasProfile,
false);
7975 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
7977 auto FS = std::make_unique<FunctionSummary>(
7979 std::move(Edges), std::move(PendingTypeTests),
7980 std::move(PendingTypeTestAssumeVCalls),
7981 std::move(PendingTypeCheckedLoadVCalls),
7982 std::move(PendingTypeTestAssumeConstVCalls),
7983 std::move(PendingTypeCheckedLoadConstVCalls),
7984 std::move(PendingParamAccesses), std::move(PendingCallsites),
7985 std::move(PendingAllocs));
7986 LastSeenSummary =
FS.get();
7987 LastSeenGUID =
VI.getGUID();
7988 FS->setModulePath(ModuleIdMap[ModuleId]);
7996 unsigned ValueID =
Record[0];
7997 uint64_t ModuleId =
Record[1];
7998 uint64_t RawFlags =
Record[2];
7999 unsigned AliaseeValueId =
Record[3];
8001 auto AS = std::make_unique<AliasSummary>(Flags);
8002 LastSeenSummary = AS.get();
8003 AS->setModulePath(ModuleIdMap[ModuleId]);
8005 auto AliaseeVI = std::get<0>(
8006 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8008 auto AliaseeInModule =
8010 AS->setAliasee(AliaseeVI, AliaseeInModule);
8012 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8013 LastSeenGUID =
VI.getGUID();
8019 unsigned ValueID =
Record[0];
8020 uint64_t ModuleId =
Record[1];
8021 uint64_t RawFlags =
Record[2];
8022 unsigned RefArrayStart = 3;
8023 GlobalVarSummary::GVarFlags GVF(
false,
8033 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8035 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8036 LastSeenSummary =
FS.get();
8037 FS->setModulePath(ModuleIdMap[ModuleId]);
8038 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8039 LastSeenGUID =
VI.getGUID();
8045 uint64_t OriginalName =
Record[0];
8046 if (!LastSeenSummary)
8047 return error(
"Name attachment that does not follow a combined record");
8051 LastSeenSummary =
nullptr;
8056 assert(PendingTypeTests.empty());
8061 assert(PendingTypeTestAssumeVCalls.empty());
8062 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8063 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8067 assert(PendingTypeCheckedLoadVCalls.empty());
8068 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8069 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8073 PendingTypeTestAssumeConstVCalls.push_back(
8078 PendingTypeCheckedLoadConstVCalls.push_back(
8084 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8086 static_cast<size_t>(Record[
I + 1]));
8092 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8094 static_cast<size_t>(Record[
I + 1]));
8103 parseTypeIdCompatibleVtableSummaryRecord(Record);
8111 PendingParamAccesses = parseParamAccesses(Record);
8119 StackIds = ArrayRef<uint64_t>(Record);
8125 StackIds.reserve(
Record.size() / 2);
8126 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8127 StackIds.push_back(*R << 32 | *(R + 1));
8132 RadixArray = ArrayRef<uint64_t>(Record);
8137 unsigned ValueID =
Record[0];
8138 SmallVector<unsigned> StackIdList;
8140 assert(R < StackIds.size());
8143 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8144 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8149 auto RecordIter =
Record.begin();
8150 unsigned ValueID = *RecordIter++;
8151 unsigned NumStackIds = *RecordIter++;
8152 unsigned NumVersions = *RecordIter++;
8153 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8154 SmallVector<unsigned> StackIdList;
8155 for (
unsigned J = 0; J < NumStackIds; J++) {
8156 assert(*RecordIter < StackIds.size());
8160 SmallVector<unsigned> Versions;
8161 for (
unsigned J = 0; J < NumVersions; J++)
8163 ValueInfo
VI = std::get<0>(
8164 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8165 PendingCallsites.push_back(
8166 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8174 PendingContextIds.reserve(
Record.size() / 2);
8175 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8176 PendingContextIds.push_back(*R << 32 | *(R + 1));
8182 std::vector<MIBInfo> MIBs;
8183 unsigned NumMIBs = 0;
8186 unsigned MIBsRead = 0;
8187 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8191 auto StackIdList = parseAllocInfoContext(Record,
I);
8192 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8198 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8200 assert(!PendingContextIds.empty() &&
8201 "Missing context ids for alloc sizes");
8202 unsigned ContextIdIndex = 0;
8208 while (MIBsRead++ < NumMIBs) {
8210 unsigned NumContextSizeInfoEntries =
Record[
I++];
8212 std::vector<ContextTotalSize> ContextSizes;
8213 ContextSizes.reserve(NumContextSizeInfoEntries);
8214 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8215 assert(ContextIdIndex < PendingContextIds.size());
8217 if (PendingContextIds[ContextIdIndex] == 0) {
8226 ContextSizes.push_back(
8227 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8229 AllContextSizes.push_back(std::move(ContextSizes));
8231 PendingContextIds.clear();
8233 PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
8234 if (!AllContextSizes.empty()) {
8235 assert(PendingAllocs.back().MIBs.size() == AllContextSizes.size());
8236 PendingAllocs.back().ContextSizeInfos = std::move(AllContextSizes);
8244 std::vector<MIBInfo> MIBs;
8245 unsigned NumMIBs =
Record[
I++];
8246 unsigned NumVersions =
Record[
I++];
8247 unsigned MIBsRead = 0;
8248 while (MIBsRead++ < NumMIBs) {
8251 SmallVector<unsigned> StackIdList;
8253 StackIdList = parseAllocInfoContext(Record,
I);
8254 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8257 SmallVector<uint8_t> Versions;
8258 for (
unsigned J = 0; J < NumVersions; J++)
8261 PendingAllocs.push_back(AllocInfo(std::move(Versions), std::move(MIBs)));
8271Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8275 SmallVector<uint64_t, 64>
Record;
8277 SmallString<128> ModulePath;
8281 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
8284 BitstreamEntry
Entry = MaybeEntry.
get();
8286 switch (
Entry.Kind) {
8289 return error(
"Malformed block");
8298 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
8301 switch (MaybeRecord.
get()) {
8306 uint64_t ModuleId =
Record[0];
8309 return error(
"Invalid code_entry record");
8311 LastSeenModule = TheIndex.
addModule(ModulePath);
8312 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8320 return error(
"Invalid hash length " + Twine(
Record.size()).str());
8321 if (!LastSeenModule)
8322 return error(
"Invalid hash that does not follow a module path");
8324 for (
auto &Val : Record) {
8325 assert(!(Val >> 32) &&
"Unexpected high bits set");
8326 LastSeenModule->
second[Pos++] = Val;
8329 LastSeenModule =
nullptr;
8342class BitcodeErrorCategoryType :
public std::error_category {
8343 const char *
name()
const noexcept
override {
8344 return "llvm.bitcode";
8347 std::string message(
int IE)
const override {
8350 case BitcodeError::CorruptedBitcode:
8351 return "Corrupted bitcode";
8360 static BitcodeErrorCategoryType ErrorCategory;
8361 return ErrorCategory;
8365 unsigned Block,
unsigned RecordID) {
8367 return std::move(Err);
8376 switch (Entry.Kind) {
8381 return error(
"Malformed block");
8385 return std::move(Err);
8395 if (MaybeRecord.
get() == RecordID)
8406Expected<std::vector<BitcodeModule>>
8410 return FOrErr.takeError();
8411 return std::move(FOrErr->Mods);
8436 switch (Entry.Kind) {
8439 return error(
"Malformed block");
8442 uint64_t IdentificationBit = -1ull;
8446 return std::move(Err);
8452 Entry = MaybeEntry.
get();
8457 return error(
"Malformed block");
8463 return std::move(Err);
8482 if (!
I.Strtab.empty())
8489 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8490 F.StrtabForSymtab = *Strtab;
8506 if (
F.Symtab.empty())
8507 F.Symtab = *SymtabOrErr;
8512 return std::move(Err);
8517 return std::move(E);
8532BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8533 bool ShouldLazyLoadMetadata,
bool IsImporting,
8537 std::string ProducerIdentification;
8538 if (IdentificationBit != -1ull) {
8539 if (
Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8540 return std::move(JumpFailed);
8543 return std::move(
E);
8546 if (
Error JumpFailed = Stream.JumpToBit(ModuleBit))
8547 return std::move(JumpFailed);
8548 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8551 std::unique_ptr<Module>
M =
8552 std::make_unique<Module>(ModuleIdentifier,
Context);
8553 M->setMaterializer(R);
8556 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8557 IsImporting, Callbacks))
8558 return std::move(Err);
8560 if (MaterializeAll) {
8562 if (
Error Err =
M->materializeAll())
8563 return std::move(Err);
8566 if (
Error Err =
R->materializeForwardReferencedFunctions())
8567 return std::move(Err);
8570 return std::move(M);
8573Expected<std::unique_ptr<Module>>
8576 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8591 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8592 ModulePath, IsPrevailing);
8593 return R.parseModule();
8600 return std::move(JumpFailed);
8602 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8603 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8604 ModuleIdentifier, 0);
8606 if (
Error Err = R.parseModule())
8607 return std::move(Err);
8609 return std::move(Index);
8615 return std::move(Err);
8621 return std::move(
E);
8623 switch (Entry.Kind) {
8626 return error(
"Malformed block");
8629 return std::make_pair(
false,
false);
8641 switch (MaybeBitCode.
get()) {
8647 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
8649 bool EnableSplitLTOUnit = Flags & 0x8;
8650 bool UnifiedLTO = Flags & 0x200;
8651 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8662 return std::move(JumpFailed);
8665 return std::move(Err);
8670 return std::move(E);
8672 switch (Entry.Kind) {
8674 return error(
"Malformed block");
8685 return Flags.takeError();
8695 return std::move(Err);
8702 return StreamFailed.takeError();
8712 if (MsOrErr->size() != 1)
8713 return error(
"Expected a single module");
8715 return (*MsOrErr)[0];
8718Expected<std::unique_ptr<Module>>
8720 bool ShouldLazyLoadMetadata,
bool IsImporting,
8726 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8731 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
8732 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
8734 IsImporting, Callbacks);
8736 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8742 return getModuleImpl(Context,
true,
false,
false, Callbacks);
8754 return BM->parseModule(Context, Callbacks);
8787 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8796 return BM->getSummary();
8804 return BM->getLTOInfo();
8809 bool IgnoreEmptyThinLTOIndexFile) {
8814 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
AMDGPU Prepare AGPR Alloc
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, bool &HasTailCall)
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
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"))
static AtomicOrdering getDecodedOrdering(unsigned Val)
static std::pair< CalleeInfo::HotnessType, bool > getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)
static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags)
static std::optional< CodeModel::Model > getDecodedCodeModel(unsigned Val)
static void setSpecialRefs(SmallVectorImpl< ValueInfo > &Refs, unsigned ROCnt, unsigned WOCnt)
static bool getDecodedDSOLocal(unsigned Val)
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.
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
static void stripTBAA(Module *M)
static int getDecodedUnaryOpcode(unsigned Val, Type *Ty)
static Expected< std::string > readTriple(BitstreamCursor &Stream)
static void parseWholeProgramDevirtResolutionByArg(ArrayRef< uint64_t > Record, size_t &Slot, WholeProgramDevirtResolution &Wpd)
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags)
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
static Expected< uint64_t > jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
static Expected< bool > hasObjCCategoryInModule(BitstreamCursor &Stream)
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags)
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs, uint64_t AttrIdx)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
static bool hasImplicitComdat(size_t Val)
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream)
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
static void inferDSOLocal(GlobalValue *GV)
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V)
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
static cl::opt< bool > ExpandConstantExprs("expand-constant-exprs", cl::Hidden, cl::desc("Expand constant expressions to instructions for testing purposes"))
static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind)
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
static Expected< std::string > readIdentificationBlock(BitstreamCursor &Stream)
Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the "epoch" encoded in the bit...
static Expected< std::pair< bool, bool > > getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID)
static bool isConstExprSupported(const BitcodeConstant *BC)
static int getDecodedCastOpcode(unsigned Val)
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase)
This file defines the DenseMap class.
Provides ErrorOr<T> smart pointer.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Machine Check Debug Module
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
PowerPC Reduce CR logical Operation
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallString class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Class for arbitrary precision integers.
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
PointerType * getType() const
Overload to return most specific pointer type.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
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.
static bool isValidFailureOrdering(AtomicOrdering Ordering)
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
static bool isTypeAttrKind(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ EndAttrKinds
Sentinel value useful for loops.
LLVM Basic Block Representation.
const Instruction & back() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Represents a module in a bitcode file.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
void push_back(Value *V, unsigned TypeID)
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
void shrinkTo(unsigned N)
unsigned getTypeID(unsigned ValNo) const
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
ArrayRef< uint8_t > getBitcodeBytes() const
Expected< word_t > Read(unsigned NumBits)
Expected< BitstreamEntry > advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Expected< BitstreamEntry > advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block.
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
uint64_t getCurrentByteNo() const
LLVM_ABI Expected< std::optional< BitstreamBlockInfo > > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
bool canSkipToPos(size_t pos) const
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
bool isInlineAsm() const
Check if this call is an inline asm statement.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo createFromIntValue(uint32_t Data)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void emplace(Args &&...A)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
bool isIntPredicate() const
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of array type with a float element type taken from argument ...
static LLVM_ABI 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 LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of vector type with a float element type taken from argument...
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI 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.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
LLVM_ABI bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static DeadOnReturnInfo createFromIntValue(uint64_t Data)
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...
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
Convenience struct for specifying and reasoning about fast-math flags.
void setFast(bool B=true)
void setAllowContract(bool B=true)
void setAllowReciprocal(bool B=true)
void setNoSignedZeros(bool B=true)
void setNoNaNs(bool B=true)
void setAllowReassoc(bool B=true)
Flag setters.
void setApproxFunc(bool B=true)
void setNoInfs(bool B=true)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
BasicBlockListType::iterator iterator
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI 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 LLVM_ABI 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...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
bool hasDefaultVisibility() const
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
bool hasExternalWeakLinkage() const
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
LLVM_ABI void setPartition(StringRef Part)
void setAttributes(AttributeSet A)
Set attribute list for this global.
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
std::vector< ConstraintInfo > ConstraintInfoVector
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
const char * getOpcodeName() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
@ MIN_INT_BITS
Minimum number of bits that can be specified.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
LLVM_ABI StringRef getString() const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
ValueT lookup(const KeyT &Key) const
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static MemoryEffectsBase readOnly()
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase createFromIntValue(uint32_t Data)
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
StringRef saveString(StringRef String)
LLVM_ABI void setFlags(uint64_t Flags)
CfiFunctionIndex & cfiFunctionDecls()
void addBlockCount(uint64_t C)
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
CfiFunctionIndex & cfiFunctionDefs()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
constexpr bool empty() const
empty - Check if the string is empty.
constexpr size_t size() const
size - Get the string size.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
LLVM_ABI 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...
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Triple - Helper class for working with autoconf configuration names.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
Type * getArrayElementType() const
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
const ParentTy * getParent() const
self_iterator getIterator()
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
@ BasicBlock
Various leaf nodes.
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
@ System
Synchronized with respect to all concurrently executing threads.
@ TYPE_CODE_OPAQUE_POINTER
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_CE_INBOUNDS_GEP
@ CST_CODE_INLINEASM_OLD3
@ CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_INLINEASM_OLD2
@ CST_CODE_CE_GEP_WITH_INRANGE
@ VST_CODE_COMBINED_ENTRY
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_INACCESSIBLEMEM_ONLY
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ FUNC_CODE_INST_ATOMICRMW_OLD
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
@ FUNC_CODE_INST_STOREATOMIC_OLD
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_INST_LANDINGPAD_OLD
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_STORE_OLD
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_CMPXCHG_OLD
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
FunctionAddr VTableAddr Value
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
StringMapEntry< Value * > ValueName
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI const std::error_category & BitcodeErrorCategory()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI void UpgradeInlineAsmString(std::string *AsmStr)
Upgrade comment in call to inline asm that represents an objc retain release marker.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
std::error_code make_error_code(BitcodeError E)
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto uninitialized_copy(R &&Src, IterTy Dst)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
LLVM_ABI void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
FunctionAddr VTableAddr uintptr_t uintptr_t Version
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
auto reverse(ContainerTy &&C)
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI std::string UpgradeDataLayoutString(StringRef DL, StringRef Triple)
Upgrade the datalayout string by adding a section for address space pointers.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ ArgMem
Access to memory via argument pointers.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
LLVM_ABI 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...
MaybeAlign decodeMaybeAlign(unsigned Value)
Dual operation of the encode function above.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
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...
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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
LLVM_ABI void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
LLVM_ABI 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,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Basic information extracted from a bitcode module to be used for LTO.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const char * BranchWeights
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
std::optional< DataLayoutCallbackFuncTy > DataLayout
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
Kind
Specifies which kind of type check we should emit for this byte array.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName