24#include "llvm/Config/llvm-config.h"
54#include "llvm/IR/IntrinsicsAArch64.h"
55#include "llvm/IR/IntrinsicsARM.h"
88#include <system_error>
98 "Print the global id for each value when reading the module summary"));
103 "Expand constant expressions to instructions for testing purposes"));
108 SWITCH_INST_MAGIC = 0x4B5
121 "file too small to contain bitcode header");
122 for (
unsigned C : {
'B',
'C'})
126 "file doesn't start with bitcode header");
128 return Res.takeError();
129 for (
unsigned C : {0x0, 0xC, 0xE, 0xD})
133 "file doesn't start with bitcode header");
135 return Res.takeError();
140 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
141 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
144 return error(
"Invalid bitcode signature");
150 return error(
"Invalid bitcode wrapper header");
154 return std::move(Err);
156 return std::move(Stream);
160template <
typename StrTy>
173 if (
F.isMaterializable())
176 I.setMetadata(LLVMContext::MD_tbaa,
nullptr);
184 return std::move(Err);
189 std::string ProducerIdentification;
196 switch (Entry.Kind) {
199 return error(
"Malformed block");
201 return ProducerIdentification;
212 switch (MaybeBitCode.
get()) {
214 return error(
"Invalid value");
222 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
241 switch (Entry.Kind) {
244 return error(
"Malformed block");
252 return std::move(Err);
264 return std::move(Err);
275 switch (Entry.Kind) {
278 return error(
"Malformed block");
290 switch (MaybeRecord.
get()) {
296 return error(
"Invalid section name record");
301 Segment = Segment.trim();
302 Section = Section.trim();
304 if (Segment ==
"__DATA" && Section.starts_with(
"__objc_catlist"))
306 if (Segment ==
"__OBJC" && Section.starts_with(
"__category"))
308 if (Segment ==
"__TEXT" && Section.starts_with(
"__swift"))
326 switch (Entry.Kind) {
328 return error(
"Malformed block");
338 return std::move(Err);
351 return std::move(Err);
364 switch (Entry.Kind) {
367 return error(
"Malformed block");
379 switch (MaybeRecord.
get()) {
384 return error(
"Invalid triple record");
403 switch (Entry.Kind) {
405 return error(
"Malformed block");
415 return std::move(Err);
422 return Skipped.takeError();
429class BitcodeReaderBase {
431 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
432 : Stream(std::
move(Stream)), Strtab(Strtab) {
433 this->Stream.setBlockInfo(&BlockInfo);
436 BitstreamBlockInfo BlockInfo;
437 BitstreamCursor Stream;
442 bool UseStrtab =
false;
444 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
449 std::pair<StringRef, ArrayRef<uint64_t>>
450 readNameFromStrtab(ArrayRef<uint64_t> Record);
452 Error readBlockInfo();
455 std::string ProducerIdentification;
462Error BitcodeReaderBase::error(
const Twine &Message) {
463 std::string FullMsg = Message.
str();
464 if (!ProducerIdentification.empty())
465 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
466 LLVM_VERSION_STRING
"')";
467 return ::error(FullMsg);
471BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
473 return error(
"Invalid version record");
474 unsigned ModuleVersion =
Record[0];
475 if (ModuleVersion > 2)
476 return error(
"Invalid value");
477 UseStrtab = ModuleVersion >= 2;
478 return ModuleVersion;
481std::pair<StringRef, ArrayRef<uint64_t>>
482BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
486 if (Record[0] + Record[1] > Strtab.
size())
488 return {StringRef(Strtab.
data() + Record[0], Record[1]),
Record.slice(2)};
499class BitcodeConstant final :
public Value,
500 TrailingObjects<BitcodeConstant, unsigned> {
501 friend TrailingObjects;
504 static constexpr uint8_t SubclassID = 255;
512 static constexpr uint8_t ConstantStructOpcode = 255;
513 static constexpr uint8_t ConstantArrayOpcode = 254;
514 static constexpr uint8_t ConstantVectorOpcode = 253;
515 static constexpr uint8_t NoCFIOpcode = 252;
516 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
517 static constexpr uint8_t BlockAddressOpcode = 250;
518 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
519 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
526 unsigned BlockAddressBB = 0;
527 Type *SrcElemTy =
nullptr;
528 std::optional<ConstantRange>
InRange;
530 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0,
Type *SrcElemTy =
nullptr,
531 std::optional<ConstantRange>
InRange = std::nullopt)
532 : Opcode(Opcode),
Flags(
Flags), SrcElemTy(SrcElemTy),
535 ExtraInfo(uint8_t Opcode, uint8_t Flags,
unsigned BlockAddressBB)
536 : Opcode(Opcode),
Flags(
Flags), BlockAddressBB(BlockAddressBB) {}
541 unsigned NumOperands;
542 unsigned BlockAddressBB;
544 std::optional<ConstantRange>
InRange;
547 BitcodeConstant(
Type *Ty,
const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
549 NumOperands(OpIDs.
size()), BlockAddressBB(
Info.BlockAddressBB),
554 BitcodeConstant &operator=(
const BitcodeConstant &) =
delete;
558 const ExtraInfo &Info,
559 ArrayRef<unsigned> OpIDs) {
560 void *Mem =
A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.
size()),
561 alignof(BitcodeConstant));
562 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
565 static bool classof(
const Value *V) {
return V->getValueID() == SubclassID; }
567 ArrayRef<unsigned> getOperandIDs()
const {
568 return ArrayRef(getTrailingObjects(), NumOperands);
571 std::optional<ConstantRange> getInRange()
const {
572 assert(Opcode == Instruction::GetElementPtr);
581class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
583 Module *TheModule =
nullptr;
584 std::optional<Triple> TargetTriple;
589 bool SeenValueSymbolTable =
false;
592 std::vector<std::string> SectionTable;
593 std::vector<std::string> GCTable;
595 std::vector<Type *> TypeList;
599 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
606 DenseMap<std::pair<Type *, unsigned>,
unsigned> VirtualTypeIDs;
607 DenseMap<Function *, unsigned> FunctionTypeIDs;
612 BitcodeReaderValueList ValueList;
613 std::optional<MetadataLoader> MDLoader;
614 std::vector<Comdat *> ComdatList;
615 DenseSet<GlobalObject *> ImplicitComdatObjects;
618 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
619 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
621 struct FunctionOperandInfo {
623 unsigned PersonalityFn;
627 std::vector<FunctionOperandInfo> FunctionOperands;
631 std::vector<AttributeList> MAttributes;
634 std::map<unsigned, AttributeList> MAttributeGroups;
638 std::vector<BasicBlock*> FunctionBBs;
642 std::vector<Function*> FunctionsWithBodies;
646 DenseMap<Function *, Function *> UpgradedIntrinsics;
651 bool SeenFirstFunctionBody =
false;
655 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
660 std::vector<uint64_t> DeferredMetadataInfo;
665 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
666 std::deque<Function *> BasicBlockFwdRefQueue;
673 std::vector<Function *> BackwardRefFunctions;
681 bool UseRelativeIDs =
false;
685 bool WillMaterializeAllForwardRefs =
false;
689 bool SeenDebugIntrinsic =
false;
690 bool SeenDebugRecord =
false;
693 TBAAVerifier TBAAVerifyHelper;
695 std::vector<std::string> BundleTags;
698 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
701 std::vector<GlobalValue::GUID> GUIDList;
707 bool SkipDebugIntrinsicUpgrade =
false;
710 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
711 StringRef ProducerIdentification, LLVMContext &
Context);
713 Error materializeForwardReferencedFunctions();
715 Error materialize(GlobalValue *GV)
override;
716 Error materializeModule()
override;
717 std::vector<StructType *> getIdentifiedStructTypes()
const override;
721 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
722 bool IsImporting, ParserCallbacks Callbacks = {});
727 Error materializeMetadata()
override;
729 void setStripDebugInfo()
override;
732 std::vector<StructType *> IdentifiedStructTypes;
733 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
734 StructType *createIdentifiedStructType(LLVMContext &
Context);
736 static constexpr unsigned InvalidTypeID = ~0
u;
738 Type *getTypeByID(
unsigned ID);
739 Type *getPtrElementTypeByID(
unsigned ID);
740 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
741 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
744 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
745 Expected<Constant *> getValueForInitializer(
unsigned ID);
747 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
748 BasicBlock *ConstExprInsertBB) {
754 Metadata *getFnMetadataByID(
unsigned ID) {
755 return MDLoader->getMetadataFwdRefOrLoad(ID);
758 BasicBlock *getBasicBlock(
unsigned ID)
const {
759 if (ID >= FunctionBBs.size())
return nullptr;
760 return FunctionBBs[
ID];
764 if (i-1 < MAttributes.size())
765 return MAttributes[i-1];
766 return AttributeList();
772 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
773 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
774 BasicBlock *ConstExprInsertBB) {
775 if (Slot ==
Record.size())
return true;
776 unsigned ValNo = (unsigned)Record[Slot++];
779 ValNo = InstNum - ValNo;
780 if (ValNo < InstNum) {
784 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
786 "Incorrect type ID stored for value");
787 return ResVal ==
nullptr;
789 if (Slot ==
Record.size())
792 TypeID = (unsigned)Record[Slot++];
793 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
795 return ResVal ==
nullptr;
798 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
799 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
800 BasicBlock *ConstExprInsertBB) {
801 if (Slot ==
Record.size())
806 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
809 if (Slot ==
Record.size())
811 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
819 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
820 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
821 BasicBlock *ConstExprInsertBB) {
822 if (
getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
830 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
831 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
832 BasicBlock *ConstExprInsertBB) {
833 ResVal =
getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
834 return ResVal ==
nullptr;
839 Value *
getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
840 unsigned InstNum,
Type *Ty,
unsigned TyID,
841 BasicBlock *ConstExprInsertBB) {
842 if (Slot ==
Record.size())
return nullptr;
843 unsigned ValNo = (unsigned)Record[Slot];
846 ValNo = InstNum - ValNo;
847 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
851 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
852 unsigned InstNum,
Type *Ty,
unsigned TyID,
853 BasicBlock *ConstExprInsertBB) {
854 if (Slot ==
Record.size())
return nullptr;
855 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
858 ValNo = InstNum - ValNo;
859 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
862 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
865 if (
Record.size() - OpNum < 2)
866 return error(
"Too few records for range");
868 unsigned LowerActiveWords =
Record[OpNum];
869 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
870 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
871 return error(
"Too few records for range");
874 OpNum += LowerActiveWords;
877 OpNum += UpperActiveWords;
880 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
881 int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
882 return ConstantRange(APInt(
BitWidth, Start,
true),
887 Expected<ConstantRange>
888 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
889 if (
Record.size() - OpNum < 1)
890 return error(
"Too few records for range");
892 return readConstantRange(Record, OpNum,
BitWidth);
896 const Triple &getTargetTriple() {
898 BitstreamCursor TripleStream(Stream.getBitcodeBytes());
899 if (Expected<std::string> TripleStr =
readTriple(TripleStream))
900 TargetTriple.emplace(std::move(*TripleStr));
903 TargetTriple.emplace();
906 return *TargetTriple;
912 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
918 Error parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind);
920 ParserCallbacks Callbacks = {});
922 Error parseComdatRecord(ArrayRef<uint64_t> Record);
923 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
924 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
925 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
926 ArrayRef<uint64_t> Record);
928 Error parseAttributeBlock();
929 Error parseAttributeGroupBlock();
930 Error parseTypeTable();
931 Error parseTypeTableBody();
932 Error parseOperandBundleTags();
933 Error parseSyncScopeNames();
935 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
936 unsigned NameIndex, Triple &TT);
937 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
Function *
F,
938 ArrayRef<uint64_t> Record);
940 Error parseGlobalValueSymbolTable();
941 Error parseConstants();
942 Error rememberAndSkipFunctionBodies();
943 Error rememberAndSkipFunctionBody();
945 Error rememberAndSkipMetadata();
948 Error globalCleanup();
949 Error resolveGlobalAndIndirectSymbolInits();
950 Error parseUseLists();
951 Error findFunctionInStream(
953 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
960class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
962 ModuleSummaryIndex &TheIndex;
966 bool SeenGlobalValSummary =
false;
969 bool SeenValueSymbolTable =
false;
983 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
984 ValueIdToValueInfoMap;
990 DenseMap<uint64_t, StringRef> ModuleIdMap;
993 std::string SourceFileName;
997 StringRef ModulePath;
1001 std::function<bool(StringRef)> IsPrevailing =
nullptr;
1004 std::function<void(ValueInfo)> OnValueInfo =
nullptr;
1008 std::vector<uint64_t> StackIds;
1012 std::vector<uint64_t> RadixArray;
1017 std::vector<unsigned> StackIdToIndex;
1020 std::vector<uint64_t> DefinedGUIDs;
1023 ModuleSummaryIndexBitcodeReader(
1024 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
1025 StringRef ModulePath,
1026 std::function<
bool(StringRef)> IsPrevailing =
nullptr,
1027 std::function<
void(ValueInfo)> OnValueInfo =
nullptr);
1034 StringRef SourceFileName);
1035 Error parseValueSymbolTable(
1037 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1040 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1041 bool HasProfile,
bool HasRelBF);
1042 Error parseEntireSummary(
unsigned ID);
1043 Error parseModuleStringTable();
1044 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1045 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1047 std::vector<FunctionSummary::ParamAccess>
1048 parseParamAccesses(ArrayRef<uint64_t> Record);
1049 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1053 static constexpr unsigned UninitializedStackIdIndex =
1054 std::numeric_limits<unsigned>::max();
1056 unsigned getStackIdIndex(
unsigned LocalIndex) {
1057 unsigned &
Index = StackIdToIndex[LocalIndex];
1060 if (Index == UninitializedStackIdIndex)
1065 template <
bool AllowNullValueInfo = false>
1066 std::pair<ValueInfo, GlobalValue::GUID>
1067 getValueInfoFromValueId(
unsigned ValueId);
1069 void addThisModule();
1085 return std::error_code();
1091 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1092 ValueList(this->Stream.SizeInBytes(),
1094 return materializeValue(
ValID, InsertBB);
1096 this->ProducerIdentification = std::string(ProducerIdentification);
1099Error BitcodeReader::materializeForwardReferencedFunctions() {
1100 if (WillMaterializeAllForwardRefs)
1104 WillMaterializeAllForwardRefs =
true;
1106 while (!BasicBlockFwdRefQueue.empty()) {
1107 Function *
F = BasicBlockFwdRefQueue.front();
1108 BasicBlockFwdRefQueue.pop_front();
1109 assert(
F &&
"Expected valid function");
1110 if (!BasicBlockFwdRefs.
count(
F))
1118 if (!
F->isMaterializable())
1119 return error(
"Never resolved function from blockaddress");
1122 if (
Error Err = materialize(
F))
1125 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1127 for (
Function *
F : BackwardRefFunctions)
1128 if (
Error Err = materialize(
F))
1130 BackwardRefFunctions.clear();
1133 WillMaterializeAllForwardRefs =
false;
1198 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1199 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1200 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1201 Flags.NoInline = (RawFlags >> 4) & 0x1;
1202 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1203 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1204 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1205 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1206 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1222 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1);
1223 RawFlags = RawFlags >> 4;
1224 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1228 bool Live = (RawFlags & 0x2) || Version < 3;
1229 bool Local = (RawFlags & 0x4);
1230 bool AutoHide = (RawFlags & 0x8);
1233 Live,
Local, AutoHide, IK,
1234 NoRenameOnPromotion);
1240 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1241 (RawFlags & 0x4) ?
true :
false,
1245static std::pair<CalleeInfo::HotnessType, bool>
1249 bool HasTailCall = (RawFlags & 0x8);
1250 return {Hotness, HasTailCall};
1255 bool &HasTailCall) {
1256 static constexpr unsigned RelBlockFreqBits = 28;
1257 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1258 RelBF = RawFlags & RelBlockFreqMask;
1259 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1284 case 0:
return false;
1285 case 1:
return true;
1347 bool IsFP = Ty->isFPOrFPVectorTy();
1349 if (!IsFP && !Ty->isIntOrIntVectorTy())
1356 return IsFP ? Instruction::FNeg : -1;
1361 bool IsFP = Ty->isFPOrFPVectorTy();
1363 if (!IsFP && !Ty->isIntOrIntVectorTy())
1370 return IsFP ? Instruction::FAdd : Instruction::Add;
1372 return IsFP ? Instruction::FSub : Instruction::Sub;
1374 return IsFP ? Instruction::FMul : Instruction::Mul;
1376 return IsFP ? -1 : Instruction::UDiv;
1378 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1380 return IsFP ? -1 : Instruction::URem;
1382 return IsFP ? Instruction::FRem : Instruction::SRem;
1384 return IsFP ? -1 : Instruction::Shl;
1386 return IsFP ? -1 : Instruction::LShr;
1388 return IsFP ? -1 : Instruction::AShr;
1390 return IsFP ? -1 : Instruction::And;
1392 return IsFP ? -1 : Instruction::Or;
1394 return IsFP ? -1 : Instruction::Xor;
1399 bool &IsElementwise) {
1497Type *BitcodeReader::getTypeByID(
unsigned ID) {
1499 if (ID >= TypeList.size())
1502 if (
Type *Ty = TypeList[ID])
1507 return TypeList[
ID] = createIdentifiedStructType(
Context);
1510unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1511 auto It = ContainedTypeIDs.
find(ID);
1512 if (It == ContainedTypeIDs.
end())
1513 return InvalidTypeID;
1515 if (Idx >= It->second.size())
1516 return InvalidTypeID;
1518 return It->second[Idx];
1521Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1522 if (ID >= TypeList.size())
1529 return getTypeByID(getContainedTypeID(ID, 0));
1532unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1533 ArrayRef<unsigned> ChildTypeIDs) {
1534 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1535 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1536 auto It = VirtualTypeIDs.
find(CacheKey);
1537 if (It != VirtualTypeIDs.
end()) {
1543 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1544 "Incorrect cached contained type IDs");
1548 unsigned TypeID = TypeList.size();
1549 TypeList.push_back(Ty);
1550 if (!ChildTypeIDs.
empty())
1571 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1585 if (Opcode == Instruction::GetElementPtr)
1589 case Instruction::FNeg:
1590 case Instruction::Select:
1591 case Instruction::ICmp:
1592 case Instruction::FCmp:
1599Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1600 BasicBlock *InsertBB) {
1602 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1604 return ValueList[StartValID];
1606 SmallDenseMap<unsigned, Value *> MaterializedValues;
1607 SmallVector<unsigned> Worklist;
1609 while (!Worklist.
empty()) {
1610 unsigned ValID = Worklist.
back();
1611 if (MaterializedValues.
count(ValID)) {
1617 if (ValID >= ValueList.
size() || !ValueList[ValID])
1618 return error(
"Invalid value ID");
1620 Value *
V = ValueList[ValID];
1623 MaterializedValues.
insert({ValID,
V});
1631 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1632 auto It = MaterializedValues.
find(OpID);
1633 if (It != MaterializedValues.
end())
1634 Ops.push_back(It->second);
1641 if (
Ops.size() != BC->getOperandIDs().size())
1643 std::reverse(
Ops.begin(),
Ops.end());
1660 switch (BC->Opcode) {
1661 case BitcodeConstant::ConstantPtrAuthOpcode: {
1664 return error(
"ptrauth key operand must be ConstantInt");
1668 return error(
"ptrauth disc operand must be ConstantInt");
1671 ConstOps.
size() > 4 ? ConstOps[4]
1676 "ptrauth deactivation symbol operand must be a pointer");
1679 DeactivationSymbol);
1682 case BitcodeConstant::NoCFIOpcode: {
1685 return error(
"no_cfi operand must be GlobalValue");
1689 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1692 return error(
"dso_local operand must be GlobalValue");
1696 case BitcodeConstant::BlockAddressOpcode: {
1699 return error(
"blockaddress operand must be a function");
1704 unsigned BBID = BC->BlockAddressBB;
1707 return error(
"Invalid ID");
1710 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1712 return error(
"Invalid ID");
1719 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1721 BasicBlockFwdRefQueue.push_back(Fn);
1722 if (FwdBBs.size() < BBID + 1)
1723 FwdBBs.resize(BBID + 1);
1731 case BitcodeConstant::ConstantStructOpcode: {
1733 if (
ST->getNumElements() != ConstOps.
size())
1734 return error(
"Invalid number of elements in struct initializer");
1736 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1737 if (
Op->getType() != Ty)
1738 return error(
"Incorrect type in struct initializer");
1743 case BitcodeConstant::ConstantArrayOpcode: {
1745 if (AT->getNumElements() != ConstOps.
size())
1746 return error(
"Invalid number of elements in array initializer");
1748 for (Constant *
Op : ConstOps)
1749 if (
Op->getType() != AT->getElementType())
1750 return error(
"Incorrect type in array initializer");
1755 case BitcodeConstant::ConstantVectorOpcode: {
1757 if (VT->getNumElements() != ConstOps.size())
1758 return error(
"Invalid number of elements in vector initializer");
1760 for (Constant *
Op : ConstOps)
1761 if (
Op->getType() != VT->getElementType())
1762 return error(
"Incorrect type in vector initializer");
1767 case Instruction::GetElementPtr:
1769 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1772 case Instruction::ExtractElement:
1775 case Instruction::InsertElement:
1779 case Instruction::ShuffleVector: {
1780 SmallVector<int, 16>
Mask;
1792 MaterializedValues.
insert({ValID,
C});
1798 return error(Twine(
"Value referenced by initializer is an unsupported "
1799 "constant expression of type ") +
1800 BC->getOpcodeName());
1806 BC->getType(),
"constexpr", InsertBB);
1809 "constexpr", InsertBB);
1812 Ops[1],
"constexpr", InsertBB);
1815 I->setHasNoSignedWrap();
1817 I->setHasNoUnsignedWrap();
1823 switch (BC->Opcode) {
1824 case BitcodeConstant::ConstantVectorOpcode: {
1825 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1828 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1835 case BitcodeConstant::ConstantStructOpcode:
1836 case BitcodeConstant::ConstantArrayOpcode: {
1840 "constexpr.ins", InsertBB);
1844 case Instruction::ICmp:
1845 case Instruction::FCmp:
1848 "constexpr", InsertBB);
1850 case Instruction::GetElementPtr:
1856 case Instruction::Select:
1859 case Instruction::ExtractElement:
1862 case Instruction::InsertElement:
1866 case Instruction::ShuffleVector:
1867 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1875 MaterializedValues.
insert({ValID,
I});
1879 return MaterializedValues[StartValID];
1882Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1883 Expected<Value *> MaybeV = materializeValue(ID,
nullptr);
1891StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1894 IdentifiedStructTypes.push_back(Ret);
1898StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1900 IdentifiedStructTypes.push_back(Ret);
1916 case Attribute::ZExt:
return 1 << 0;
1917 case Attribute::SExt:
return 1 << 1;
1918 case Attribute::NoReturn:
return 1 << 2;
1919 case Attribute::InReg:
return 1 << 3;
1920 case Attribute::StructRet:
return 1 << 4;
1921 case Attribute::NoUnwind:
return 1 << 5;
1922 case Attribute::NoAlias:
return 1 << 6;
1923 case Attribute::ByVal:
return 1 << 7;
1924 case Attribute::Nest:
return 1 << 8;
1925 case Attribute::ReadNone:
return 1 << 9;
1926 case Attribute::ReadOnly:
return 1 << 10;
1927 case Attribute::NoInline:
return 1 << 11;
1928 case Attribute::AlwaysInline:
return 1 << 12;
1929 case Attribute::OptimizeForSize:
return 1 << 13;
1930 case Attribute::StackProtect:
return 1 << 14;
1931 case Attribute::StackProtectReq:
return 1 << 15;
1932 case Attribute::Alignment:
return 31 << 16;
1934 case Attribute::NoRedZone:
return 1 << 22;
1935 case Attribute::NoImplicitFloat:
return 1 << 23;
1936 case Attribute::Naked:
return 1 << 24;
1937 case Attribute::InlineHint:
return 1 << 25;
1938 case Attribute::StackAlignment:
return 7 << 26;
1939 case Attribute::ReturnsTwice:
return 1 << 29;
1940 case Attribute::UWTable:
return 1 << 30;
1941 case Attribute::NonLazyBind:
return 1U << 31;
1942 case Attribute::SanitizeAddress:
return 1ULL << 32;
1943 case Attribute::MinSize:
return 1ULL << 33;
1944 case Attribute::NoDuplicate:
return 1ULL << 34;
1945 case Attribute::StackProtectStrong:
return 1ULL << 35;
1946 case Attribute::SanitizeThread:
return 1ULL << 36;
1947 case Attribute::SanitizeMemory:
return 1ULL << 37;
1948 case Attribute::NoBuiltin:
return 1ULL << 38;
1949 case Attribute::Returned:
return 1ULL << 39;
1950 case Attribute::Cold:
return 1ULL << 40;
1951 case Attribute::Builtin:
return 1ULL << 41;
1952 case Attribute::OptimizeNone:
return 1ULL << 42;
1953 case Attribute::InAlloca:
return 1ULL << 43;
1954 case Attribute::NonNull:
return 1ULL << 44;
1955 case Attribute::JumpTable:
return 1ULL << 45;
1956 case Attribute::Convergent:
return 1ULL << 46;
1957 case Attribute::SafeStack:
return 1ULL << 47;
1958 case Attribute::NoRecurse:
return 1ULL << 48;
1961 case Attribute::SwiftSelf:
return 1ULL << 51;
1962 case Attribute::SwiftError:
return 1ULL << 52;
1963 case Attribute::WriteOnly:
return 1ULL << 53;
1964 case Attribute::Speculatable:
return 1ULL << 54;
1965 case Attribute::StrictFP:
return 1ULL << 55;
1966 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1967 case Attribute::NoCfCheck:
return 1ULL << 57;
1968 case Attribute::OptForFuzzing:
return 1ULL << 58;
1969 case Attribute::ShadowCallStack:
return 1ULL << 59;
1970 case Attribute::SpeculativeLoadHardening:
1972 case Attribute::ImmArg:
1974 case Attribute::WillReturn:
1976 case Attribute::NoFree:
1992 if (
I == Attribute::Alignment)
1993 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1994 else if (
I == Attribute::StackAlignment)
1995 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1997 B.addTypeAttr(
I,
nullptr);
2011 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
2013 "Alignment must be a power of two.");
2016 B.addAlignmentAttr(Alignment);
2018 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
2019 (EncodedAttrs & 0xffff);
2021 if (AttrIdx == AttributeList::FunctionIndex) {
2024 if (Attrs & (1ULL << 9)) {
2026 Attrs &= ~(1ULL << 9);
2029 if (Attrs & (1ULL << 10)) {
2031 Attrs &= ~(1ULL << 10);
2034 if (Attrs & (1ULL << 49)) {
2036 Attrs &= ~(1ULL << 49);
2039 if (Attrs & (1ULL << 50)) {
2041 Attrs &= ~(1ULL << 50);
2044 if (Attrs & (1ULL << 53)) {
2046 Attrs &= ~(1ULL << 53);
2050 B.addMemoryAttr(ME);
2054 if (Attrs & (1ULL << 21)) {
2055 Attrs &= ~(1ULL << 21);
2062Error BitcodeReader::parseAttributeBlock() {
2066 if (!MAttributes.empty())
2067 return error(
"Invalid multiple blocks");
2069 SmallVector<uint64_t, 64>
Record;
2078 BitstreamEntry
Entry = MaybeEntry.
get();
2080 switch (
Entry.Kind) {
2083 return error(
"Malformed block");
2096 switch (MaybeRecord.
get()) {
2102 return error(
"Invalid parameter attribute record");
2104 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2110 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2115 Attrs.push_back(MAttributeGroups[Val]);
2117 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2130 return Attribute::Alignment;
2132 return Attribute::AlwaysInline;
2134 return Attribute::Builtin;
2136 return Attribute::ByVal;
2138 return Attribute::InAlloca;
2140 return Attribute::Cold;
2142 return Attribute::Convergent;
2144 return Attribute::DisableSanitizerInstrumentation;
2146 return Attribute::ElementType;
2148 return Attribute::FnRetThunkExtern;
2150 return Attribute::Flatten;
2152 return Attribute::HybridPatchable;
2154 return Attribute::InlineHint;
2156 return Attribute::InReg;
2158 return Attribute::JumpTable;
2160 return Attribute::Memory;
2162 return Attribute::NoFPClass;
2164 return Attribute::MinSize;
2166 return Attribute::Naked;
2168 return Attribute::Nest;
2170 return Attribute::NoAlias;
2172 return Attribute::NoBuiltin;
2174 return Attribute::NoCallback;
2176 return Attribute::NoDivergenceSource;
2178 return Attribute::NoDuplicate;
2180 return Attribute::NoFree;
2182 return Attribute::NoFreeObj;
2184 return Attribute::NoImplicitFloat;
2186 return Attribute::NoInline;
2188 return Attribute::NoRecurse;
2190 return Attribute::NoMerge;
2192 return Attribute::NonLazyBind;
2194 return Attribute::NonNull;
2196 return Attribute::Dereferenceable;
2198 return Attribute::DereferenceableOrNull;
2200 return Attribute::AllocAlign;
2202 return Attribute::AllocKind;
2204 return Attribute::AllocSize;
2206 return Attribute::AllocatedPointer;
2208 return Attribute::NoRedZone;
2210 return Attribute::NoReturn;
2212 return Attribute::NoSync;
2214 return Attribute::NoCfCheck;
2216 return Attribute::NoProfile;
2218 return Attribute::SkipProfile;
2220 return Attribute::NoUnwind;
2222 return Attribute::NoSanitizeBounds;
2224 return Attribute::NoSanitizeCoverage;
2226 return Attribute::NullPointerIsValid;
2228 return Attribute::OptimizeForDebugging;
2230 return Attribute::OptForFuzzing;
2232 return Attribute::OptimizeForSize;
2234 return Attribute::OptimizeNone;
2236 return Attribute::ReadNone;
2238 return Attribute::ReadOnly;
2240 return Attribute::Returned;
2242 return Attribute::ReturnsTwice;
2244 return Attribute::SExt;
2246 return Attribute::Speculatable;
2248 return Attribute::StackAlignment;
2250 return Attribute::StackProtect;
2252 return Attribute::StackProtectReq;
2254 return Attribute::StackProtectStrong;
2256 return Attribute::SafeStack;
2258 return Attribute::ShadowCallStack;
2260 return Attribute::StrictFP;
2262 return Attribute::StructRet;
2264 return Attribute::SanitizeAddress;
2266 return Attribute::SanitizeHWAddress;
2268 return Attribute::SanitizeThread;
2270 return Attribute::SanitizeType;
2272 return Attribute::SanitizeMemory;
2274 return Attribute::SanitizeNumericalStability;
2276 return Attribute::SanitizeRealtime;
2278 return Attribute::SanitizeRealtimeBlocking;
2280 return Attribute::SanitizeAllocToken;
2282 return Attribute::SpeculativeLoadHardening;
2284 return Attribute::SwiftError;
2286 return Attribute::SwiftSelf;
2288 return Attribute::SwiftAsync;
2290 return Attribute::UWTable;
2292 return Attribute::VScaleRange;
2294 return Attribute::WillReturn;
2296 return Attribute::WriteOnly;
2298 return Attribute::ZExt;
2300 return Attribute::ImmArg;
2302 return Attribute::SanitizeMemTag;
2304 return Attribute::Preallocated;
2306 return Attribute::NoUndef;
2308 return Attribute::ByRef;
2310 return Attribute::MustProgress;
2312 return Attribute::Hot;
2314 return Attribute::PresplitCoroutine;
2316 return Attribute::Writable;
2318 return Attribute::CoroDestroyOnlyWhenComplete;
2320 return Attribute::DeadOnUnwind;
2322 return Attribute::Range;
2324 return Attribute::Initializes;
2326 return Attribute::CoroElideSafe;
2328 return Attribute::NoExt;
2330 return Attribute::Captures;
2332 return Attribute::DeadOnReturn;
2334 return Attribute::NoCreateUndefOrPoison;
2336 return Attribute::DenormalFPEnv;
2338 return Attribute::NoOutline;
2340 return Attribute::NoIPA;
2345 MaybeAlign &Alignment) {
2348 if (
Exponent > Value::MaxAlignmentExponent + 1)
2349 return error(
"Invalid alignment value");
2354Error BitcodeReader::parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind) {
2356 if (*Kind == Attribute::None)
2357 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2362 switch (EncodedKind) {
2386Error BitcodeReader::parseAttributeGroupBlock() {
2390 if (!MAttributeGroups.empty())
2391 return error(
"Invalid multiple blocks");
2393 SmallVector<uint64_t, 64>
Record;
2400 BitstreamEntry
Entry = MaybeEntry.
get();
2402 switch (
Entry.Kind) {
2405 return error(
"Malformed block");
2418 switch (MaybeRecord.
get()) {
2423 return error(
"Invalid grp record");
2430 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2431 if (Record[i] == 0) {
2432 Attribute::AttrKind
Kind;
2434 if (Idx == AttributeList::FunctionIndex &&
2443 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2449 if (Kind == Attribute::ByVal)
2450 B.addByValAttr(
nullptr);
2451 else if (Kind == Attribute::StructRet)
2452 B.addStructRetAttr(
nullptr);
2453 else if (Kind == Attribute::InAlloca)
2454 B.addInAllocaAttr(
nullptr);
2455 else if (Kind == Attribute::UWTable)
2456 B.addUWTableAttr(UWTableKind::Default);
2457 else if (Kind == Attribute::DeadOnReturn)
2458 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2459 else if (Attribute::isEnumAttrKind(Kind))
2460 B.addAttribute(Kind);
2462 return error(
"Not an enum attribute");
2463 }
else if (Record[i] == 1) {
2464 Attribute::AttrKind
Kind;
2465 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2467 if (!Attribute::isIntAttrKind(Kind))
2468 return error(
"Not an int attribute");
2469 if (Kind == Attribute::Alignment)
2470 B.addAlignmentAttr(Record[++i]);
2471 else if (Kind == Attribute::StackAlignment)
2472 B.addStackAlignmentAttr(Record[++i]);
2473 else if (Kind == Attribute::Dereferenceable)
2474 B.addDereferenceableAttr(Record[++i]);
2475 else if (Kind == Attribute::DereferenceableOrNull)
2476 B.addDereferenceableOrNullAttr(Record[++i]);
2477 else if (Kind == Attribute::DeadOnReturn)
2478 B.addDeadOnReturnAttr(
2480 else if (Kind == Attribute::AllocSize)
2481 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2482 else if (Kind == Attribute::VScaleRange)
2483 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2484 else if (Kind == Attribute::UWTable)
2486 else if (Kind == Attribute::AllocKind)
2487 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2488 else if (Kind == Attribute::Memory) {
2490 const uint8_t
Version = (EncodedME >> 56);
2504 if (getTargetTriple().isAArch64())
2509 B.addMemoryAttr(ME);
2514 EncodedME & 0x00FFFFFFFFFFFFFFULL);
2517 if (
Version == 1 && getTargetTriple().isAArch64())
2519 IRMemLocation::TargetMem0,
2520 ME.
getModRef(IRMemLocation::InaccessibleMem)) |
2522 IRMemLocation::TargetMem1,
2523 ME.
getModRef(IRMemLocation::InaccessibleMem));
2524 B.addMemoryAttr(ME);
2526 }
else if (Kind == Attribute::Captures)
2528 else if (Kind == Attribute::NoFPClass)
2531 else if (Kind == Attribute::DenormalFPEnv) {
2532 B.addDenormalFPEnvAttr(
2535 }
else if (Record[i] == 3 || Record[i] == 4) {
2537 SmallString<64> KindStr;
2538 SmallString<64> ValStr;
2540 while (Record[i] != 0 && i != e)
2542 assert(Record[i] == 0 &&
"Kind string not null terminated");
2547 while (Record[i] != 0 && i != e)
2549 assert(Record[i] == 0 &&
"Value string not null terminated");
2552 B.addAttribute(KindStr.
str(), ValStr.
str());
2553 }
else if (Record[i] == 5 || Record[i] == 6) {
2554 bool HasType =
Record[i] == 6;
2555 Attribute::AttrKind
Kind;
2556 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2558 if (!Attribute::isTypeAttrKind(Kind))
2559 return error(
"Not a type attribute");
2561 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2562 }
else if (Record[i] == 7) {
2563 Attribute::AttrKind
Kind;
2566 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2568 if (!Attribute::isConstantRangeAttrKind(Kind))
2569 return error(
"Not a ConstantRange attribute");
2571 Expected<ConstantRange> MaybeCR =
2572 readBitWidthAndConstantRange(Record, i);
2577 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2578 }
else if (Record[i] == 8) {
2579 Attribute::AttrKind
Kind;
2582 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2584 if (!Attribute::isConstantRangeListAttrKind(Kind))
2585 return error(
"Not a constant range list attribute");
2589 return error(
"Too few records for constant range list");
2590 unsigned RangeSize =
Record[i++];
2592 for (
unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2593 Expected<ConstantRange> MaybeCR =
2594 readConstantRange(Record, i,
BitWidth);
2602 return error(
"Invalid (unordered or overlapping) range list");
2603 B.addConstantRangeListAttr(Kind, Val);
2605 return error(
"Invalid attribute group entry");
2610 B.addMemoryAttr(ME);
2613 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2620Error BitcodeReader::parseTypeTable() {
2624 return parseTypeTableBody();
2627Error BitcodeReader::parseTypeTableBody() {
2628 if (!TypeList.empty())
2629 return error(
"Invalid multiple blocks");
2631 SmallVector<uint64_t, 64>
Record;
2632 unsigned NumRecords = 0;
2641 BitstreamEntry
Entry = MaybeEntry.
get();
2643 switch (
Entry.Kind) {
2646 return error(
"Malformed block");
2648 if (NumRecords != TypeList.size())
2649 return error(
"Malformed block");
2658 Type *ResultTy =
nullptr;
2659 SmallVector<unsigned> ContainedIDs;
2663 switch (MaybeRecord.
get()) {
2665 return error(
"Invalid value");
2670 return error(
"Invalid numentry record");
2671 TypeList.resize(Record[0]);
2674 ResultTy = Type::getVoidTy(
Context);
2677 ResultTy = Type::getHalfTy(
Context);
2680 ResultTy = Type::getBFloatTy(
Context);
2683 ResultTy = Type::getFloatTy(
Context);
2686 ResultTy = Type::getDoubleTy(
Context);
2689 ResultTy = Type::getX86_FP80Ty(
Context);
2692 ResultTy = Type::getFP128Ty(
Context);
2695 ResultTy = Type::getPPC_FP128Ty(
Context);
2698 ResultTy = Type::getLabelTy(
Context);
2701 ResultTy = Type::getMetadataTy(
Context);
2709 ResultTy = Type::getX86_AMXTy(
Context);
2712 ResultTy = Type::getTokenTy(
Context);
2716 return error(
"Invalid record");
2721 return error(
"Bitwidth for byte type out of range");
2727 return error(
"Invalid integer record");
2732 return error(
"Bitwidth for integer type out of range");
2739 return error(
"Invalid pointer record");
2743 ResultTy = getTypeByID(Record[0]);
2745 !PointerType::isValidElementType(ResultTy))
2746 return error(
"Invalid type");
2753 return error(
"Invalid opaque pointer record");
2762 return error(
"Invalid function record");
2764 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2765 if (
Type *
T = getTypeByID(Record[i]))
2771 ResultTy = getTypeByID(Record[2]);
2772 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2773 return error(
"Invalid type");
2776 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2782 return error(
"Invalid function record");
2784 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2785 if (
Type *
T = getTypeByID(Record[i])) {
2786 if (!FunctionType::isValidArgumentType(
T))
2787 return error(
"Invalid function argument type");
2794 ResultTy = getTypeByID(Record[1]);
2795 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2796 return error(
"Invalid type");
2799 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2804 return error(
"Invalid anon struct record");
2806 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2807 if (
Type *
T = getTypeByID(Record[i]))
2813 return error(
"Invalid type");
2820 return error(
"Invalid struct name record");
2825 return error(
"Invalid named struct record");
2827 if (NumRecords >= TypeList.size())
2828 return error(
"Invalid TYPE table");
2834 TypeList[NumRecords] =
nullptr;
2836 Res = createIdentifiedStructType(
Context, TypeName);
2840 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2841 if (
Type *
T = getTypeByID(Record[i]))
2847 return error(
"Invalid named struct record");
2856 return error(
"Invalid opaque type record");
2858 if (NumRecords >= TypeList.size())
2859 return error(
"Invalid TYPE table");
2865 TypeList[NumRecords] =
nullptr;
2867 Res = createIdentifiedStructType(
Context, TypeName);
2874 return error(
"Invalid target extension type record");
2876 if (NumRecords >= TypeList.size())
2877 return error(
"Invalid TYPE table");
2879 if (Record[0] >=
Record.size())
2880 return error(
"Too many type parameters");
2882 unsigned NumTys =
Record[0];
2884 SmallVector<unsigned, 8> IntParams;
2885 for (
unsigned i = 0; i < NumTys; i++) {
2886 if (
Type *
T = getTypeByID(Record[i + 1]))
2889 return error(
"Invalid type");
2892 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2893 if (Record[i] > UINT_MAX)
2894 return error(
"Integer parameter too large");
2899 if (
auto E = TTy.takeError())
2907 return error(
"Invalid array type record");
2908 ResultTy = getTypeByID(Record[1]);
2909 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2910 return error(
"Invalid type");
2912 ResultTy = ArrayType::get(ResultTy, Record[0]);
2917 return error(
"Invalid vector type record");
2919 return error(
"Invalid vector length");
2920 ResultTy = getTypeByID(Record[1]);
2921 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2922 return error(
"Invalid type");
2925 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2929 if (NumRecords >= TypeList.size())
2930 return error(
"Invalid TYPE table");
2931 if (TypeList[NumRecords])
2933 "Invalid TYPE table: Only named structs can be forward referenced");
2934 assert(ResultTy &&
"Didn't read a type?");
2935 TypeList[NumRecords] = ResultTy;
2936 if (!ContainedIDs.
empty())
2937 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2942Error BitcodeReader::parseOperandBundleTags() {
2946 if (!BundleTags.empty())
2947 return error(
"Invalid multiple blocks");
2949 SmallVector<uint64_t, 64>
Record;
2955 BitstreamEntry
Entry = MaybeEntry.
get();
2957 switch (
Entry.Kind) {
2960 return error(
"Malformed block");
2974 return error(
"Invalid operand bundle record");
2977 BundleTags.emplace_back();
2979 return error(
"Invalid operand bundle record");
2984Error BitcodeReader::parseSyncScopeNames() {
2989 return error(
"Invalid multiple synchronization scope names blocks");
2991 SmallVector<uint64_t, 64>
Record;
2996 BitstreamEntry
Entry = MaybeEntry.
get();
2998 switch (
Entry.Kind) {
3001 return error(
"Malformed block");
3004 return error(
"Invalid empty synchronization scope names block");
3018 return error(
"Invalid sync scope record");
3020 SmallString<16> SSN;
3022 return error(
"Invalid sync scope record");
3030Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
3031 unsigned NameIndex, Triple &TT) {
3034 return error(
"Invalid record");
3035 unsigned ValueID =
Record[0];
3036 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3037 return error(
"Invalid record");
3038 Value *
V = ValueList[ValueID];
3041 if (NameStr.contains(0))
3042 return error(
"Invalid value name");
3043 V->setName(NameStr);
3045 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
3058 return std::move(JumpFailed);
3064 return error(
"Expected value symbol table subblock");
3068void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
3070 ArrayRef<uint64_t> Record) {
3075 uint64_t FuncBitOffset = FuncWordOffset * 32;
3076 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3080 if (FuncBitOffset > LastFunctionBlockBit)
3081 LastFunctionBlockBit = FuncBitOffset;
3085Error BitcodeReader::parseGlobalValueSymbolTable() {
3086 unsigned FuncBitcodeOffsetDelta =
3092 SmallVector<uint64_t, 64>
Record;
3097 BitstreamEntry
Entry = MaybeEntry.
get();
3099 switch (
Entry.Kind) {
3102 return error(
"Malformed block");
3113 switch (MaybeRecord.
get()) {
3115 unsigned ValueID =
Record[0];
3116 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3117 return error(
"Invalid value reference in symbol table");
3118 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3135 if (!MaybeCurrentBit)
3137 CurrentBit = MaybeCurrentBit.
get();
3140 if (
Error Err = parseGlobalValueSymbolTable())
3161 unsigned FuncBitcodeOffsetDelta =
3167 SmallVector<uint64_t, 64>
Record;
3178 BitstreamEntry
Entry = MaybeEntry.
get();
3180 switch (
Entry.Kind) {
3183 return error(
"Malformed block");
3199 switch (MaybeRecord.
get()) {
3203 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3211 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3219 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3224 return error(
"Invalid bbentry record");
3227 return error(
"Invalid bbentry record");
3249Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3250 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3251 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3252 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3254 GlobalInitWorklist.swap(GlobalInits);
3255 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3256 FunctionOperandWorklist.swap(FunctionOperands);
3258 while (!GlobalInitWorklist.empty()) {
3259 unsigned ValID = GlobalInitWorklist.back().second;
3260 if (ValID >= ValueList.
size()) {
3262 GlobalInits.push_back(GlobalInitWorklist.back());
3264 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3267 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3269 GlobalInitWorklist.pop_back();
3272 while (!IndirectSymbolInitWorklist.empty()) {
3273 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3274 if (ValID >= ValueList.
size()) {
3275 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3277 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3281 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3284 return error(
"Alias and aliasee types don't match");
3289 return error(
"Expected an alias or an ifunc");
3292 IndirectSymbolInitWorklist.pop_back();
3295 while (!FunctionOperandWorklist.empty()) {
3296 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3297 if (
Info.PersonalityFn) {
3298 unsigned ValID =
Info.PersonalityFn - 1;
3299 if (ValID < ValueList.
size()) {
3300 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3303 Info.F->setPersonalityFn(MaybeC.
get());
3304 Info.PersonalityFn = 0;
3308 unsigned ValID =
Info.Prefix - 1;
3309 if (ValID < ValueList.
size()) {
3310 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3313 Info.F->setPrefixData(MaybeC.
get());
3317 if (
Info.Prologue) {
3318 unsigned ValID =
Info.Prologue - 1;
3319 if (ValID < ValueList.
size()) {
3320 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3323 Info.F->setPrologueData(MaybeC.
get());
3327 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3328 FunctionOperands.push_back(Info);
3329 FunctionOperandWorklist.pop_back();
3338 BitcodeReader::decodeSignRotatedValue);
3340 return APInt(TypeBits, Words);
3343Error BitcodeReader::parseConstants() {
3351 unsigned Int32TyID = getVirtualTypeID(CurTy);
3352 unsigned CurTyID = Int32TyID;
3353 Type *CurElemTy =
nullptr;
3354 unsigned NextCstNo = ValueList.
size();
3362 switch (Entry.Kind) {
3365 return error(
"Malformed block");
3367 if (NextCstNo != ValueList.
size())
3368 return error(
"Invalid constant reference");
3379 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
3382 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3392 return error(
"Invalid settype record");
3393 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3394 return error(
"Invalid settype record");
3395 if (TypeList[Record[0]] == VoidType)
3396 return error(
"Invalid constant type");
3398 CurTy = TypeList[CurTyID];
3399 CurElemTy = getPtrElementTypeByID(CurTyID);
3403 return error(
"Invalid type for a constant null value");
3406 return error(
"Invalid type for a constant null value");
3411 return error(
"Invalid integer const record");
3416 return error(
"Invalid wide integer const record");
3419 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3420 V = ConstantInt::get(CurTy, VInt);
3425 return error(
"Invalid byte const record");
3426 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]),
3431 return error(
"Invalid wide byte const record");
3434 APInt VByte =
readWideAPInt(Record, ScalarTy->getBitWidth());
3435 V = ConstantByte::get(CurTy, VByte);
3440 return error(
"Invalid float const record");
3443 if (ScalarTy->isHalfTy())
3444 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3445 APInt(16, (uint16_t)Record[0])));
3446 else if (ScalarTy->isBFloatTy())
3447 V = ConstantFP::get(
3448 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3449 else if (ScalarTy->isFloatTy())
3450 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3451 APInt(32, (uint32_t)Record[0])));
3452 else if (ScalarTy->isDoubleTy())
3453 V = ConstantFP::get(
3454 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3455 else if (ScalarTy->isX86_FP80Ty()) {
3458 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3459 Rearrange[1] =
Record[0] >> 48;
3460 V = ConstantFP::get(
3461 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3462 }
else if (ScalarTy->isFP128Ty())
3463 V = ConstantFP::get(CurTy,
3464 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3465 else if (ScalarTy->isPPC_FP128Ty())
3466 V = ConstantFP::get(
3467 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3475 return error(
"Invalid aggregate record");
3477 SmallVector<unsigned, 16> Elts;
3481 V = BitcodeConstant::create(
3482 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3484 V = BitcodeConstant::create(
Alloc, CurTy,
3485 BitcodeConstant::ConstantArrayOpcode, Elts);
3487 V = BitcodeConstant::create(
3488 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3497 return error(
"Invalid string record");
3507 return error(
"Invalid data record");
3511 return error(
"Invalid type for value");
3514 SmallString<128> RawData;
3517 const char *Src =
reinterpret_cast<const char *
>(&Val);
3519 Src +=
sizeof(
uint64_t) - EltBytes;
3520 RawData.
append(Src, Src + EltBytes);
3525 : ConstantDataArray::getRaw(RawData.str(),
Record.
size(), EltTy);
3530 return error(
"Invalid unary op constexpr record");
3535 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3541 return error(
"Invalid binary op constexpr record");
3547 if (
Record.size() >= 4) {
3548 if (
Opc == Instruction::Add ||
3549 Opc == Instruction::Sub ||
3550 Opc == Instruction::Mul ||
3551 Opc == Instruction::Shl) {
3556 }
else if (
Opc == Instruction::SDiv ||
3557 Opc == Instruction::UDiv ||
3558 Opc == Instruction::LShr ||
3559 Opc == Instruction::AShr) {
3564 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3565 {(unsigned)Record[1], (
unsigned)
Record[2]});
3571 return error(
"Invalid cast constexpr record");
3576 unsigned OpTyID =
Record[1];
3577 Type *OpTy = getTypeByID(OpTyID);
3579 return error(
"Invalid cast constexpr record");
3580 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3592 return error(
"Constant GEP record must have at least two elements");
3594 Type *PointeeType =
nullptr;
3598 PointeeType = getTypeByID(Record[OpNum++]);
3601 std::optional<ConstantRange>
InRange;
3605 unsigned InRangeIndex =
Op >> 1;
3611 Expected<ConstantRange> MaybeInRange =
3612 readBitWidthAndConstantRange(Record, OpNum);
3621 SmallVector<unsigned, 16> Elts;
3622 unsigned BaseTypeID =
Record[OpNum];
3623 while (OpNum !=
Record.size()) {
3624 unsigned ElTyID =
Record[OpNum++];
3625 Type *ElTy = getTypeByID(ElTyID);
3627 return error(
"Invalid getelementptr constexpr record");
3631 if (Elts.
size() < 1)
3632 return error(
"Invalid gep with no operands");
3636 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3637 BaseType = getTypeByID(BaseTypeID);
3642 return error(
"GEP base operand must be pointer or vector of pointer");
3645 PointeeType = getPtrElementTypeByID(BaseTypeID);
3647 return error(
"Missing element type for old-style constant GEP");
3650 V = BitcodeConstant::create(
3652 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3658 return error(
"Invalid select constexpr record");
3660 V = BitcodeConstant::create(
3661 Alloc, CurTy, Instruction::Select,
3662 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3668 return error(
"Invalid extractelement constexpr record");
3669 unsigned OpTyID =
Record[0];
3673 return error(
"Invalid extractelement constexpr record");
3675 if (
Record.size() == 4) {
3676 unsigned IdxTyID =
Record[2];
3677 Type *IdxTy = getTypeByID(IdxTyID);
3679 return error(
"Invalid extractelement constexpr record");
3685 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3686 {(unsigned)Record[1], IdxRecord});
3692 if (
Record.size() < 3 || !OpTy)
3693 return error(
"Invalid insertelement constexpr record");
3695 if (
Record.size() == 4) {
3696 unsigned IdxTyID =
Record[2];
3697 Type *IdxTy = getTypeByID(IdxTyID);
3699 return error(
"Invalid insertelement constexpr record");
3705 V = BitcodeConstant::create(
3706 Alloc, CurTy, Instruction::InsertElement,
3707 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3712 if (
Record.size() < 3 || !OpTy)
3713 return error(
"Invalid shufflevector constexpr record");
3714 V = BitcodeConstant::create(
3715 Alloc, CurTy, Instruction::ShuffleVector,
3716 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3723 if (
Record.size() < 4 || !RTy || !OpTy)
3724 return error(
"Invalid shufflevector constexpr record");
3725 V = BitcodeConstant::create(
3726 Alloc, CurTy, Instruction::ShuffleVector,
3727 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3732 return error(
"Invalid cmp constexpt record");
3733 unsigned OpTyID =
Record[0];
3734 Type *OpTy = getTypeByID(OpTyID);
3736 return error(
"Invalid cmp constexpr record");
3737 V = BitcodeConstant::create(
3740 : Instruction::ICmp),
3741 (uint8_t)Record[3]},
3742 {(unsigned)Record[1], (
unsigned)
Record[2]});
3749 return error(
"Invalid inlineasm record");
3750 std::string AsmStr, ConstrStr;
3751 bool HasSideEffects =
Record[0] & 1;
3752 bool IsAlignStack =
Record[0] >> 1;
3753 unsigned AsmStrSize =
Record[1];
3754 if (2+AsmStrSize >=
Record.size())
3755 return error(
"Invalid inlineasm record");
3756 unsigned ConstStrSize =
Record[2+AsmStrSize];
3757 if (3+AsmStrSize+ConstStrSize >
Record.size())
3758 return error(
"Invalid inlineasm record");
3760 for (
unsigned i = 0; i != AsmStrSize; ++i)
3761 AsmStr += (
char)
Record[2+i];
3762 for (
unsigned i = 0; i != ConstStrSize; ++i)
3763 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3766 return error(
"Missing element type for old-style inlineasm");
3768 HasSideEffects, IsAlignStack);
3775 return error(
"Invalid inlineasm record");
3776 std::string AsmStr, ConstrStr;
3777 bool HasSideEffects =
Record[0] & 1;
3778 bool IsAlignStack = (
Record[0] >> 1) & 1;
3779 unsigned AsmDialect =
Record[0] >> 2;
3780 unsigned AsmStrSize =
Record[1];
3781 if (2+AsmStrSize >=
Record.size())
3782 return error(
"Invalid inlineasm record");
3783 unsigned ConstStrSize =
Record[2+AsmStrSize];
3784 if (3+AsmStrSize+ConstStrSize >
Record.size())
3785 return error(
"Invalid inlineasm record");
3787 for (
unsigned i = 0; i != AsmStrSize; ++i)
3788 AsmStr += (
char)
Record[2+i];
3789 for (
unsigned i = 0; i != ConstStrSize; ++i)
3790 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3793 return error(
"Missing element type for old-style inlineasm");
3795 HasSideEffects, IsAlignStack,
3802 return error(
"Invalid inlineasm record");
3804 std::string AsmStr, ConstrStr;
3805 bool HasSideEffects =
Record[OpNum] & 1;
3806 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3807 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3808 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3810 unsigned AsmStrSize =
Record[OpNum];
3812 if (OpNum + AsmStrSize >=
Record.size())
3813 return error(
"Invalid inlineasm record");
3814 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3815 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3816 return error(
"Invalid inlineasm record");
3818 for (
unsigned i = 0; i != AsmStrSize; ++i)
3819 AsmStr += (
char)
Record[OpNum + i];
3821 for (
unsigned i = 0; i != ConstStrSize; ++i)
3822 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3825 return error(
"Missing element type for old-style inlineasm");
3827 HasSideEffects, IsAlignStack,
3834 return error(
"Invalid inlineasm record");
3839 return error(
"Invalid inlineasm record");
3840 std::string AsmStr, ConstrStr;
3841 bool HasSideEffects =
Record[OpNum] & 1;
3842 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3843 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3844 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3846 unsigned AsmStrSize =
Record[OpNum];
3848 if (OpNum + AsmStrSize >=
Record.size())
3849 return error(
"Invalid inlineasm record");
3850 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3851 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3852 return error(
"Invalid inlineasm record");
3854 for (
unsigned i = 0; i != AsmStrSize; ++i)
3855 AsmStr += (
char)
Record[OpNum + i];
3857 for (
unsigned i = 0; i != ConstStrSize; ++i)
3858 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3860 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3866 return error(
"Invalid blockaddress record");
3867 unsigned FnTyID =
Record[0];
3868 Type *FnTy = getTypeByID(FnTyID);
3870 return error(
"Invalid blockaddress record");
3871 V = BitcodeConstant::create(
3873 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3879 return error(
"Invalid dso_local record");
3880 unsigned GVTyID =
Record[0];
3881 Type *GVTy = getTypeByID(GVTyID);
3883 return error(
"Invalid dso_local record");
3884 V = BitcodeConstant::create(
3885 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3890 return error(
"Invalid no_cfi record");
3891 unsigned GVTyID =
Record[0];
3892 Type *GVTy = getTypeByID(GVTyID);
3894 return error(
"Invalid no_cfi record");
3895 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3901 return error(
"Invalid ptrauth record");
3903 V = BitcodeConstant::create(
Alloc, CurTy,
3904 BitcodeConstant::ConstantPtrAuthOpcode,
3905 {(unsigned)Record[0], (
unsigned)
Record[1],
3906 (unsigned)Record[2], (
unsigned)
Record[3]});
3911 return error(
"Invalid ptrauth record");
3913 V = BitcodeConstant::create(
3914 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3915 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3916 (
unsigned)
Record[3], (unsigned)Record[4]});
3921 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3928Error BitcodeReader::parseUseLists() {
3933 SmallVector<uint64_t, 64>
Record;
3939 BitstreamEntry
Entry = MaybeEntry.
get();
3941 switch (
Entry.Kind) {
3944 return error(
"Malformed block");
3958 switch (MaybeRecord.
get()) {
3966 if (RecordLength < 3)
3968 return error(
"Invalid uselist record");
3969 unsigned ID =
Record.pop_back_val();
3973 assert(ID < FunctionBBs.size() &&
"Basic block not found");
3974 V = FunctionBBs[
ID];
3978 if (!
V->hasUseList())
3981 unsigned NumUses = 0;
3982 SmallDenseMap<const Use *, unsigned, 16> Order;
3983 for (
const Use &U :
V->materialized_uses()) {
3984 if (++NumUses >
Record.size())
3986 Order[&
U] =
Record[NumUses - 1];
3993 V->sortUseList([&](
const Use &L,
const Use &R) {
4004Error BitcodeReader::rememberAndSkipMetadata() {
4007 DeferredMetadataInfo.push_back(CurBit);
4015Error BitcodeReader::materializeMetadata() {
4016 for (
uint64_t BitPos : DeferredMetadataInfo) {
4020 if (
Error Err = MDLoader->parseModuleMetadata())
4029 NamedMDNode *LinkerOpts =
4031 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
4038 DeferredMetadataInfo.clear();
4042void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
4046Error BitcodeReader::rememberAndSkipFunctionBody() {
4048 if (FunctionsWithBodies.empty())
4049 return error(
"Insufficient function protos");
4051 Function *Fn = FunctionsWithBodies.back();
4052 FunctionsWithBodies.pop_back();
4057 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4058 "Mismatch between VST and scanned function offsets");
4059 DeferredFunctionInfo[Fn] = CurBit;
4067Error BitcodeReader::globalCleanup() {
4069 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4071 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4072 return error(
"Malformed global initializer set");
4077 MDLoader->upgradeDebugIntrinsics(
F);
4081 !SkipDebugIntrinsicUpgrade))
4082 UpgradedIntrinsics[&
F] = NewFn;
4088 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4089 for (GlobalVariable &GV : TheModule->globals())
4091 UpgradedVariables.emplace_back(&GV, Upgraded);
4092 for (
auto &Pair : UpgradedVariables) {
4093 Pair.first->eraseFromParent();
4094 TheModule->insertGlobalVariable(Pair.second);
4097 for (
size_t ValueID = 0; ValueID < GUIDList.size(); ValueID++) {
4098 const auto GUID = GUIDList[ValueID];
4102 const auto *
Value = ValueList[ValueID];
4103 TheModule->insertGUID(
Value, GUID);
4108 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4109 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4117Error BitcodeReader::rememberAndSkipFunctionBodies() {
4122 return error(
"Could not find function in stream");
4124 if (!SeenFirstFunctionBody)
4125 return error(
"Trying to materialize functions before seeing function blocks");
4129 assert(SeenValueSymbolTable);
4132 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4135 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4137 switch (
Entry.Kind) {
4139 return error(
"Expect SubBlock");
4143 return error(
"Expect function block");
4145 if (
Error Err = rememberAndSkipFunctionBody())
4154Error BitcodeReaderBase::readBlockInfo() {
4155 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4157 if (!MaybeNewBlockInfo)
4159 std::optional<BitstreamBlockInfo> NewBlockInfo =
4160 std::move(MaybeNewBlockInfo.
get());
4162 return error(
"Malformed block");
4163 BlockInfo = std::move(*NewBlockInfo);
4167Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4171 std::tie(Name, Record) = readNameFromStrtab(Record);
4174 return error(
"Invalid comdat record");
4176 std::string OldFormatName;
4179 return error(
"Invalid comdat record");
4180 unsigned ComdatNameSize =
Record[1];
4181 if (ComdatNameSize >
Record.size() - 2)
4182 return error(
"Comdat name size too large");
4183 OldFormatName.reserve(ComdatNameSize);
4184 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4185 OldFormatName += (
char)
Record[2 + i];
4186 Name = OldFormatName;
4188 Comdat *
C = TheModule->getOrInsertComdat(Name);
4189 C->setSelectionKind(SK);
4190 ComdatList.push_back(
C);
4204 Meta.NoAddress =
true;
4206 Meta.NoHWAddress =
true;
4210 Meta.IsDynInit =
true;
4214Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4222 std::tie(Name, Record) = readNameFromStrtab(Record);
4225 return error(
"Invalid global variable record");
4226 unsigned TyID =
Record[0];
4227 Type *Ty = getTypeByID(TyID);
4229 return error(
"Invalid global variable record");
4231 bool explicitType =
Record[1] & 2;
4237 return error(
"Invalid type for value");
4239 TyID = getContainedTypeID(TyID);
4240 Ty = getTypeByID(TyID);
4242 return error(
"Missing element type for old-style global");
4248 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4252 if (Record[5] - 1 >= SectionTable.size())
4253 return error(
"Invalid ID");
4262 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4270 bool ExternallyInitialized =
false;
4272 ExternallyInitialized =
Record[9];
4274 GlobalVariable *NewGV =
4284 if (
Record.size() > 10) {
4296 if (
unsigned InitID = Record[2])
4297 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4299 if (
Record.size() > 11) {
4300 if (
unsigned ComdatID = Record[11]) {
4301 if (ComdatID > ComdatList.size())
4302 return error(
"Invalid global variable comdat ID");
4303 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4306 ImplicitComdatObjects.
insert(NewGV);
4309 if (
Record.size() > 12) {
4314 if (
Record.size() > 13) {
4323 if (
Record.size() > 16 && Record[16]) {
4324 llvm::GlobalValue::SanitizerMetadata
Meta =
4329 if (
Record.size() > 17 && Record[17]) {
4333 return error(
"Invalid global variable code model");
4339void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4340 if (ValueTypeCallback) {
4341 (*ValueTypeCallback)(
4342 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4343 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4347Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4353 std::tie(Name, Record) = readNameFromStrtab(Record);
4356 return error(
"Invalid function record");
4357 unsigned FTyID =
Record[0];
4358 Type *FTy = getTypeByID(FTyID);
4360 return error(
"Invalid function record");
4362 FTyID = getContainedTypeID(FTyID, 0);
4363 FTy = getTypeByID(FTyID);
4365 return error(
"Missing element type for old-style function");
4369 return error(
"Invalid type for value");
4370 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4371 if (CC & ~CallingConv::MaxID)
4372 return error(
"Invalid calling convention ID");
4374 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4380 AddrSpace, Name, TheModule);
4383 "Incorrect fully specified type provided for function");
4384 FunctionTypeIDs[
Func] = FTyID;
4386 Func->setCallingConv(CC);
4387 bool isProto =
Record[2];
4391 callValueTypeCallback(Func, FTyID);
4396 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4397 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4398 Attribute::InAlloca}) {
4399 if (!
Func->hasParamAttribute(i, Kind))
4402 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4405 Func->removeParamAttr(i, Kind);
4407 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4408 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4410 return error(
"Missing param element type for attribute upgrade");
4414 case Attribute::ByVal:
4415 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4417 case Attribute::StructRet:
4418 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4420 case Attribute::InAlloca:
4421 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4427 Func->addParamAttr(i, NewAttr);
4431 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4432 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4433 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4434 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4436 return error(
"Missing param element type for x86_intrcc upgrade");
4438 Func->addParamAttr(0, NewAttr);
4442 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4445 Func->setAlignment(*Alignment);
4447 if (Record[6] - 1 >= SectionTable.size())
4448 return error(
"Invalid ID");
4449 Func->setSection(SectionTable[Record[6] - 1]);
4453 if (!
Func->hasLocalLinkage())
4455 if (
Record.size() > 8 && Record[8]) {
4456 if (Record[8] - 1 >= GCTable.size())
4457 return error(
"Invalid ID");
4458 Func->setGC(GCTable[Record[8] - 1]);
4463 Func->setUnnamedAddr(UnnamedAddr);
4465 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4467 OperandInfo.Prologue =
Record[10];
4469 if (
Record.size() > 11) {
4471 if (!
Func->hasLocalLinkage()) {
4478 if (
Record.size() > 12) {
4479 if (
unsigned ComdatID = Record[12]) {
4480 if (ComdatID > ComdatList.size())
4481 return error(
"Invalid function comdat ID");
4482 Func->setComdat(ComdatList[ComdatID - 1]);
4485 ImplicitComdatObjects.
insert(Func);
4489 OperandInfo.Prefix =
Record[13];
4492 OperandInfo.PersonalityFn =
Record[14];
4494 if (
Record.size() > 15) {
4504 Record[17] + Record[18] <= Strtab.
size()) {
4505 Func->setPartition(StringRef(Strtab.
data() + Record[17], Record[18]));
4508 if (
Record.size() > 19) {
4509 MaybeAlign PrefAlignment;
4510 if (
Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4512 Func->setPreferredAlignment(PrefAlignment);
4515 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4517 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4518 FunctionOperands.push_back(OperandInfo);
4523 Func->setIsMaterializable(
true);
4524 FunctionsWithBodies.push_back(Func);
4525 DeferredFunctionInfo[
Func] = 0;
4530Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4531 unsigned BitCode, ArrayRef<uint64_t> Record) {
4541 std::tie(Name, Record) = readNameFromStrtab(Record);
4544 if (
Record.size() < (3 + (
unsigned)NewRecord))
4545 return error(
"Invalid global indirect symbol record");
4550 return error(
"Invalid global indirect symbol record");
4556 return error(
"Invalid type for value");
4557 AddrSpace = PTy->getAddressSpace();
4559 Ty = getTypeByID(
TypeID);
4561 return error(
"Missing element type for old-style indirect symbol");
4563 AddrSpace =
Record[OpNum++];
4566 auto Val =
Record[OpNum++];
4575 nullptr, TheModule);
4579 if (OpNum !=
Record.size()) {
4580 auto VisInd = OpNum++;
4586 if (OpNum !=
Record.size()) {
4587 auto S =
Record[OpNum++];
4594 if (OpNum !=
Record.size())
4596 if (OpNum !=
Record.size())
4599 if (OpNum !=
Record.size())
4604 if (OpNum + 1 <
Record.size()) {
4606 if (Record[OpNum] + Record[OpNum + 1] > Strtab.
size())
4607 return error(
"Malformed partition, too large.");
4609 StringRef(Strtab.
data() + Record[OpNum], Record[OpNum + 1]));
4613 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4618 bool ShouldLazyLoadMetadata,
4619 ParserCallbacks Callbacks) {
4620 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4627 SmallVector<uint64_t, 64>
Record;
4631 bool ResolvedDataLayout =
false;
4636 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4639 Module::GlobalAsmProperties Props;
4641 auto ResolveDataLayout = [&]() ->
Error {
4642 if (ResolvedDataLayout)
4646 ResolvedDataLayout =
true;
4650 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4654 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4655 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4656 TentativeDataLayoutStr = *LayoutOverride;
4664 TheModule->setDataLayout(MaybeDL.
get());
4670 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4673 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4675 switch (
Entry.Kind) {
4677 return error(
"Malformed block");
4679 if (
Error Err = ResolveDataLayout())
4681 return globalCleanup();
4690 if (
Error Err = readBlockInfo())
4694 if (
Error Err = parseAttributeBlock())
4698 if (
Error Err = parseAttributeGroupBlock())
4702 if (
Error Err = parseTypeTable())
4706 if (!SeenValueSymbolTable) {
4712 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4713 if (
Error Err = parseValueSymbolTable())
4715 SeenValueSymbolTable =
true;
4725 if (
Error Err = parseConstants())
4727 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4731 if (ShouldLazyLoadMetadata) {
4732 if (
Error Err = rememberAndSkipMetadata())
4736 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4737 if (
Error Err = MDLoader->parseModuleMetadata())
4741 if (
Error Err = MDLoader->parseMetadataKinds())
4745 if (
Error Err = ResolveDataLayout())
4750 if (!SeenFirstFunctionBody) {
4751 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4752 if (
Error Err = globalCleanup())
4754 SeenFirstFunctionBody =
true;
4757 if (VSTOffset > 0) {
4761 if (!SeenValueSymbolTable) {
4762 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4764 SeenValueSymbolTable =
true;
4786 if (
Error Err = rememberAndSkipFunctionBody())
4793 if (SeenValueSymbolTable) {
4797 return globalCleanup();
4801 if (
Error Err = parseUseLists())
4805 if (
Error Err = parseOperandBundleTags())
4809 if (
Error Err = parseSyncScopeNames())
4821 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
4824 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4827 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4830 UseRelativeIDs = *VersionOrErr >= 1;
4834 if (ResolvedDataLayout)
4835 return error(
"target triple too late in module");
4838 return error(
"Invalid triple record");
4839 TheModule->setTargetTriple(Triple(std::move(S)));
4843 if (ResolvedDataLayout)
4844 return error(
"datalayout too late in module");
4846 return error(
"Invalid data layout record");
4852 return error(
"Invalid module asm record");
4853 size_t SepPos = Str.find(
'\0');
4854 if (SepPos == std::string::npos)
4855 return error(
"Invalid module asm record");
4856 if (!Props.
set(StringRef(Str.data(), SepPos), Str.substr(SepPos + 1)))
4857 return error(
"Unknown module asm property");
4863 return error(
"Invalid asm record");
4864 TheModule->appendModuleInlineAsm(Module::GlobalAsmFragment(S, Props));
4872 return error(
"Invalid deplib record");
4879 return error(
"Invalid section name record");
4880 SectionTable.push_back(S);
4886 return error(
"Invalid gcname record");
4887 GCTable.push_back(S);
4891 if (
Error Err = parseComdatRecord(Record))
4900 if (
Error Err = parseGlobalVarRecord(Record))
4904 if (
Error Err = ResolveDataLayout())
4906 if (
Error Err = parseFunctionRecord(Record))
4912 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4918 return error(
"Invalid vstoffset record");
4922 VSTOffset =
Record[0] - 1;
4927 GUIDList.reserve(GUIDList.size() +
Record.size() / 2);
4928 for (
size_t i = 0; i <
Record.size(); i += 2)
4929 GUIDList.push_back(Record[i] << 32 | Record[i + 1]);
4935 return error(
"Invalid source filename record");
4936 TheModule->setSourceFileName(
ValueName);
4942 this->ValueTypeCallback = std::nullopt;
4946Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4948 ParserCallbacks Callbacks) {
4950 MetadataLoaderCallbacks MDCallbacks;
4951 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(ID); };
4953 return getContainedTypeID(
I, J);
4956 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4958 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4961Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4963 return error(
"Load/Store operand is not a pointer type");
4964 if (!PointerType::isLoadableOrStorableType(ValType))
4965 return error(
"Cannot load/store from pointer");
4969Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4970 ArrayRef<unsigned> ArgTyIDs) {
4972 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4973 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4974 Attribute::InAlloca}) {
4975 if (!
Attrs.hasParamAttr(i, Kind) ||
4976 Attrs.getParamAttr(i, Kind).getValueAsType())
4979 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4981 return error(
"Missing element type for typed attribute upgrade");
4985 case Attribute::ByVal:
4986 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4988 case Attribute::StructRet:
4989 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4991 case Attribute::InAlloca:
4992 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
5005 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
5009 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
5010 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5012 return error(
"Missing element type for inline asm upgrade");
5015 Attribute::get(
Context, Attribute::ElementType, ElemTy));
5023 case Intrinsic::preserve_array_access_index:
5024 case Intrinsic::preserve_struct_access_index:
5025 case Intrinsic::aarch64_ldaxr:
5026 case Intrinsic::aarch64_ldxr:
5027 case Intrinsic::aarch64_stlxr:
5028 case Intrinsic::aarch64_stxr:
5029 case Intrinsic::arm_ldaex:
5030 case Intrinsic::arm_ldrex:
5031 case Intrinsic::arm_stlex:
5032 case Intrinsic::arm_strex: {
5035 case Intrinsic::aarch64_stlxr:
5036 case Intrinsic::aarch64_stxr:
5037 case Intrinsic::arm_stlex:
5038 case Intrinsic::arm_strex:
5045 if (!
Attrs.getParamElementType(ArgNo)) {
5046 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5048 return error(
"Missing element type for elementtype upgrade");
5068 if (MDLoader->hasFwdRefs())
5069 return error(
"Invalid function metadata: incoming forward references");
5071 InstructionList.
clear();
5072 unsigned ModuleValueListSize = ValueList.
size();
5073 unsigned ModuleMDLoaderSize = MDLoader->size();
5077 unsigned FTyID = FunctionTypeIDs[
F];
5078 for (Argument &
I :
F->args()) {
5079 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
5080 assert(
I.getType() == getTypeByID(ArgTyID) &&
5081 "Incorrect fully specified type for Function Argument");
5085 unsigned NextValueNo = ValueList.
size();
5087 unsigned CurBBNo = 0;
5092 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
5096 auto getLastInstruction = [&]() -> Instruction * {
5097 if (CurBB && !CurBB->
empty())
5098 return &CurBB->
back();
5099 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5100 !FunctionBBs[CurBBNo - 1]->
empty())
5101 return &FunctionBBs[CurBBNo - 1]->back();
5105 std::vector<OperandBundleDef> OperandBundles;
5108 SmallVector<uint64_t, 64>
Record;
5111 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
5114 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
5116 switch (
Entry.Kind) {
5118 return error(
"Malformed block");
5120 goto OutOfRecordLoop;
5129 if (
Error Err = parseConstants())
5131 NextValueNo = ValueList.
size();
5134 if (
Error Err = parseValueSymbolTable())
5138 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5142 assert(DeferredMetadataInfo.empty() &&
5143 "Must read all module-level metadata before function-level");
5144 if (
Error Err = MDLoader->parseFunctionMetadata())
5148 if (
Error Err = parseUseLists())
5162 unsigned ResTypeID = InvalidTypeID;
5163 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
5166 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5168 return error(
"Invalid value");
5170 if (
Record.empty() || Record[0] == 0)
5171 return error(
"Invalid declareblocks record");
5173 FunctionBBs.resize(Record[0]);
5176 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5177 if (BBFRI == BasicBlockFwdRefs.
end()) {
5178 for (BasicBlock *&BB : FunctionBBs)
5181 auto &BBRefs = BBFRI->second;
5183 if (BBRefs.size() > FunctionBBs.size())
5184 return error(
"Invalid ID");
5185 assert(!BBRefs.empty() &&
"Unexpected empty array");
5186 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5187 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5189 if (
I < RE && BBRefs[
I]) {
5190 BBRefs[
I]->insertInto(
F);
5191 FunctionBBs[
I] = BBRefs[
I];
5197 BasicBlockFwdRefs.
erase(BBFRI);
5200 CurBB = FunctionBBs[0];
5207 return error(
"Invalid blockaddr users record");
5223 BackwardRefFunctions.push_back(
F);
5225 return error(
"Invalid blockaddr users record");
5232 I = getLastInstruction();
5235 return error(
"Invalid debug_loc_again record");
5236 I->setDebugLoc(LastLoc);
5241 I = getLastInstruction();
5243 return error(
"Invalid debug loc record");
5251 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5254 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5256 return error(
"Invalid debug loc record");
5260 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5262 return error(
"Invalid debug loc record");
5265 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5266 isImplicitCode, AtomGroup, AtomRank);
5267 I->setDebugLoc(LastLoc);
5275 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5277 return error(
"Invalid unary operator record");
5281 return error(
"Invalid unary operator record");
5285 if (OpNum <
Record.size()) {
5289 I->setFastMathFlags(FMF);
5298 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5302 return error(
"Invalid binary operator record");
5306 return error(
"Invalid binary operator record");
5310 if (OpNum <
Record.size()) {
5311 if (
Opc == Instruction::Add ||
5312 Opc == Instruction::Sub ||
5313 Opc == Instruction::Mul ||
5314 Opc == Instruction::Shl) {
5319 }
else if (
Opc == Instruction::SDiv ||
5320 Opc == Instruction::UDiv ||
5321 Opc == Instruction::LShr ||
5322 Opc == Instruction::AShr) {
5325 }
else if (
Opc == Instruction::Or) {
5331 I->setFastMathFlags(FMF);
5340 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5341 OpNum + 1 >
Record.size())
5342 return error(
"Invalid cast record");
5344 ResTypeID =
Record[OpNum++];
5345 Type *ResTy = getTypeByID(ResTypeID);
5348 if (
Opc == -1 || !ResTy)
5349 return error(
"Invalid cast record");
5354 assert(CurBB &&
"No current BB?");
5360 return error(
"Invalid cast");
5364 if (OpNum <
Record.size()) {
5365 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5368 }
else if (
Opc == Instruction::Trunc) {
5380 I->setFastMathFlags(FMF);
5399 Ty = getTypeByID(TyID);
5403 TyID = InvalidTypeID;
5408 unsigned BasePtrTypeID;
5409 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5411 return error(
"Invalid gep record");
5414 TyID = getContainedTypeID(BasePtrTypeID);
5415 if (
BasePtr->getType()->isVectorTy())
5416 TyID = getContainedTypeID(TyID);
5417 Ty = getTypeByID(TyID);
5420 SmallVector<Value*, 16> GEPIdx;
5421 while (OpNum !=
Record.size()) {
5424 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5425 return error(
"Invalid gep record");
5436 unsigned SubType = 0;
5437 if (GTI.isStruct()) {
5439 Idx->getType()->isVectorTy()
5441 :
cast<ConstantInt>(Idx);
5444 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5451 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5452 if (
I->getType()->isVectorTy())
5453 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5456 GEP->setNoWrapFlags(NW);
5465 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5466 return error(
"Invalid extractvalue record");
5469 unsigned RecSize =
Record.size();
5470 if (OpNum == RecSize)
5471 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5473 SmallVector<unsigned, 4> EXTRACTVALIdx;
5474 ResTypeID = AggTypeID;
5475 for (; OpNum != RecSize; ++OpNum) {
5480 if (!IsStruct && !IsArray)
5481 return error(
"EXTRACTVAL: Invalid type");
5482 if ((
unsigned)Index != Index)
5483 return error(
"Invalid value");
5485 return error(
"EXTRACTVAL: Invalid struct index");
5487 return error(
"EXTRACTVAL: Invalid array index");
5488 EXTRACTVALIdx.
push_back((
unsigned)Index);
5492 ResTypeID = getContainedTypeID(ResTypeID, Index);
5495 ResTypeID = getContainedTypeID(ResTypeID);
5509 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5510 return error(
"Invalid insertvalue record");
5513 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5514 return error(
"Invalid insertvalue record");
5516 unsigned RecSize =
Record.size();
5517 if (OpNum == RecSize)
5518 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5520 SmallVector<unsigned, 4> INSERTVALIdx;
5522 for (; OpNum != RecSize; ++OpNum) {
5527 if (!IsStruct && !IsArray)
5528 return error(
"INSERTVAL: Invalid type");
5529 if ((
unsigned)Index != Index)
5530 return error(
"Invalid value");
5532 return error(
"INSERTVAL: Invalid struct index");
5534 return error(
"INSERTVAL: Invalid array index");
5536 INSERTVALIdx.
push_back((
unsigned)Index);
5544 return error(
"Inserted value type doesn't match aggregate type");
5547 ResTypeID = AggTypeID;
5559 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5561 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5563 popValue(Record, OpNum, NextValueNo, CondType,
5564 getVirtualTypeID(CondType),
Cond, CurBB))
5565 return error(
"Invalid select record");
5578 unsigned ValTypeID, CondTypeID;
5579 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5581 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5583 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5584 return error(
"Invalid vector select record");
5587 if (VectorType* vector_type =
5590 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5591 return error(
"Invalid type for value");
5595 return error(
"Invalid type for value");
5599 ResTypeID = ValTypeID;
5604 I->setFastMathFlags(FMF);
5612 unsigned VecTypeID, IdxTypeID;
5613 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5614 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5615 return error(
"Invalid extractelement record");
5617 return error(
"Invalid type for value");
5619 ResTypeID = getContainedTypeID(VecTypeID);
5626 Value *Vec, *Elt, *Idx;
5627 unsigned VecTypeID, IdxTypeID;
5628 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5629 return error(
"Invalid insertelement record");
5631 return error(
"Invalid type for value");
5632 if (popValue(Record, OpNum, NextValueNo,
5634 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5635 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5636 return error(
"Invalid insert element record");
5638 ResTypeID = VecTypeID;
5646 unsigned Vec1TypeID;
5647 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5649 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5651 return error(
"Invalid shufflevector record");
5653 unsigned MaskTypeID;
5654 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5655 return error(
"Invalid shufflevector record");
5657 return error(
"Invalid type for value");
5659 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5661 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5676 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5677 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5679 return error(
"Invalid comparison record");
5681 if (OpNum >=
Record.size())
5683 "Invalid record: operand number exceeded available operands");
5688 if (IsFP &&
Record.size() > OpNum+1)
5693 return error(
"Invalid fcmp predicate");
5694 I =
new FCmpInst(PredVal,
LHS,
RHS);
5697 return error(
"Invalid icmp predicate");
5698 I =
new ICmpInst(PredVal,
LHS,
RHS);
5699 if (
Record.size() > OpNum + 1 &&
5704 if (OpNum + 1 !=
Record.size())
5705 return error(
"Invalid comparison record");
5707 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5709 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5712 I->setFastMathFlags(FMF);
5729 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5730 return error(
"Invalid ret record");
5731 if (OpNum !=
Record.size())
5732 return error(
"Invalid ret record");
5740 return error(
"Invalid br record");
5741 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5743 return error(
"Invalid br record");
5745 if (
Record.size() == 1) {
5750 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5753 getVirtualTypeID(CondType), CurBB);
5754 if (!FalseDest || !
Cond)
5755 return error(
"Invalid br record");
5763 return error(
"Invalid cleanupret record");
5766 Value *CleanupPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5767 getVirtualTypeID(TokenTy), CurBB);
5769 return error(
"Invalid cleanupret record");
5771 if (
Record.size() == 2) {
5772 UnwindDest = getBasicBlock(Record[Idx++]);
5774 return error(
"Invalid cleanupret record");
5783 return error(
"Invalid catchret record");
5786 Value *CatchPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5787 getVirtualTypeID(TokenTy), CurBB);
5789 return error(
"Invalid catchret record");
5790 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5792 return error(
"Invalid catchret record");
5801 return error(
"Invalid catchswitch record");
5806 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5807 getVirtualTypeID(TokenTy), CurBB);
5809 return error(
"Invalid catchswitch record");
5811 unsigned NumHandlers =
Record[Idx++];
5814 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5815 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5817 return error(
"Invalid catchswitch record");
5822 if (Idx + 1 ==
Record.size()) {
5823 UnwindDest = getBasicBlock(Record[Idx++]);
5825 return error(
"Invalid catchswitch record");
5828 if (
Record.size() != Idx)
5829 return error(
"Invalid catchswitch record");
5833 for (BasicBlock *Handler : Handlers)
5834 CatchSwitch->addHandler(Handler);
5836 ResTypeID = getVirtualTypeID(
I->getType());
5844 return error(
"Invalid catchpad/cleanuppad record");
5849 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5850 getVirtualTypeID(TokenTy), CurBB);
5852 return error(
"Invalid catchpad/cleanuppad record");
5854 unsigned NumArgOperands =
Record[Idx++];
5856 SmallVector<Value *, 2>
Args;
5857 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5860 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5861 return error(
"Invalid catchpad/cleanuppad record");
5862 Args.push_back(Val);
5865 if (
Record.size() != Idx)
5866 return error(
"Invalid catchpad/cleanuppad record");
5872 ResTypeID = getVirtualTypeID(
I->getType());
5878 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5884 unsigned OpTyID =
Record[1];
5885 Type *OpTy = getTypeByID(OpTyID);
5891 return error(
"Invalid switch record");
5893 unsigned NumCases =
Record[4];
5898 unsigned CurIdx = 5;
5899 for (
unsigned i = 0; i != NumCases; ++i) {
5901 unsigned NumItems =
Record[CurIdx++];
5902 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5903 bool isSingleNumber =
Record[CurIdx++];
5906 unsigned ActiveWords = 1;
5907 if (ValueBitWidth > 64)
5908 ActiveWords =
Record[CurIdx++];
5911 CurIdx += ActiveWords;
5913 if (!isSingleNumber) {
5915 if (ValueBitWidth > 64)
5916 ActiveWords =
Record[CurIdx++];
5919 CurIdx += ActiveWords;
5930 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5931 for (ConstantInt *Cst : CaseVals)
5932 SI->addCase(Cst, DestBB);
5941 return error(
"Invalid switch record");
5942 unsigned OpTyID =
Record[0];
5943 Type *OpTy = getTypeByID(OpTyID);
5947 return error(
"Invalid switch record");
5948 unsigned NumCases = (
Record.size()-3)/2;
5951 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5953 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
5954 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5955 if (!CaseVal || !DestBB) {
5957 return error(
"Invalid switch record");
5959 SI->addCase(CaseVal, DestBB);
5966 return error(
"Invalid indirectbr record");
5967 unsigned OpTyID =
Record[0];
5968 Type *OpTy = getTypeByID(OpTyID);
5971 return error(
"Invalid indirectbr record");
5972 unsigned NumDests =
Record.size()-2;
5975 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5976 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5980 return error(
"Invalid indirectbr record");
5990 return error(
"Invalid invoke record");
5993 unsigned CCInfo =
Record[OpNum++];
5994 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5995 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5997 unsigned FTyID = InvalidTypeID;
5998 FunctionType *FTy =
nullptr;
5999 if ((CCInfo >> 13) & 1) {
6003 return error(
"Explicit invoke type is not a function type");
6007 unsigned CalleeTypeID;
6008 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6010 return error(
"Invalid invoke record");
6014 return error(
"Callee is not a pointer");
6016 FTyID = getContainedTypeID(CalleeTypeID);
6019 return error(
"Callee is not of pointer to function type");
6021 if (
Record.size() < FTy->getNumParams() + OpNum)
6022 return error(
"Insufficient operands to call");
6024 SmallVector<Value*, 16>
Ops;
6025 SmallVector<unsigned, 16> ArgTyIDs;
6026 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6027 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6028 Ops.push_back(
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6032 return error(
"Invalid invoke record");
6035 if (!FTy->isVarArg()) {
6036 if (
Record.size() != OpNum)
6037 return error(
"Invalid invoke record");
6040 while (OpNum !=
Record.size()) {
6043 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6044 return error(
"Invalid invoke record");
6051 if (!OperandBundles.empty())
6056 ResTypeID = getContainedTypeID(FTyID);
6057 OperandBundles.clear();
6060 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
6071 Value *Val =
nullptr;
6073 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
6074 return error(
"Invalid resume record");
6083 unsigned CCInfo =
Record[OpNum++];
6085 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
6086 unsigned NumIndirectDests =
Record[OpNum++];
6087 SmallVector<BasicBlock *, 16> IndirectDests;
6088 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
6089 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
6091 unsigned FTyID = InvalidTypeID;
6092 FunctionType *FTy =
nullptr;
6097 return error(
"Explicit call type is not a function type");
6101 unsigned CalleeTypeID;
6102 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6104 return error(
"Invalid callbr record");
6108 return error(
"Callee is not a pointer type");
6110 FTyID = getContainedTypeID(CalleeTypeID);
6113 return error(
"Callee is not of pointer to function type");
6115 if (
Record.size() < FTy->getNumParams() + OpNum)
6116 return error(
"Insufficient operands to call");
6118 SmallVector<Value*, 16>
Args;
6119 SmallVector<unsigned, 16> ArgTyIDs;
6121 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6123 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6124 if (FTy->getParamType(i)->isLabelTy())
6125 Arg = getBasicBlock(Record[OpNum]);
6127 Arg =
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6130 return error(
"Invalid callbr record");
6131 Args.push_back(Arg);
6136 if (!FTy->isVarArg()) {
6137 if (OpNum !=
Record.size())
6138 return error(
"Invalid callbr record");
6140 while (OpNum !=
Record.size()) {
6143 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6144 return error(
"Invalid callbr record");
6151 if (!OperandBundles.empty())
6156 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6159 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6164 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6165 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6166 unsigned LabelNo = ArgNo - FirstBlockArg;
6168 if (!BA || BA->getFunction() !=
F ||
6169 LabelNo > IndirectDests.
size() ||
6170 BA->getBasicBlock() != IndirectDests[LabelNo])
6171 return error(
"callbr argument does not match indirect dest");
6176 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6180 for (
Value *Arg : Args)
6183 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6186 std::string Constraints =
IA->getConstraintString().str();
6189 for (
const auto &CI : ConstraintInfo) {
6191 if (ArgNo >= FirstBlockArg)
6192 Constraints.insert(Pos,
"!");
6197 Pos = Constraints.find(
',', Pos);
6198 if (Pos == std::string::npos)
6204 IA->hasSideEffects(),
IA->isAlignStack(),
6205 IA->getDialect(),
IA->canThrow());
6211 ResTypeID = getContainedTypeID(FTyID);
6212 OperandBundles.clear();
6229 return error(
"Invalid phi record");
6231 unsigned TyID =
Record[0];
6232 Type *Ty = getTypeByID(TyID);
6234 return error(
"Invalid phi record");
6239 size_t NumArgs = (
Record.size() - 1) / 2;
6243 return error(
"Invalid phi record");
6247 SmallDenseMap<BasicBlock *, Value *>
Args;
6248 for (
unsigned i = 0; i != NumArgs; i++) {
6249 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6252 return error(
"Invalid phi BB");
6259 auto It =
Args.find(BB);
6261 if (It !=
Args.end()) {
6275 if (!PhiConstExprBB)
6277 EdgeBB = PhiConstExprBB;
6285 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6287 V =
getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6291 return error(
"Invalid phi record");
6294 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6295 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6296 PhiConstExprBB =
nullptr;
6299 Args.insert({BB,
V});
6305 if (
Record.size() % 2 == 0) {
6309 I->setFastMathFlags(FMF);
6321 return error(
"Invalid landingpad record");
6325 return error(
"Invalid landingpad record");
6327 ResTypeID =
Record[Idx++];
6328 Type *Ty = getTypeByID(ResTypeID);
6330 return error(
"Invalid landingpad record");
6332 Value *PersFn =
nullptr;
6333 unsigned PersFnTypeID;
6334 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6336 return error(
"Invalid landingpad record");
6338 if (!
F->hasPersonalityFn())
6341 return error(
"Personality function mismatch");
6344 bool IsCleanup = !!
Record[Idx++];
6345 unsigned NumClauses =
Record[Idx++];
6348 for (
unsigned J = 0; J != NumClauses; ++J) {
6354 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6357 return error(
"Invalid landingpad record");
6362 "Catch clause has a invalid type!");
6365 "Filter clause has invalid type!");
6376 return error(
"Invalid alloca record");
6377 using APV = AllocaPackedValues;
6381 unsigned TyID =
Record[0];
6382 Type *Ty = getTypeByID(TyID);
6384 TyID = getContainedTypeID(TyID);
6385 Ty = getTypeByID(TyID);
6387 return error(
"Missing element type for old-style alloca");
6389 unsigned OpTyID =
Record[1];
6390 Type *OpTy = getTypeByID(OpTyID);
6391 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6396 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6400 return error(
"Invalid alloca record");
6402 const DataLayout &
DL = TheModule->getDataLayout();
6403 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6405 SmallPtrSet<Type *, 4> Visited;
6406 if (!Align && !Ty->
isSized(&Visited))
6407 return error(
"alloca of unsized type");
6409 Align =
DL.getPrefTypeAlign(Ty);
6411 if (!
Size->getType()->isIntegerTy())
6412 return error(
"alloca element count must have integer type");
6414 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6418 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6426 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6427 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6428 return error(
"Invalid load record");
6431 return error(
"Load operand is not a pointer type");
6434 if (OpNum + 3 ==
Record.size()) {
6435 ResTypeID =
Record[OpNum++];
6436 Ty = getTypeByID(ResTypeID);
6438 ResTypeID = getContainedTypeID(OpTypeID);
6439 Ty = getTypeByID(ResTypeID);
6443 return error(
"Missing load type");
6445 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6449 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6451 SmallPtrSet<Type *, 4> Visited;
6452 if (!Align && !Ty->
isSized(&Visited))
6453 return error(
"load of unsized type");
6455 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6456 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6465 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6466 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size() &&
6467 OpNum + 6 !=
Record.size()))
6468 return error(
"Invalid load atomic record");
6471 return error(
"Load operand is not a pointer type");
6474 if (
Record.size() >= OpNum + 5) {
6475 ResTypeID =
Record[OpNum++];
6476 Ty = getTypeByID(ResTypeID);
6478 ResTypeID = getContainedTypeID(OpTypeID);
6479 Ty = getTypeByID(ResTypeID);
6483 return error(
"Missing atomic load type");
6485 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6489 if (Ordering == AtomicOrdering::NotAtomic ||
6490 Ordering == AtomicOrdering::Release ||
6491 Ordering == AtomicOrdering::AcquireRelease)
6492 return error(
"Invalid load atomic record");
6493 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6494 return error(
"Invalid load atomic record");
6495 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6496 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6499 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6502 return error(
"Alignment missing from atomic load");
6505 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6515 unsigned PtrTypeID, ValTypeID;
6516 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6517 return error(
"Invalid store record");
6520 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6521 return error(
"Invalid store record");
6523 ValTypeID = getContainedTypeID(PtrTypeID);
6524 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6525 ValTypeID, Val, CurBB))
6526 return error(
"Invalid store record");
6529 if (OpNum + 2 !=
Record.size())
6530 return error(
"Invalid store record");
6535 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6537 SmallPtrSet<Type *, 4> Visited;
6539 return error(
"store of unsized type");
6541 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6542 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6552 unsigned PtrTypeID, ValTypeID;
6553 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6555 return error(
"Invalid store atomic record");
6557 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6558 return error(
"Invalid store atomic record");
6560 ValTypeID = getContainedTypeID(PtrTypeID);
6561 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6562 ValTypeID, Val, CurBB))
6563 return error(
"Invalid store atomic record");
6566 if (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size())
6567 return error(
"Invalid store atomic record");
6572 if (Ordering == AtomicOrdering::NotAtomic ||
6573 Ordering == AtomicOrdering::Acquire ||
6574 Ordering == AtomicOrdering::AcquireRelease)
6575 return error(
"Invalid store atomic record");
6576 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6577 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6578 return error(
"Invalid store atomic record");
6581 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6584 return error(
"Alignment missing from atomic store");
6586 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6590 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6599 const size_t NumRecords =
Record.size();
6601 Value *Ptr =
nullptr;
6603 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6604 return error(
"Invalid cmpxchg record");
6607 return error(
"Cmpxchg operand is not a pointer type");
6610 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6611 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6612 CmpTypeID, Cmp, CurBB))
6613 return error(
"Invalid cmpxchg record");
6616 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6618 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6619 return error(
"Invalid cmpxchg record");
6623 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6624 SuccessOrdering == AtomicOrdering::Unordered)
6625 return error(
"Invalid cmpxchg record");
6627 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6629 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6637 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6638 FailureOrdering == AtomicOrdering::Unordered)
6639 return error(
"Invalid cmpxchg record");
6642 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6644 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6645 FailureOrdering, SSID);
6648 if (NumRecords < 8) {
6652 I->insertInto(CurBB, CurBB->
end());
6654 ResTypeID = CmpTypeID;
6657 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6658 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6667 const size_t NumRecords =
Record.size();
6669 Value *Ptr =
nullptr;
6671 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6672 return error(
"Invalid cmpxchg record");
6675 return error(
"Cmpxchg operand is not a pointer type");
6679 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6680 return error(
"Invalid cmpxchg record");
6682 Value *Val =
nullptr;
6683 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6685 return error(
"Invalid cmpxchg record");
6687 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6688 return error(
"Invalid cmpxchg record");
6690 const bool IsVol =
Record[OpNum];
6695 return error(
"Invalid cmpxchg success ordering");
6697 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6699 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6705 return error(
"Invalid cmpxchg failure ordering");
6707 const bool IsWeak =
Record[OpNum + 4];
6711 if (NumRecords == (OpNum + 6)) {
6712 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6717 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6719 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6720 FailureOrdering, SSID);
6724 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6725 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6734 const size_t NumRecords =
Record.size();
6737 Value *Ptr =
nullptr;
6739 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6740 return error(
"Invalid atomicrmw record");
6743 return error(
"Invalid atomicrmw record");
6745 Value *Val =
nullptr;
6746 unsigned ValTypeID = InvalidTypeID;
6748 ValTypeID = getContainedTypeID(PtrTypeID);
6749 if (popValue(Record, OpNum, NextValueNo,
6750 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6751 return error(
"Invalid atomicrmw record");
6753 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6754 return error(
"Invalid atomicrmw record");
6757 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6758 return error(
"Invalid atomicrmw record");
6760 bool IsElementwise =
false;
6765 return error(
"Invalid atomicrmw record");
6767 const bool IsVol =
Record[OpNum + 1];
6770 if (Ordering == AtomicOrdering::NotAtomic ||
6771 Ordering == AtomicOrdering::Unordered)
6772 return error(
"Invalid atomicrmw record");
6774 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6778 if (NumRecords == (OpNum + 5)) {
6779 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6785 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6787 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID,
6789 ResTypeID = ValTypeID;
6797 return error(
"Invalid fence record");
6799 if (Ordering == AtomicOrdering::NotAtomic ||
6800 Ordering == AtomicOrdering::Unordered ||
6801 Ordering == AtomicOrdering::Monotonic)
6802 return error(
"Invalid fence record");
6804 I =
new FenceInst(
Context, Ordering, SSID);
6811 SeenDebugRecord =
true;
6814 return error(
"Invalid dbg record: missing instruction");
6817 Inst->
getParent()->insertDbgRecordBefore(
6828 SeenDebugRecord =
true;
6831 return error(
"Invalid dbg record: missing instruction");
6848 DILocalVariable *Var =
6850 DIExpression *Expr =
6863 unsigned SlotBefore =
Slot;
6864 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6865 return error(
"Invalid dbg record: invalid value");
6867 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6870 RawLocation = getFnMetadataByID(Record[Slot++]);
6873 DbgVariableRecord *DVR =
nullptr;
6877 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6878 DbgVariableRecord::LocationType::Value);
6881 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6882 DbgVariableRecord::LocationType::Declare);
6885 DVR =
new DbgVariableRecord(
6886 RawLocation, Var, Expr, DIL,
6887 DbgVariableRecord::LocationType::DeclareValue);
6891 DIExpression *AddrExpr =
6893 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6894 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
6907 return error(
"Invalid call record");
6911 unsigned CCInfo =
Record[OpNum++];
6917 return error(
"Fast math flags indicator set for call with no FMF");
6920 unsigned FTyID = InvalidTypeID;
6921 FunctionType *FTy =
nullptr;
6926 return error(
"Explicit call type is not a function type");
6930 unsigned CalleeTypeID;
6931 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6933 return error(
"Invalid call record");
6937 return error(
"Callee is not a pointer type");
6939 FTyID = getContainedTypeID(CalleeTypeID);
6942 return error(
"Callee is not of pointer to function type");
6944 if (
Record.size() < FTy->getNumParams() + OpNum)
6945 return error(
"Insufficient operands to call");
6947 SmallVector<Value*, 16>
Args;
6948 SmallVector<unsigned, 16> ArgTyIDs;
6950 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6951 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6952 if (FTy->getParamType(i)->isLabelTy())
6953 Args.push_back(getBasicBlock(Record[OpNum]));
6956 FTy->getParamType(i), ArgTyID, CurBB));
6959 return error(
"Invalid call record");
6963 if (!FTy->isVarArg()) {
6964 if (OpNum !=
Record.size())
6965 return error(
"Invalid call record");
6967 while (OpNum !=
Record.size()) {
6970 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6971 return error(
"Invalid call record");
6978 if (!OperandBundles.empty())
6982 ResTypeID = getContainedTypeID(FTyID);
6983 OperandBundles.clear();
6997 SeenDebugIntrinsic =
true;
7004 return error(
"Fast-math-flags specified for call without "
7005 "floating-point scalar or vector return type");
7006 I->setFastMathFlags(FMF);
7012 return error(
"Invalid va_arg record");
7013 unsigned OpTyID =
Record[0];
7014 Type *OpTy = getTypeByID(OpTyID);
7017 Type *ResTy = getTypeByID(ResTypeID);
7018 if (!OpTy || !
Op || !ResTy)
7019 return error(
"Invalid va_arg record");
7020 I =
new VAArgInst(
Op, ResTy);
7030 if (
Record.empty() || Record[0] >= BundleTags.size())
7031 return error(
"Invalid operand bundle record");
7033 std::vector<Value *> Inputs;
7036 while (OpNum !=
Record.size()) {
7038 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
7039 return error(
"Invalid operand bundle record");
7040 Inputs.push_back(
Op);
7043 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
7051 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7052 return error(
"Invalid freeze record");
7053 if (OpNum !=
Record.size())
7054 return error(
"Invalid freeze record");
7056 I =
new FreezeInst(
Op);
7057 ResTypeID = OpTypeID;
7067 return error(
"Invalid instruction with no BB");
7069 if (!OperandBundles.empty()) {
7071 return error(
"Operand bundles found with no consumer");
7073 I->insertInto(CurBB, CurBB->
end());
7076 if (
I->isTerminator()) {
7078 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
7082 if (!
I->getType()->isVoidTy()) {
7083 assert(
I->getType() == getTypeByID(ResTypeID) &&
7084 "Incorrect result type ID");
7092 if (!OperandBundles.empty())
7093 return error(
"Operand bundles found with no consumer");
7097 if (!
A->getParent()) {
7099 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
7105 return error(
"Never resolved value found in function");
7110 if (MDLoader->hasFwdRefs())
7111 return error(
"Invalid function metadata: outgoing forward refs");
7116 for (
const auto &Pair : ConstExprEdgeBBs) {
7127 ValueList.
shrinkTo(ModuleValueListSize);
7128 MDLoader->shrinkTo(ModuleMDLoaderSize);
7129 std::vector<BasicBlock*>().swap(FunctionBBs);
7134Error BitcodeReader::findFunctionInStream(
7136 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7137 while (DeferredFunctionInfoIterator->second == 0) {
7142 assert(VSTOffset == 0 || !
F->hasName());
7145 if (
Error Err = rememberAndSkipFunctionBodies())
7151SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7154 if (Val >= SSIDs.
size())
7163Error BitcodeReader::materialize(GlobalValue *GV) {
7166 if (!
F || !
F->isMaterializable())
7169 auto DFII = DeferredFunctionInfo.
find(
F);
7170 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7173 if (DFII->second == 0)
7174 if (
Error Err = findFunctionInStream(
F, DFII))
7178 if (
Error Err = materializeMetadata())
7185 if (
Error Err = parseFunctionBody(
F))
7187 F->setIsMaterializable(
false);
7191 if (SeenDebugIntrinsic && SeenDebugRecord)
7192 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7198 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7199 F->setSubprogram(SP);
7202 if (!MDLoader->isStrippingTBAA()) {
7204 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7207 MDLoader->setStripTBAA(
true);
7214 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7215 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7221 unsigned ExpectedNumOperands = 0;
7223 ExpectedNumOperands = 2;
7225 ExpectedNumOperands =
SI->getNumSuccessors();
7227 ExpectedNumOperands = 1;
7231 ExpectedNumOperands = 2;
7238 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7239 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7245 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7246 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7248 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7249 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7250 CI->getArgOperand(ArgNo)->getType(),
7251 CI->getParamAttributes(ArgNo)));
7254 if (
Function *OldFn = CI->getCalledFunction()) {
7255 auto It = UpgradedIntrinsics.
find(OldFn);
7256 if (It != UpgradedIntrinsics.
end())
7260 BC && BC->getSrcTy() == BC->getDestTy() &&
7266 CI && CI->isMustTailCall() && CI->getNextNode() == BC) {
7267 BC->replaceAllUsesWith(CI);
7268 BC->eraseFromParent();
7278 return materializeForwardReferencedFunctions();
7281Error BitcodeReader::materializeModule() {
7282 if (
Error Err = materializeMetadata())
7286 WillMaterializeAllForwardRefs =
true;
7291 if (
Error Err = materialize(&
F))
7297 if (LastFunctionBlockBit || NextUnreadBit)
7299 ? LastFunctionBlockBit
7305 if (!BasicBlockFwdRefs.
empty())
7306 return error(
"Never resolved function from blockaddress");
7312 for (
auto &[OldFn, NewFn] : UpgradedIntrinsics) {
7313 for (User *U : OldFn->users()) {
7317 if (OldFn != NewFn) {
7318 if (!OldFn->use_empty())
7319 OldFn->replaceAllUsesWith(NewFn);
7320 OldFn->eraseFromParent();
7323 UpgradedIntrinsics.clear();
7338std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7339 return IdentifiedStructTypes;
7342ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7343 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7344 StringRef ModulePath, std::function<
bool(StringRef)> IsPrevailing,
7345 std::function<
void(ValueInfo)> OnValueInfo)
7346 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7347 ModulePath(ModulePath), IsPrevailing(IsPrevailing),
7348 OnValueInfo(OnValueInfo) {}
7350void ModuleSummaryIndexBitcodeReader::addThisModule() {
7355ModuleSummaryIndexBitcodeReader::getThisModule() {
7359template <
bool AllowNullValueInfo>
7360std::pair<ValueInfo, GlobalValue::GUID>
7361ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7362 auto VGI = ValueIdToValueInfoMap[ValueId];
7369 assert(AllowNullValueInfo || std::get<0>(VGI));
7373void ModuleSummaryIndexBitcodeReader::setValueGUID(
7375 StringRef SourceFileName) {
7377 if (ValueID < DefinedGUIDs.size())
7378 ValueGUID = DefinedGUIDs[ValueID];
7385 auto OriginalNameID = ValueGUID;
7389 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7397 ValueIdToValueInfoMap[ValueID] = std::make_pair(VI, OriginalNameID);
7405Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7407 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7414 if (!MaybeCurrentBit)
7421 SmallVector<uint64_t, 64>
Record;
7430 BitstreamEntry
Entry = MaybeEntry.
get();
7432 switch (
Entry.Kind) {
7435 return error(
"Malformed block");
7451 switch (MaybeRecord.
get()) {
7456 return error(
"Invalid vst_code_entry record");
7457 unsigned ValueID =
Record[0];
7459 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7460 assert(VLI != ValueIdToLinkageMap.
end() &&
7461 "No linkage found for VST entry?");
7470 return error(
"Invalid vst_code_fnentry record");
7471 unsigned ValueID =
Record[0];
7473 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7474 assert(VLI != ValueIdToLinkageMap.
end() &&
7475 "No linkage found for VST entry?");
7483 unsigned ValueID =
Record[0];
7487 ValueIdToValueInfoMap[ValueID] =
7498Error ModuleSummaryIndexBitcodeReader::parseModule() {
7502 SmallVector<uint64_t, 64>
Record;
7503 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7504 unsigned ValueId = 0;
7508 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
7511 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7513 switch (
Entry.Kind) {
7515 return error(
"Malformed block");
7527 if (
Error Err = readBlockInfo())
7533 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7534 !SeenGlobalValSummary) &&
7535 "Expected early VST parse via VSTOffset record");
7542 if (!SourceFileName.
empty())
7544 assert(!SeenValueSymbolTable &&
7545 "Already read VST when parsing summary block?");
7550 if (VSTOffset > 0) {
7551 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7553 SeenValueSymbolTable =
true;
7555 SeenGlobalValSummary =
true;
7556 if (
Error Err = parseEntireSummary(
Entry.ID))
7560 if (
Error Err = parseModuleStringTable())
7568 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7571 switch (MaybeBitCode.
get()) {
7575 if (
Error Err = parseVersionRecord(Record).takeError())
7583 return error(
"Invalid source filename record");
7590 return error(
"Invalid hash length " + Twine(
Record.size()));
7591 auto &Hash = getThisModule()->second;
7593 for (
auto &Val : Record) {
7594 assert(!(Val >> 32) &&
"Unexpected high bits set");
7602 return error(
"Invalid vstoffset record");
7606 VSTOffset =
Record[0] - 1;
7611 DefinedGUIDs.reserve(DefinedGUIDs.size() +
Record.size() / 2);
7612 for (
size_t i = 0; i <
Record.size(); i += 2)
7613 DefinedGUIDs.push_back(Record[i] << 32 | Record[i + 1]);
7623 ArrayRef<uint64_t> GVRecord;
7624 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7625 if (GVRecord.
size() <= 3)
7626 return error(
"Invalid global record");
7630 ValueIdToLinkageMap[ValueId++] =
Linkage;
7634 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7645ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7649 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7654ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7655 bool IsOldProfileFormat,
7656 bool HasProfile,
bool HasRelBF) {
7660 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7665 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7667 bool HasTailCall =
false;
7669 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7670 if (IsOldProfileFormat) {
7674 }
else if (HasProfile)
7675 std::tie(Hotness, HasTailCall) =
7709 static_cast<size_t>(
Record[Slot + 1])};
7732 while (Slot <
Record.size())
7736std::vector<FunctionSummary::ParamAccess>
7737ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7738 auto ReadRange = [&]() {
7740 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7742 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7749 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7750 while (!
Record.empty()) {
7751 PendingParamAccesses.emplace_back();
7752 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7754 ParamAccess.
Use = ReadRange();
7759 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7760 Call.Offsets = ReadRange();
7763 return PendingParamAccesses;
7766void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7767 ArrayRef<uint64_t> Record,
size_t &Slot,
7770 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7774void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7775 ArrayRef<uint64_t> Record) {
7783 while (Slot <
Record.size())
7784 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7787SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7788 ArrayRef<uint64_t> Record,
unsigned &
I) {
7789 SmallVector<unsigned> StackIdList;
7793 if (RadixArray.empty()) {
7794 unsigned NumStackEntries =
Record[
I++];
7796 StackIdList.
reserve(NumStackEntries);
7797 for (
unsigned J = 0; J < NumStackEntries; J++) {
7798 assert(Record[
I] < StackIds.size());
7799 StackIdList.
push_back(getStackIdIndex(Record[
I++]));
7802 unsigned RadixIndex =
Record[
I++];
7808 assert(RadixIndex < RadixArray.size());
7809 unsigned NumStackIds = RadixArray[RadixIndex++];
7810 StackIdList.
reserve(NumStackIds);
7811 while (NumStackIds--) {
7812 assert(RadixIndex < RadixArray.size());
7813 unsigned Elem = RadixArray[RadixIndex];
7814 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7815 RadixIndex = RadixIndex - Elem;
7816 assert(RadixIndex < RadixArray.size());
7817 Elem = RadixArray[RadixIndex];
7819 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7822 StackIdList.
push_back(getStackIdIndex(Elem));
7832 unsigned FirstWORef = Refs.
size() - WOCnt;
7833 unsigned RefNo = FirstWORef - ROCnt;
7834 for (; RefNo < FirstWORef; ++RefNo)
7835 Refs[RefNo].setReadOnly();
7836 for (; RefNo < Refs.
size(); ++RefNo)
7837 Refs[RefNo].setWriteOnly();
7842Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7845 SmallVector<uint64_t, 64>
Record;
7852 BitstreamEntry
Entry = MaybeEntry.
get();
7855 return error(
"Invalid Summary Block: record for version expected");
7860 return error(
"Invalid Summary Block: version expected");
7863 const bool IsOldProfileFormat =
Version == 1;
7866 const bool MemProfAfterFunctionSummary =
Version >= 13;
7868 return error(
"Invalid summary version " + Twine(
Version) +
" in module '" +
7869 ModulePath +
"'. Version should be in the range [1-" +
7875 GlobalValueSummary *LastSeenSummary =
nullptr;
7885 FunctionSummary *CurrentPrevailingFS =
nullptr;
7890 std::vector<GlobalValue::GUID> PendingTypeTests;
7891 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7892 PendingTypeCheckedLoadVCalls;
7893 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7894 PendingTypeCheckedLoadConstVCalls;
7895 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7897 std::vector<CallsiteInfo> PendingCallsites;
7898 std::vector<AllocInfo> PendingAllocs;
7899 std::vector<uint64_t> PendingContextIds;
7905 BitstreamEntry
Entry = MaybeEntry.
get();
7907 switch (
Entry.Kind) {
7910 return error(
"Malformed block");
7926 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7929 unsigned BitCode = MaybeBitCode.
get();
7946 ValueIdToValueInfoMap[ValueID] =
7964 unsigned ValueID =
Record[0];
7966 unsigned InstCount =
Record[2];
7968 unsigned NumRefs =
Record[3];
7969 unsigned NumRORefs = 0, NumWORefs = 0;
7970 int RefListStartIndex = 4;
7974 RefListStartIndex = 5;
7977 RefListStartIndex = 6;
7980 RefListStartIndex = 7;
7991 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7993 "Record size inconsistent with number of references");
7995 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8000 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8001 IsOldProfileFormat, HasProfile, HasRelBF);
8003 auto [
VI,
GUID] = getValueInfoFromValueId(ValueID);
8010 IsPrevailing(
VI.name());
8016 assert(!MemProfAfterFunctionSummary ||
8017 (PendingCallsites.empty() && PendingAllocs.empty()));
8018 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
8019 PendingCallsites.clear();
8020 PendingAllocs.clear();
8023 auto FS = std::make_unique<FunctionSummary>(
8025 std::move(Calls), std::move(PendingTypeTests),
8026 std::move(PendingTypeTestAssumeVCalls),
8027 std::move(PendingTypeCheckedLoadVCalls),
8028 std::move(PendingTypeTestAssumeConstVCalls),
8029 std::move(PendingTypeCheckedLoadConstVCalls),
8030 std::move(PendingParamAccesses), std::move(PendingCallsites),
8031 std::move(PendingAllocs));
8032 FS->setModulePath(getThisModule()->first());
8033 FS->setOriginalName(GUID);
8036 if (MemProfAfterFunctionSummary) {
8037 if (IsPrevailingSym)
8038 CurrentPrevailingFS =
FS.get();
8040 CurrentPrevailingFS =
nullptr;
8049 unsigned ValueID =
Record[0];
8051 unsigned AliaseeID =
Record[2];
8053 auto AS = std::make_unique<AliasSummary>(Flags);
8059 AS->setModulePath(getThisModule()->first());
8061 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
8063 if (!AliaseeInModule)
8064 return error(
"Alias expects aliasee summary to be parsed");
8065 AS->setAliasee(AliaseeVI, AliaseeInModule);
8067 auto GUID = getValueInfoFromValueId(ValueID);
8068 AS->setOriginalName(std::get<1>(GUID));
8074 unsigned ValueID =
Record[0];
8076 unsigned RefArrayStart = 2;
8077 GlobalVarSummary::GVarFlags GVF(
false,
8087 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8089 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8090 FS->setModulePath(getThisModule()->first());
8091 auto GUID = getValueInfoFromValueId(ValueID);
8092 FS->setOriginalName(std::get<1>(GUID));
8100 unsigned ValueID =
Record[0];
8103 unsigned NumRefs =
Record[3];
8104 unsigned RefListStartIndex = 4;
8105 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
8108 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8110 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
8111 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
8116 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8117 VS->setModulePath(getThisModule()->first());
8118 VS->setVTableFuncs(VTableFuncs);
8119 auto GUID = getValueInfoFromValueId(ValueID);
8120 VS->setOriginalName(std::get<1>(GUID));
8132 unsigned ValueID =
Record[0];
8135 unsigned InstCount =
Record[3];
8137 unsigned NumRefs =
Record[4];
8138 unsigned NumRORefs = 0, NumWORefs = 0;
8139 int RefListStartIndex = 5;
8143 RefListStartIndex = 6;
8144 size_t NumRefsIndex = 5;
8146 unsigned NumRORefsOffset = 1;
8147 RefListStartIndex = 7;
8150 RefListStartIndex = 8;
8152 RefListStartIndex = 9;
8154 NumRORefsOffset = 2;
8157 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
8159 NumRefs =
Record[NumRefsIndex];
8163 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8165 "Record size inconsistent with number of references");
8167 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8170 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8171 IsOldProfileFormat, HasProfile,
false);
8172 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8174 auto FS = std::make_unique<FunctionSummary>(
8176 std::move(Edges), std::move(PendingTypeTests),
8177 std::move(PendingTypeTestAssumeVCalls),
8178 std::move(PendingTypeCheckedLoadVCalls),
8179 std::move(PendingTypeTestAssumeConstVCalls),
8180 std::move(PendingTypeCheckedLoadConstVCalls),
8181 std::move(PendingParamAccesses), std::move(PendingCallsites),
8182 std::move(PendingAllocs));
8183 LastSeenSummary =
FS.get();
8184 if (MemProfAfterFunctionSummary)
8185 CurrentPrevailingFS =
FS.get();
8186 LastSeenGUID =
VI.getGUID();
8187 FS->setModulePath(ModuleIdMap[ModuleId]);
8195 unsigned ValueID =
Record[0];
8198 unsigned AliaseeValueId =
Record[3];
8200 auto AS = std::make_unique<AliasSummary>(Flags);
8201 LastSeenSummary = AS.get();
8202 AS->setModulePath(ModuleIdMap[ModuleId]);
8204 auto AliaseeVI = std::get<0>(
8205 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8207 auto AliaseeInModule =
8209 AS->setAliasee(AliaseeVI, AliaseeInModule);
8211 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8212 LastSeenGUID =
VI.getGUID();
8218 unsigned ValueID =
Record[0];
8221 unsigned RefArrayStart = 3;
8222 GlobalVarSummary::GVarFlags GVF(
false,
8232 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8234 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8235 LastSeenSummary =
FS.get();
8236 FS->setModulePath(ModuleIdMap[ModuleId]);
8237 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8238 LastSeenGUID =
VI.getGUID();
8245 if (!LastSeenSummary)
8246 return error(
"Name attachment that does not follow a combined record");
8250 LastSeenSummary =
nullptr;
8255 assert(PendingTypeTests.empty());
8260 assert(PendingTypeTestAssumeVCalls.empty());
8261 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8262 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8266 assert(PendingTypeCheckedLoadVCalls.empty());
8267 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8268 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8272 PendingTypeTestAssumeConstVCalls.push_back(
8277 PendingTypeCheckedLoadConstVCalls.push_back(
8284 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8285 StringRef
Name(Strtab.
data() + Record[
I],
8286 static_cast<size_t>(Record[
I + 1]));
8289 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, GUID);
8292 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8294 StringRef
Name(Strtab.
data() + Record[
I + 1],
8295 static_cast<size_t>(Record[
I + 2]));
8296 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8305 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8306 StringRef
Name(Strtab.
data() + Record[
I],
8307 static_cast<size_t>(Record[
I + 1]));
8310 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, GUID);
8313 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8315 StringRef
Name(Strtab.
data() + Record[
I + 1],
8316 static_cast<size_t>(Record[
I + 2]));
8317 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8328 parseTypeIdCompatibleVtableSummaryRecord(Record);
8336 PendingParamAccesses = parseParamAccesses(Record);
8343 assert(StackIds.empty());
8345 StackIds = ArrayRef<uint64_t>(Record);
8351 StackIds.reserve(
Record.size() / 2);
8352 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8353 StackIds.push_back(*R << 32 | *(R + 1));
8355 assert(StackIdToIndex.empty());
8357 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8362 RadixArray = ArrayRef<uint64_t>(Record);
8369 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8371 unsigned ValueID =
Record[0];
8372 SmallVector<unsigned> StackIdList;
8374 assert(R < StackIds.size());
8375 StackIdList.
push_back(getStackIdIndex(R));
8377 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8378 if (MemProfAfterFunctionSummary)
8380 CallsiteInfo({
VI, std::move(StackIdList)}));
8382 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8389 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8390 auto RecordIter =
Record.begin();
8391 unsigned ValueID = *RecordIter++;
8392 unsigned NumStackIds = *RecordIter++;
8393 unsigned NumVersions = *RecordIter++;
8394 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8395 SmallVector<unsigned> StackIdList;
8396 for (
unsigned J = 0; J < NumStackIds; J++) {
8397 assert(*RecordIter < StackIds.size());
8398 StackIdList.
push_back(getStackIdIndex(*RecordIter++));
8400 SmallVector<unsigned> Versions;
8401 for (
unsigned J = 0; J < NumVersions; J++)
8403 ValueInfo
VI = std::get<0>(
8404 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8405 if (MemProfAfterFunctionSummary)
8407 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8409 PendingCallsites.push_back(
8410 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8417 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8422 PendingContextIds.reserve(
Record.size() / 2);
8423 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8424 PendingContextIds.push_back(*R << 32 | *(R + 1));
8431 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8432 PendingContextIds.clear();
8436 std::vector<MIBInfo> MIBs;
8437 unsigned NumMIBs = 0;
8440 unsigned MIBsRead = 0;
8441 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8445 auto StackIdList = parseAllocInfoContext(Record,
I);
8446 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8452 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8454 assert(!PendingContextIds.empty() &&
8455 "Missing context ids for alloc sizes");
8456 unsigned ContextIdIndex = 0;
8462 while (MIBsRead++ < NumMIBs) {
8464 unsigned NumContextSizeInfoEntries =
Record[
I++];
8466 std::vector<ContextTotalSize> ContextSizes;
8467 ContextSizes.reserve(NumContextSizeInfoEntries);
8468 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8469 assert(ContextIdIndex < PendingContextIds.size());
8471 if (PendingContextIds[ContextIdIndex] == 0) {
8480 ContextSizes.push_back(
8481 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8483 AllContextSizes.push_back(std::move(ContextSizes));
8485 PendingContextIds.clear();
8487 AllocInfo AI(std::move(MIBs));
8488 if (!AllContextSizes.empty()) {
8489 assert(AI.MIBs.size() == AllContextSizes.size());
8490 AI.ContextSizeInfos = std::move(AllContextSizes);
8493 if (MemProfAfterFunctionSummary)
8494 CurrentPrevailingFS->
addAlloc(std::move(AI));
8496 PendingAllocs.push_back(std::move(AI));
8504 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8506 std::vector<MIBInfo> MIBs;
8507 unsigned NumMIBs =
Record[
I++];
8508 unsigned NumVersions =
Record[
I++];
8509 unsigned MIBsRead = 0;
8510 while (MIBsRead++ < NumMIBs) {
8513 SmallVector<unsigned> StackIdList;
8515 StackIdList = parseAllocInfoContext(Record,
I);
8516 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8519 SmallVector<uint8_t> Versions;
8520 for (
unsigned J = 0; J < NumVersions; J++)
8523 AllocInfo AI(std::move(Versions), std::move(MIBs));
8524 if (MemProfAfterFunctionSummary)
8525 CurrentPrevailingFS->
addAlloc(std::move(AI));
8527 PendingAllocs.push_back(std::move(AI));
8537Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8541 SmallVector<uint64_t, 64>
Record;
8543 SmallString<128> ModulePath;
8550 BitstreamEntry
Entry = MaybeEntry.
get();
8552 switch (
Entry.Kind) {
8555 return error(
"Malformed block");
8567 switch (MaybeRecord.
get()) {
8575 return error(
"Invalid code_entry record");
8577 LastSeenModule = TheIndex.
addModule(ModulePath);
8578 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8586 return error(
"Invalid hash length " + Twine(
Record.size()));
8587 if (!LastSeenModule)
8588 return error(
"Invalid hash that does not follow a module path");
8590 for (
auto &Val : Record) {
8591 assert(!(Val >> 32) &&
"Unexpected high bits set");
8592 LastSeenModule->
second[Pos++] = Val;
8595 LastSeenModule =
nullptr;
8608class BitcodeErrorCategoryType :
public std::error_category {
8609 const char *
name()
const noexcept
override {
8610 return "llvm.bitcode";
8613 std::string message(
int IE)
const override {
8616 case BitcodeError::CorruptedBitcode:
8617 return "Corrupted bitcode";
8626 static BitcodeErrorCategoryType ErrorCategory;
8627 return ErrorCategory;
8631 unsigned Block,
unsigned RecordID) {
8633 return std::move(Err);
8642 switch (Entry.Kind) {
8647 return error(
"Malformed block");
8651 return std::move(Err);
8661 if (MaybeRecord.
get() == RecordID)
8672Expected<std::vector<BitcodeModule>>
8676 return FOrErr.takeError();
8677 return std::move(FOrErr->Mods);
8702 switch (Entry.Kind) {
8705 return error(
"Malformed block");
8708 uint64_t IdentificationBit = -1ull;
8712 return std::move(Err);
8718 Entry = MaybeEntry.
get();
8723 return error(
"Malformed block");
8729 return std::move(Err);
8748 if (!
I.Strtab.empty())
8755 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8756 F.StrtabForSymtab = *Strtab;
8772 if (
F.Symtab.empty())
8773 F.Symtab = *SymtabOrErr;
8778 return std::move(Err);
8783 return std::move(E);
8798BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8799 bool ShouldLazyLoadMetadata,
bool IsImporting,
8803 std::string ProducerIdentification;
8804 if (IdentificationBit != -1ull) {
8806 return std::move(JumpFailed);
8809 return std::move(
E);
8813 return std::move(JumpFailed);
8814 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8817 std::unique_ptr<Module>
M =
8818 std::make_unique<Module>(ModuleIdentifier,
Context);
8819 M->setMaterializer(R);
8822 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8823 IsImporting, Callbacks))
8824 return std::move(Err);
8826 if (MaterializeAll) {
8828 if (
Error Err =
M->materializeAll())
8829 return std::move(Err);
8832 if (
Error Err =
R->materializeForwardReferencedFunctions())
8833 return std::move(Err);
8836 return std::move(M);
8839Expected<std::unique_ptr<Module>>
8842 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8852 std::function<
bool(
StringRef)> IsPrevailing,
8853 std::function<
void(
ValueInfo)> OnValueInfo) {
8858 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8859 ModulePath, IsPrevailing, OnValueInfo);
8860 return R.parseModule();
8867 return std::move(JumpFailed);
8869 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8870 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8871 ModuleIdentifier, 0);
8873 if (
Error Err = R.parseModule())
8874 return std::move(Err);
8876 return std::move(Index);
8882 return std::move(Err);
8888 return std::move(
E);
8890 switch (Entry.Kind) {
8893 return error(
"Malformed block");
8896 return std::make_pair(
false,
false);
8908 switch (MaybeBitCode.
get()) {
8914 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
8916 bool EnableSplitLTOUnit = Flags & 0x8;
8917 bool UnifiedLTO = Flags & 0x200;
8918 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8929 return std::move(JumpFailed);
8932 return std::move(Err);
8937 return std::move(E);
8939 switch (Entry.Kind) {
8941 return error(
"Malformed block");
8952 return Flags.takeError();
8962 return std::move(Err);
8969 return StreamFailed.takeError();
8979 if (MsOrErr->size() != 1)
8980 return error(
"Expected a single module");
8982 return (*MsOrErr)[0];
8985Expected<std::unique_ptr<Module>>
8987 bool ShouldLazyLoadMetadata,
bool IsImporting,
8993 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8998 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
8999 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
9001 IsImporting, Callbacks);
9003 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
9009 return getModuleImpl(Context,
true,
false,
false, Callbacks);
9021 return BM->parseModule(Context, Callbacks);
9054 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
9063 return BM->getSummary();
9071 return BM->getLTOInfo();
9076 bool IgnoreEmptyThinLTOIndexFile) {
9081 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
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 AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val, bool &IsElementwise)
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 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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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.
static constexpr Value * getValue(Ty &ValueOrUse)
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
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
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
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; assumes that the block is well-formed.
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 Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(StringRef)> IsPrevailing=nullptr, std::function< void(ValueInfo)> OnValueInfo=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
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.
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
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.
@ MIN_BYTE_BITS
Minimum number of bits that can be specified.
@ MAX_BYTE_BITS
Maximum number of bits that can be specified Note that bit width is stored in the Type classes Subcla...
static LLVM_ABI ByteType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing a ByteType.
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)
Provid