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 Triple BitcodeTargetTriple;
586 uint64_t NextUnreadBit = 0;
588 uint64_t LastFunctionBlockBit = 0;
589 bool SeenValueSymbolTable =
false;
590 uint64_t VSTOffset = 0;
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,
712 Triple BitcodeTargetTriple);
714 Error materializeForwardReferencedFunctions();
716 Error materialize(GlobalValue *GV)
override;
717 Error materializeModule()
override;
718 std::vector<StructType *> getIdentifiedStructTypes()
const override;
722 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
723 bool IsImporting, ParserCallbacks Callbacks = {});
725 static uint64_t decodeSignRotatedValue(uint64_t V);
728 Error materializeMetadata()
override;
730 void setStripDebugInfo()
override;
733 std::vector<StructType *> IdentifiedStructTypes;
734 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
735 StructType *createIdentifiedStructType(LLVMContext &
Context);
737 static constexpr unsigned InvalidTypeID = ~0
u;
739 Type *getTypeByID(
unsigned ID);
740 Type *getPtrElementTypeByID(
unsigned ID);
741 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
742 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
745 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
746 Expected<Constant *> getValueForInitializer(
unsigned ID);
748 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
749 BasicBlock *ConstExprInsertBB) {
756 return MDLoader->getMetadataFwdRefOrLoad(
ID);
760 if (
ID >= FunctionBBs.size())
return nullptr;
761 return FunctionBBs[
ID];
765 if (i-1 < MAttributes.size())
766 return MAttributes[i-1];
767 return AttributeList();
773 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
774 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
775 BasicBlock *ConstExprInsertBB) {
776 if (Slot ==
Record.size())
return true;
777 unsigned ValNo = (unsigned)Record[Slot++];
780 ValNo = InstNum - ValNo;
781 if (ValNo < InstNum) {
785 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
787 "Incorrect type ID stored for value");
788 return ResVal ==
nullptr;
790 if (Slot ==
Record.size())
793 TypeID = (unsigned)Record[Slot++];
794 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
796 return ResVal ==
nullptr;
799 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
800 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
801 BasicBlock *ConstExprInsertBB) {
802 if (Slot ==
Record.size())
807 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
810 if (Slot ==
Record.size())
812 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
820 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
821 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
822 BasicBlock *ConstExprInsertBB) {
823 if (
getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
831 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
832 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
833 BasicBlock *ConstExprInsertBB) {
834 ResVal =
getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
835 return ResVal ==
nullptr;
840 Value *
getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
841 unsigned InstNum,
Type *Ty,
unsigned TyID,
842 BasicBlock *ConstExprInsertBB) {
843 if (Slot ==
Record.size())
return nullptr;
844 unsigned ValNo = (unsigned)Record[Slot];
847 ValNo = InstNum - ValNo;
848 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
852 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
853 unsigned InstNum,
Type *Ty,
unsigned TyID,
854 BasicBlock *ConstExprInsertBB) {
855 if (Slot ==
Record.size())
return nullptr;
856 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
859 ValNo = InstNum - ValNo;
860 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
863 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
866 if (
Record.size() - OpNum < 2)
867 return error(
"Too few records for range");
869 unsigned LowerActiveWords =
Record[OpNum];
870 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
871 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
872 return error(
"Too few records for range");
875 OpNum += LowerActiveWords;
878 OpNum += UpperActiveWords;
881 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
882 int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
883 return ConstantRange(APInt(
BitWidth, Start,
true),
888 Expected<ConstantRange>
889 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
890 if (
Record.size() - OpNum < 1)
891 return error(
"Too few records for range");
893 return readConstantRange(Record, OpNum,
BitWidth);
899 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
904 Error parseAlignmentValue(uint64_t
Exponent, MaybeAlign &Alignment);
905 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
907 ParserCallbacks Callbacks = {});
909 Error parseComdatRecord(ArrayRef<uint64_t> Record);
910 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
911 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
912 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
913 ArrayRef<uint64_t> Record);
915 Error parseAttributeBlock();
916 Error parseAttributeGroupBlock();
917 Error parseTypeTable();
918 Error parseTypeTableBody();
919 Error parseOperandBundleTags();
920 Error parseSyncScopeNames();
922 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
923 unsigned NameIndex, Triple &TT);
924 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta, Function *
F,
925 ArrayRef<uint64_t> Record);
927 Error parseGlobalValueSymbolTable();
928 Error parseConstants();
929 Error rememberAndSkipFunctionBodies();
930 Error rememberAndSkipFunctionBody();
932 Error rememberAndSkipMetadata();
934 Error parseFunctionBody(Function *
F);
935 Error globalCleanup();
936 Error resolveGlobalAndIndirectSymbolInits();
937 Error parseUseLists();
938 Error findFunctionInStream(
940 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
947class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
949 ModuleSummaryIndex &TheIndex;
953 bool SeenGlobalValSummary =
false;
956 bool SeenValueSymbolTable =
false;
960 uint64_t VSTOffset = 0;
970 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
971 ValueIdToValueInfoMap;
977 DenseMap<uint64_t, StringRef> ModuleIdMap;
980 std::string SourceFileName;
984 StringRef ModulePath;
988 std::function<bool(StringRef)> IsPrevailing =
nullptr;
991 std::function<void(ValueInfo)> OnValueInfo =
nullptr;
995 std::vector<uint64_t> StackIds;
999 std::vector<uint64_t> RadixArray;
1004 std::vector<unsigned> StackIdToIndex;
1007 std::vector<uint64_t> DefinedGUIDs;
1010 ModuleSummaryIndexBitcodeReader(
1011 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
1012 StringRef ModulePath,
1013 std::function<
bool(StringRef)> IsPrevailing =
nullptr,
1014 std::function<
void(ValueInfo)> OnValueInfo =
nullptr);
1019 void setValueGUID(uint64_t ValueID, StringRef
ValueName,
1021 StringRef SourceFileName);
1022 Error parseValueSymbolTable(
1024 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1027 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1028 bool HasProfile,
bool HasRelBF);
1029 Error parseEntireSummary(
unsigned ID);
1030 Error parseModuleStringTable();
1031 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1032 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1034 std::vector<FunctionSummary::ParamAccess>
1035 parseParamAccesses(ArrayRef<uint64_t> Record);
1036 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1040 static constexpr unsigned UninitializedStackIdIndex =
1041 std::numeric_limits<unsigned>::max();
1043 unsigned getStackIdIndex(
unsigned LocalIndex) {
1044 unsigned &
Index = StackIdToIndex[LocalIndex];
1047 if (Index == UninitializedStackIdIndex)
1052 template <
bool AllowNullValueInfo = false>
1053 std::pair<ValueInfo, GlobalValue::GUID>
1054 getValueInfoFromValueId(
unsigned ValueId);
1056 void addThisModule();
1072 return std::error_code();
1078 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1079 BitcodeTargetTriple(TTriple),
1080 ValueList(this->Stream.SizeInBytes(),
1082 return materializeValue(
ValID, InsertBB);
1084 this->ProducerIdentification = std::string(ProducerIdentification);
1087Error BitcodeReader::materializeForwardReferencedFunctions() {
1088 if (WillMaterializeAllForwardRefs)
1092 WillMaterializeAllForwardRefs =
true;
1094 while (!BasicBlockFwdRefQueue.empty()) {
1095 Function *
F = BasicBlockFwdRefQueue.front();
1096 BasicBlockFwdRefQueue.pop_front();
1097 assert(
F &&
"Expected valid function");
1098 if (!BasicBlockFwdRefs.
count(
F))
1106 if (!
F->isMaterializable())
1107 return error(
"Never resolved function from blockaddress");
1110 if (
Error Err = materialize(
F))
1113 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1115 for (Function *
F : BackwardRefFunctions)
1116 if (
Error Err = materialize(
F))
1118 BackwardRefFunctions.clear();
1121 WillMaterializeAllForwardRefs =
false;
1186 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1187 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1188 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1189 Flags.NoInline = (RawFlags >> 4) & 0x1;
1190 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1191 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1192 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1193 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1194 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1210 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1);
1211 RawFlags = RawFlags >> 4;
1212 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1216 bool Live = (RawFlags & 0x2) || Version < 3;
1217 bool Local = (RawFlags & 0x4);
1218 bool AutoHide = (RawFlags & 0x8);
1221 Live,
Local, AutoHide, IK,
1222 NoRenameOnPromotion);
1228 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1229 (RawFlags & 0x4) ?
true :
false,
1233static std::pair<CalleeInfo::HotnessType, bool>
1237 bool HasTailCall = (RawFlags & 0x8);
1238 return {Hotness, HasTailCall};
1243 bool &HasTailCall) {
1244 static constexpr unsigned RelBlockFreqBits = 28;
1245 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1246 RelBF = RawFlags & RelBlockFreqMask;
1247 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1272 case 0:
return false;
1273 case 1:
return true;
1335 bool IsFP = Ty->isFPOrFPVectorTy();
1337 if (!IsFP && !Ty->isIntOrIntVectorTy())
1344 return IsFP ? Instruction::FNeg : -1;
1349 bool IsFP = Ty->isFPOrFPVectorTy();
1351 if (!IsFP && !Ty->isIntOrIntVectorTy())
1358 return IsFP ? Instruction::FAdd : Instruction::Add;
1360 return IsFP ? Instruction::FSub : Instruction::Sub;
1362 return IsFP ? Instruction::FMul : Instruction::Mul;
1364 return IsFP ? -1 : Instruction::UDiv;
1366 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1368 return IsFP ? -1 : Instruction::URem;
1370 return IsFP ? Instruction::FRem : Instruction::SRem;
1372 return IsFP ? -1 : Instruction::Shl;
1374 return IsFP ? -1 : Instruction::LShr;
1376 return IsFP ? -1 : Instruction::AShr;
1378 return IsFP ? -1 : Instruction::And;
1380 return IsFP ? -1 : Instruction::Or;
1382 return IsFP ? -1 : Instruction::Xor;
1387 bool &IsElementwise) {
1485Type *BitcodeReader::getTypeByID(
unsigned ID) {
1487 if (
ID >= TypeList.size())
1490 if (
Type *Ty = TypeList[
ID])
1495 return TypeList[
ID] = createIdentifiedStructType(
Context);
1498unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1499 auto It = ContainedTypeIDs.
find(
ID);
1500 if (It == ContainedTypeIDs.
end())
1501 return InvalidTypeID;
1503 if (Idx >= It->second.size())
1504 return InvalidTypeID;
1506 return It->second[Idx];
1509Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1510 if (
ID >= TypeList.size())
1517 return getTypeByID(getContainedTypeID(
ID, 0));
1520unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1521 ArrayRef<unsigned> ChildTypeIDs) {
1522 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1523 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1524 auto It = VirtualTypeIDs.
find(CacheKey);
1525 if (It != VirtualTypeIDs.
end()) {
1531 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1532 "Incorrect cached contained type IDs");
1536 unsigned TypeID = TypeList.size();
1537 TypeList.push_back(Ty);
1538 if (!ChildTypeIDs.
empty())
1559 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1573 if (Opcode == Instruction::GetElementPtr)
1577 case Instruction::FNeg:
1578 case Instruction::Select:
1579 case Instruction::ICmp:
1580 case Instruction::FCmp:
1587Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1588 BasicBlock *InsertBB) {
1590 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1592 return ValueList[StartValID];
1594 SmallDenseMap<unsigned, Value *> MaterializedValues;
1595 SmallVector<unsigned> Worklist;
1597 while (!Worklist.
empty()) {
1598 unsigned ValID = Worklist.
back();
1599 if (MaterializedValues.
count(ValID)) {
1605 if (ValID >= ValueList.
size() || !ValueList[ValID])
1606 return error(
"Invalid value ID");
1608 Value *
V = ValueList[ValID];
1611 MaterializedValues.
insert({ValID,
V});
1619 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1620 auto It = MaterializedValues.
find(OpID);
1621 if (It != MaterializedValues.
end())
1622 Ops.push_back(It->second);
1629 if (
Ops.size() != BC->getOperandIDs().size())
1631 std::reverse(
Ops.begin(),
Ops.end());
1648 switch (BC->Opcode) {
1649 case BitcodeConstant::ConstantPtrAuthOpcode: {
1652 return error(
"ptrauth key operand must be ConstantInt");
1656 return error(
"ptrauth disc operand must be ConstantInt");
1659 ConstOps.
size() > 4 ? ConstOps[4]
1664 "ptrauth deactivation symbol operand must be a pointer");
1667 DeactivationSymbol);
1670 case BitcodeConstant::NoCFIOpcode: {
1673 return error(
"no_cfi operand must be GlobalValue");
1677 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1680 return error(
"dso_local operand must be GlobalValue");
1684 case BitcodeConstant::BlockAddressOpcode: {
1687 return error(
"blockaddress operand must be a function");
1692 unsigned BBID = BC->BlockAddressBB;
1695 return error(
"Invalid ID");
1698 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1700 return error(
"Invalid ID");
1707 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1709 BasicBlockFwdRefQueue.push_back(Fn);
1710 if (FwdBBs.size() < BBID + 1)
1711 FwdBBs.resize(BBID + 1);
1719 case BitcodeConstant::ConstantStructOpcode: {
1721 if (
ST->getNumElements() != ConstOps.
size())
1722 return error(
"Invalid number of elements in struct initializer");
1724 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1725 if (
Op->getType() != Ty)
1726 return error(
"Incorrect type in struct initializer");
1731 case BitcodeConstant::ConstantArrayOpcode: {
1733 if (AT->getNumElements() != ConstOps.
size())
1734 return error(
"Invalid number of elements in array initializer");
1736 for (Constant *
Op : ConstOps)
1737 if (
Op->getType() != AT->getElementType())
1738 return error(
"Incorrect type in array initializer");
1743 case BitcodeConstant::ConstantVectorOpcode: {
1745 if (VT->getNumElements() != ConstOps.size())
1746 return error(
"Invalid number of elements in vector initializer");
1748 for (Constant *
Op : ConstOps)
1749 if (
Op->getType() != VT->getElementType())
1750 return error(
"Incorrect type in vector initializer");
1755 case Instruction::GetElementPtr:
1757 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1760 case Instruction::ExtractElement:
1763 case Instruction::InsertElement:
1767 case Instruction::ShuffleVector: {
1768 SmallVector<int, 16>
Mask;
1780 MaterializedValues.
insert({ValID,
C});
1786 return error(Twine(
"Value referenced by initializer is an unsupported "
1787 "constant expression of type ") +
1788 BC->getOpcodeName());
1794 BC->getType(),
"constexpr", InsertBB);
1797 "constexpr", InsertBB);
1800 Ops[1],
"constexpr", InsertBB);
1803 I->setHasNoSignedWrap();
1805 I->setHasNoUnsignedWrap();
1811 switch (BC->Opcode) {
1812 case BitcodeConstant::ConstantVectorOpcode: {
1813 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1816 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1823 case BitcodeConstant::ConstantStructOpcode:
1824 case BitcodeConstant::ConstantArrayOpcode: {
1828 "constexpr.ins", InsertBB);
1832 case Instruction::ICmp:
1833 case Instruction::FCmp:
1836 "constexpr", InsertBB);
1838 case Instruction::GetElementPtr:
1844 case Instruction::Select:
1847 case Instruction::ExtractElement:
1850 case Instruction::InsertElement:
1854 case Instruction::ShuffleVector:
1855 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1863 MaterializedValues.
insert({ValID,
I});
1867 return MaterializedValues[StartValID];
1870Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1871 Expected<Value *> MaybeV = materializeValue(
ID,
nullptr);
1879StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1882 IdentifiedStructTypes.push_back(Ret);
1886StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1888 IdentifiedStructTypes.push_back(Ret);
1904 case Attribute::ZExt:
return 1 << 0;
1905 case Attribute::SExt:
return 1 << 1;
1906 case Attribute::NoReturn:
return 1 << 2;
1907 case Attribute::InReg:
return 1 << 3;
1908 case Attribute::StructRet:
return 1 << 4;
1909 case Attribute::NoUnwind:
return 1 << 5;
1910 case Attribute::NoAlias:
return 1 << 6;
1911 case Attribute::ByVal:
return 1 << 7;
1912 case Attribute::Nest:
return 1 << 8;
1913 case Attribute::ReadNone:
return 1 << 9;
1914 case Attribute::ReadOnly:
return 1 << 10;
1915 case Attribute::NoInline:
return 1 << 11;
1916 case Attribute::AlwaysInline:
return 1 << 12;
1917 case Attribute::OptimizeForSize:
return 1 << 13;
1918 case Attribute::StackProtect:
return 1 << 14;
1919 case Attribute::StackProtectReq:
return 1 << 15;
1920 case Attribute::Alignment:
return 31 << 16;
1922 case Attribute::NoRedZone:
return 1 << 22;
1923 case Attribute::NoImplicitFloat:
return 1 << 23;
1924 case Attribute::Naked:
return 1 << 24;
1925 case Attribute::InlineHint:
return 1 << 25;
1926 case Attribute::StackAlignment:
return 7 << 26;
1927 case Attribute::ReturnsTwice:
return 1 << 29;
1928 case Attribute::UWTable:
return 1 << 30;
1929 case Attribute::NonLazyBind:
return 1U << 31;
1930 case Attribute::SanitizeAddress:
return 1ULL << 32;
1931 case Attribute::MinSize:
return 1ULL << 33;
1932 case Attribute::NoDuplicate:
return 1ULL << 34;
1933 case Attribute::StackProtectStrong:
return 1ULL << 35;
1934 case Attribute::SanitizeThread:
return 1ULL << 36;
1935 case Attribute::SanitizeMemory:
return 1ULL << 37;
1936 case Attribute::NoBuiltin:
return 1ULL << 38;
1937 case Attribute::Returned:
return 1ULL << 39;
1938 case Attribute::Cold:
return 1ULL << 40;
1939 case Attribute::Builtin:
return 1ULL << 41;
1940 case Attribute::OptimizeNone:
return 1ULL << 42;
1941 case Attribute::InAlloca:
return 1ULL << 43;
1942 case Attribute::NonNull:
return 1ULL << 44;
1943 case Attribute::JumpTable:
return 1ULL << 45;
1944 case Attribute::Convergent:
return 1ULL << 46;
1945 case Attribute::SafeStack:
return 1ULL << 47;
1946 case Attribute::NoRecurse:
return 1ULL << 48;
1949 case Attribute::SwiftSelf:
return 1ULL << 51;
1950 case Attribute::SwiftError:
return 1ULL << 52;
1951 case Attribute::WriteOnly:
return 1ULL << 53;
1952 case Attribute::Speculatable:
return 1ULL << 54;
1953 case Attribute::StrictFP:
return 1ULL << 55;
1954 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1955 case Attribute::NoCfCheck:
return 1ULL << 57;
1956 case Attribute::OptForFuzzing:
return 1ULL << 58;
1957 case Attribute::ShadowCallStack:
return 1ULL << 59;
1958 case Attribute::SpeculativeLoadHardening:
1960 case Attribute::ImmArg:
1962 case Attribute::WillReturn:
1964 case Attribute::NoFree:
1980 if (
I == Attribute::Alignment)
1981 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1982 else if (
I == Attribute::StackAlignment)
1983 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1985 B.addTypeAttr(
I,
nullptr);
1999 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
2001 "Alignment must be a power of two.");
2004 B.addAlignmentAttr(Alignment);
2006 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
2007 (EncodedAttrs & 0xffff);
2009 if (AttrIdx == AttributeList::FunctionIndex) {
2012 if (Attrs & (1ULL << 9)) {
2014 Attrs &= ~(1ULL << 9);
2017 if (Attrs & (1ULL << 10)) {
2019 Attrs &= ~(1ULL << 10);
2022 if (Attrs & (1ULL << 49)) {
2024 Attrs &= ~(1ULL << 49);
2027 if (Attrs & (1ULL << 50)) {
2029 Attrs &= ~(1ULL << 50);
2032 if (Attrs & (1ULL << 53)) {
2034 Attrs &= ~(1ULL << 53);
2038 B.addMemoryAttr(ME);
2042 if (Attrs & (1ULL << 21)) {
2043 Attrs &= ~(1ULL << 21);
2050Error BitcodeReader::parseAttributeBlock() {
2054 if (!MAttributes.empty())
2055 return error(
"Invalid multiple blocks");
2057 SmallVector<uint64_t, 64>
Record;
2066 BitstreamEntry
Entry = MaybeEntry.
get();
2068 switch (
Entry.Kind) {
2071 return error(
"Malformed block");
2084 switch (MaybeRecord.
get()) {
2090 return error(
"Invalid parameter attribute record");
2092 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2098 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2102 for (uint64_t Val : Record)
2103 Attrs.push_back(MAttributeGroups[Val]);
2105 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2118 return Attribute::Alignment;
2120 return Attribute::AlwaysInline;
2122 return Attribute::Builtin;
2124 return Attribute::ByVal;
2126 return Attribute::InAlloca;
2128 return Attribute::Cold;
2130 return Attribute::Convergent;
2132 return Attribute::DisableSanitizerInstrumentation;
2134 return Attribute::ElementType;
2136 return Attribute::FnRetThunkExtern;
2138 return Attribute::Flatten;
2140 return Attribute::InlineHint;
2142 return Attribute::InReg;
2144 return Attribute::JumpTable;
2146 return Attribute::Memory;
2148 return Attribute::NoFPClass;
2150 return Attribute::MinSize;
2152 return Attribute::Naked;
2154 return Attribute::Nest;
2156 return Attribute::NoAlias;
2158 return Attribute::NoBuiltin;
2160 return Attribute::NoCallback;
2162 return Attribute::NoDivergenceSource;
2164 return Attribute::NoDuplicate;
2166 return Attribute::NoFree;
2168 return Attribute::NoImplicitFloat;
2170 return Attribute::NoInline;
2172 return Attribute::NoRecurse;
2174 return Attribute::NoMerge;
2176 return Attribute::NonLazyBind;
2178 return Attribute::NonNull;
2180 return Attribute::Dereferenceable;
2182 return Attribute::DereferenceableOrNull;
2184 return Attribute::AllocAlign;
2186 return Attribute::AllocKind;
2188 return Attribute::AllocSize;
2190 return Attribute::AllocatedPointer;
2192 return Attribute::NoRedZone;
2194 return Attribute::NoReturn;
2196 return Attribute::NoSync;
2198 return Attribute::NoCfCheck;
2200 return Attribute::NoProfile;
2202 return Attribute::SkipProfile;
2204 return Attribute::NoUnwind;
2206 return Attribute::NoSanitizeBounds;
2208 return Attribute::NoSanitizeCoverage;
2210 return Attribute::NullPointerIsValid;
2212 return Attribute::OptimizeForDebugging;
2214 return Attribute::OptForFuzzing;
2216 return Attribute::OptimizeForSize;
2218 return Attribute::OptimizeNone;
2220 return Attribute::ReadNone;
2222 return Attribute::ReadOnly;
2224 return Attribute::Returned;
2226 return Attribute::ReturnsTwice;
2228 return Attribute::SExt;
2230 return Attribute::Speculatable;
2232 return Attribute::StackAlignment;
2234 return Attribute::StackProtect;
2236 return Attribute::StackProtectReq;
2238 return Attribute::StackProtectStrong;
2240 return Attribute::SafeStack;
2242 return Attribute::ShadowCallStack;
2244 return Attribute::StrictFP;
2246 return Attribute::StructRet;
2248 return Attribute::SanitizeAddress;
2250 return Attribute::SanitizeHWAddress;
2252 return Attribute::SanitizeThread;
2254 return Attribute::SanitizeType;
2256 return Attribute::SanitizeMemory;
2258 return Attribute::SanitizeNumericalStability;
2260 return Attribute::SanitizeRealtime;
2262 return Attribute::SanitizeRealtimeBlocking;
2264 return Attribute::SanitizeAllocToken;
2266 return Attribute::SpeculativeLoadHardening;
2268 return Attribute::SwiftError;
2270 return Attribute::SwiftSelf;
2272 return Attribute::SwiftAsync;
2274 return Attribute::UWTable;
2276 return Attribute::VScaleRange;
2278 return Attribute::WillReturn;
2280 return Attribute::WriteOnly;
2282 return Attribute::ZExt;
2284 return Attribute::ImmArg;
2286 return Attribute::SanitizeMemTag;
2288 return Attribute::Preallocated;
2290 return Attribute::NoUndef;
2292 return Attribute::ByRef;
2294 return Attribute::MustProgress;
2296 return Attribute::Hot;
2298 return Attribute::PresplitCoroutine;
2300 return Attribute::Writable;
2302 return Attribute::CoroDestroyOnlyWhenComplete;
2304 return Attribute::DeadOnUnwind;
2306 return Attribute::Range;
2308 return Attribute::Initializes;
2310 return Attribute::CoroElideSafe;
2312 return Attribute::NoExt;
2314 return Attribute::Captures;
2316 return Attribute::DeadOnReturn;
2318 return Attribute::NoCreateUndefOrPoison;
2320 return Attribute::DenormalFPEnv;
2322 return Attribute::NoOutline;
2324 return Attribute::NoIPA;
2329 MaybeAlign &Alignment) {
2332 if (
Exponent > Value::MaxAlignmentExponent + 1)
2333 return error(
"Invalid alignment value");
2338Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2340 if (*Kind == Attribute::None)
2341 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2346 switch (EncodedKind) {
2370Error BitcodeReader::parseAttributeGroupBlock() {
2374 if (!MAttributeGroups.empty())
2375 return error(
"Invalid multiple blocks");
2377 SmallVector<uint64_t, 64>
Record;
2384 BitstreamEntry
Entry = MaybeEntry.
get();
2386 switch (
Entry.Kind) {
2389 return error(
"Malformed block");
2402 switch (MaybeRecord.
get()) {
2407 return error(
"Invalid grp record");
2409 uint64_t GrpID =
Record[0];
2410 uint64_t Idx =
Record[1];
2414 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2415 if (Record[i] == 0) {
2416 Attribute::AttrKind
Kind;
2417 uint64_t EncodedKind =
Record[++i];
2418 if (Idx == AttributeList::FunctionIndex &&
2427 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2433 if (Kind == Attribute::ByVal)
2434 B.addByValAttr(
nullptr);
2435 else if (Kind == Attribute::StructRet)
2436 B.addStructRetAttr(
nullptr);
2437 else if (Kind == Attribute::InAlloca)
2438 B.addInAllocaAttr(
nullptr);
2439 else if (Kind == Attribute::UWTable)
2440 B.addUWTableAttr(UWTableKind::Default);
2441 else if (Kind == Attribute::DeadOnReturn)
2442 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2443 else if (Attribute::isEnumAttrKind(Kind))
2444 B.addAttribute(Kind);
2446 return error(
"Not an enum attribute");
2447 }
else if (Record[i] == 1) {
2448 Attribute::AttrKind
Kind;
2449 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2451 if (!Attribute::isIntAttrKind(Kind))
2452 return error(
"Not an int attribute");
2453 if (Kind == Attribute::Alignment)
2454 B.addAlignmentAttr(Record[++i]);
2455 else if (Kind == Attribute::StackAlignment)
2456 B.addStackAlignmentAttr(Record[++i]);
2457 else if (Kind == Attribute::Dereferenceable)
2458 B.addDereferenceableAttr(Record[++i]);
2459 else if (Kind == Attribute::DereferenceableOrNull)
2460 B.addDereferenceableOrNullAttr(Record[++i]);
2461 else if (Kind == Attribute::DeadOnReturn)
2462 B.addDeadOnReturnAttr(
2464 else if (Kind == Attribute::AllocSize)
2465 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2466 else if (Kind == Attribute::VScaleRange)
2467 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2468 else if (Kind == Attribute::UWTable)
2470 else if (Kind == Attribute::AllocKind)
2471 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2472 else if (Kind == Attribute::Memory) {
2473 uint64_t EncodedME =
Record[++i];
2474 const uint8_t
Version = (EncodedME >> 56);
2493 B.addMemoryAttr(ME);
2498 EncodedME & 0x00FFFFFFFFFFFFFFULL);
2503 IRMemLocation::TargetMem0,
2504 ME.
getModRef(IRMemLocation::InaccessibleMem)) |
2506 IRMemLocation::TargetMem1,
2507 ME.
getModRef(IRMemLocation::InaccessibleMem));
2508 B.addMemoryAttr(ME);
2510 }
else if (Kind == Attribute::Captures)
2512 else if (Kind == Attribute::NoFPClass)
2515 else if (Kind == Attribute::DenormalFPEnv) {
2516 B.addDenormalFPEnvAttr(
2519 }
else if (Record[i] == 3 || Record[i] == 4) {
2521 SmallString<64> KindStr;
2522 SmallString<64> ValStr;
2524 while (Record[i] != 0 && i != e)
2526 assert(Record[i] == 0 &&
"Kind string not null terminated");
2531 while (Record[i] != 0 && i != e)
2533 assert(Record[i] == 0 &&
"Value string not null terminated");
2536 B.addAttribute(KindStr.
str(), ValStr.
str());
2537 }
else if (Record[i] == 5 || Record[i] == 6) {
2538 bool HasType =
Record[i] == 6;
2539 Attribute::AttrKind
Kind;
2540 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2542 if (!Attribute::isTypeAttrKind(Kind))
2543 return error(
"Not a type attribute");
2545 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2546 }
else if (Record[i] == 7) {
2547 Attribute::AttrKind
Kind;
2550 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2552 if (!Attribute::isConstantRangeAttrKind(Kind))
2553 return error(
"Not a ConstantRange attribute");
2555 Expected<ConstantRange> MaybeCR =
2556 readBitWidthAndConstantRange(Record, i);
2561 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2562 }
else if (Record[i] == 8) {
2563 Attribute::AttrKind
Kind;
2566 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2568 if (!Attribute::isConstantRangeListAttrKind(Kind))
2569 return error(
"Not a constant range list attribute");
2573 return error(
"Too few records for constant range list");
2574 unsigned RangeSize =
Record[i++];
2576 for (
unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2577 Expected<ConstantRange> MaybeCR =
2578 readConstantRange(Record, i,
BitWidth);
2586 return error(
"Invalid (unordered or overlapping) range list");
2587 B.addConstantRangeListAttr(Kind, Val);
2589 return error(
"Invalid attribute group entry");
2594 B.addMemoryAttr(ME);
2597 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2604Error BitcodeReader::parseTypeTable() {
2608 return parseTypeTableBody();
2611Error BitcodeReader::parseTypeTableBody() {
2612 if (!TypeList.empty())
2613 return error(
"Invalid multiple blocks");
2615 SmallVector<uint64_t, 64>
Record;
2616 unsigned NumRecords = 0;
2625 BitstreamEntry
Entry = MaybeEntry.
get();
2627 switch (
Entry.Kind) {
2630 return error(
"Malformed block");
2632 if (NumRecords != TypeList.size())
2633 return error(
"Malformed block");
2642 Type *ResultTy =
nullptr;
2643 SmallVector<unsigned> ContainedIDs;
2647 switch (MaybeRecord.
get()) {
2649 return error(
"Invalid value");
2654 return error(
"Invalid numentry record");
2655 TypeList.resize(Record[0]);
2658 ResultTy = Type::getVoidTy(
Context);
2661 ResultTy = Type::getHalfTy(
Context);
2664 ResultTy = Type::getBFloatTy(
Context);
2667 ResultTy = Type::getFloatTy(
Context);
2670 ResultTy = Type::getDoubleTy(
Context);
2673 ResultTy = Type::getX86_FP80Ty(
Context);
2676 ResultTy = Type::getFP128Ty(
Context);
2679 ResultTy = Type::getPPC_FP128Ty(
Context);
2682 ResultTy = Type::getLabelTy(
Context);
2685 ResultTy = Type::getMetadataTy(
Context);
2693 ResultTy = Type::getX86_AMXTy(
Context);
2696 ResultTy = Type::getTokenTy(
Context);
2700 return error(
"Invalid record");
2702 uint64_t NumBits =
Record[0];
2705 return error(
"Bitwidth for byte type out of range");
2711 return error(
"Invalid integer record");
2713 uint64_t NumBits =
Record[0];
2716 return error(
"Bitwidth for integer type out of range");
2723 return error(
"Invalid pointer record");
2727 ResultTy = getTypeByID(Record[0]);
2729 !PointerType::isValidElementType(ResultTy))
2730 return error(
"Invalid type");
2737 return error(
"Invalid opaque pointer record");
2746 return error(
"Invalid function record");
2748 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2749 if (
Type *
T = getTypeByID(Record[i]))
2755 ResultTy = getTypeByID(Record[2]);
2756 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2757 return error(
"Invalid type");
2760 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2766 return error(
"Invalid function record");
2768 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2769 if (
Type *
T = getTypeByID(Record[i])) {
2770 if (!FunctionType::isValidArgumentType(
T))
2771 return error(
"Invalid function argument type");
2778 ResultTy = getTypeByID(Record[1]);
2779 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2780 return error(
"Invalid type");
2783 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2788 return error(
"Invalid anon struct record");
2790 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2791 if (
Type *
T = getTypeByID(Record[i]))
2797 return error(
"Invalid type");
2804 return error(
"Invalid struct name record");
2809 return error(
"Invalid named struct record");
2811 if (NumRecords >= TypeList.size())
2812 return error(
"Invalid TYPE table");
2818 TypeList[NumRecords] =
nullptr;
2820 Res = createIdentifiedStructType(
Context, TypeName);
2824 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2825 if (
Type *
T = getTypeByID(Record[i]))
2831 return error(
"Invalid named struct record");
2840 return error(
"Invalid opaque type record");
2842 if (NumRecords >= TypeList.size())
2843 return error(
"Invalid TYPE table");
2849 TypeList[NumRecords] =
nullptr;
2851 Res = createIdentifiedStructType(
Context, TypeName);
2858 return error(
"Invalid target extension type record");
2860 if (NumRecords >= TypeList.size())
2861 return error(
"Invalid TYPE table");
2863 if (Record[0] >=
Record.size())
2864 return error(
"Too many type parameters");
2866 unsigned NumTys =
Record[0];
2868 SmallVector<unsigned, 8> IntParams;
2869 for (
unsigned i = 0; i < NumTys; i++) {
2870 if (
Type *
T = getTypeByID(Record[i + 1]))
2873 return error(
"Invalid type");
2876 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2877 if (Record[i] > UINT_MAX)
2878 return error(
"Integer parameter too large");
2883 if (
auto E = TTy.takeError())
2891 return error(
"Invalid array type record");
2892 ResultTy = getTypeByID(Record[1]);
2893 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2894 return error(
"Invalid type");
2896 ResultTy = ArrayType::get(ResultTy, Record[0]);
2901 return error(
"Invalid vector type record");
2903 return error(
"Invalid vector length");
2904 ResultTy = getTypeByID(Record[1]);
2905 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2906 return error(
"Invalid type");
2909 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2913 if (NumRecords >= TypeList.size())
2914 return error(
"Invalid TYPE table");
2915 if (TypeList[NumRecords])
2917 "Invalid TYPE table: Only named structs can be forward referenced");
2918 assert(ResultTy &&
"Didn't read a type?");
2919 TypeList[NumRecords] = ResultTy;
2920 if (!ContainedIDs.
empty())
2921 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2926Error BitcodeReader::parseOperandBundleTags() {
2930 if (!BundleTags.empty())
2931 return error(
"Invalid multiple blocks");
2933 SmallVector<uint64_t, 64>
Record;
2939 BitstreamEntry
Entry = MaybeEntry.
get();
2941 switch (
Entry.Kind) {
2944 return error(
"Malformed block");
2958 return error(
"Invalid operand bundle record");
2961 BundleTags.emplace_back();
2963 return error(
"Invalid operand bundle record");
2968Error BitcodeReader::parseSyncScopeNames() {
2973 return error(
"Invalid multiple synchronization scope names blocks");
2975 SmallVector<uint64_t, 64>
Record;
2980 BitstreamEntry
Entry = MaybeEntry.
get();
2982 switch (
Entry.Kind) {
2985 return error(
"Malformed block");
2988 return error(
"Invalid empty synchronization scope names block");
3002 return error(
"Invalid sync scope record");
3004 SmallString<16> SSN;
3006 return error(
"Invalid sync scope record");
3014Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
3015 unsigned NameIndex, Triple &TT) {
3018 return error(
"Invalid record");
3019 unsigned ValueID =
Record[0];
3020 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3021 return error(
"Invalid record");
3022 Value *
V = ValueList[ValueID];
3025 if (NameStr.contains(0))
3026 return error(
"Invalid value name");
3027 V->setName(NameStr);
3029 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
3042 return std::move(JumpFailed);
3048 return error(
"Expected value symbol table subblock");
3052void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
3054 ArrayRef<uint64_t> Record) {
3058 uint64_t FuncWordOffset =
Record[1] - 1;
3059 uint64_t FuncBitOffset = FuncWordOffset * 32;
3060 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3064 if (FuncBitOffset > LastFunctionBlockBit)
3065 LastFunctionBlockBit = FuncBitOffset;
3069Error BitcodeReader::parseGlobalValueSymbolTable() {
3070 unsigned FuncBitcodeOffsetDelta =
3076 SmallVector<uint64_t, 64>
Record;
3081 BitstreamEntry
Entry = MaybeEntry.
get();
3083 switch (
Entry.Kind) {
3086 return error(
"Malformed block");
3097 switch (MaybeRecord.
get()) {
3099 unsigned ValueID =
Record[0];
3100 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3101 return error(
"Invalid value reference in symbol table");
3102 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3112Error BitcodeReader::parseValueSymbolTable(uint64_t
Offset) {
3113 uint64_t CurrentBit;
3119 if (!MaybeCurrentBit)
3121 CurrentBit = MaybeCurrentBit.
get();
3124 if (
Error Err = parseGlobalValueSymbolTable())
3145 unsigned FuncBitcodeOffsetDelta =
3151 SmallVector<uint64_t, 64>
Record;
3162 BitstreamEntry
Entry = MaybeEntry.
get();
3164 switch (
Entry.Kind) {
3167 return error(
"Malformed block");
3183 switch (MaybeRecord.
get()) {
3187 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3195 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3203 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3208 return error(
"Invalid bbentry record");
3211 return error(
"Invalid bbentry record");
3223uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3233Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3234 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3235 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3236 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3238 GlobalInitWorklist.swap(GlobalInits);
3239 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3240 FunctionOperandWorklist.swap(FunctionOperands);
3242 while (!GlobalInitWorklist.empty()) {
3243 unsigned ValID = GlobalInitWorklist.back().second;
3244 if (ValID >= ValueList.
size()) {
3246 GlobalInits.push_back(GlobalInitWorklist.back());
3248 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3251 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3253 GlobalInitWorklist.pop_back();
3256 while (!IndirectSymbolInitWorklist.empty()) {
3257 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3258 if (ValID >= ValueList.
size()) {
3259 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3261 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3265 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3268 return error(
"Alias and aliasee types don't match");
3273 return error(
"Expected an alias or an ifunc");
3276 IndirectSymbolInitWorklist.pop_back();
3279 while (!FunctionOperandWorklist.empty()) {
3280 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3281 if (
Info.PersonalityFn) {
3282 unsigned ValID =
Info.PersonalityFn - 1;
3283 if (ValID < ValueList.
size()) {
3284 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3287 Info.F->setPersonalityFn(MaybeC.
get());
3288 Info.PersonalityFn = 0;
3292 unsigned ValID =
Info.Prefix - 1;
3293 if (ValID < ValueList.
size()) {
3294 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3297 Info.F->setPrefixData(MaybeC.
get());
3301 if (
Info.Prologue) {
3302 unsigned ValID =
Info.Prologue - 1;
3303 if (ValID < ValueList.
size()) {
3304 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3307 Info.F->setPrologueData(MaybeC.
get());
3311 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3312 FunctionOperands.push_back(Info);
3313 FunctionOperandWorklist.pop_back();
3322 BitcodeReader::decodeSignRotatedValue);
3324 return APInt(TypeBits, Words);
3327Error BitcodeReader::parseConstants() {
3335 unsigned Int32TyID = getVirtualTypeID(CurTy);
3336 unsigned CurTyID = Int32TyID;
3337 Type *CurElemTy =
nullptr;
3338 unsigned NextCstNo = ValueList.
size();
3346 switch (Entry.Kind) {
3349 return error(
"Malformed block");
3351 if (NextCstNo != ValueList.
size())
3352 return error(
"Invalid constant reference");
3363 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
3366 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3376 return error(
"Invalid settype record");
3377 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3378 return error(
"Invalid settype record");
3379 if (TypeList[Record[0]] == VoidType)
3380 return error(
"Invalid constant type");
3382 CurTy = TypeList[CurTyID];
3383 CurElemTy = getPtrElementTypeByID(CurTyID);
3387 return error(
"Invalid type for a constant null value");
3390 return error(
"Invalid type for a constant null value");
3395 return error(
"Invalid integer const record");
3400 return error(
"Invalid wide integer const record");
3403 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3404 V = ConstantInt::get(CurTy, VInt);
3409 return error(
"Invalid byte const record");
3410 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]),
3415 return error(
"Invalid wide byte const record");
3418 APInt VByte =
readWideAPInt(Record, ScalarTy->getBitWidth());
3419 V = ConstantByte::get(CurTy, VByte);
3424 return error(
"Invalid float const record");
3427 if (ScalarTy->isHalfTy())
3428 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3429 APInt(16, (uint16_t)Record[0])));
3430 else if (ScalarTy->isBFloatTy())
3431 V = ConstantFP::get(
3432 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3433 else if (ScalarTy->isFloatTy())
3434 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3435 APInt(32, (uint32_t)Record[0])));
3436 else if (ScalarTy->isDoubleTy())
3437 V = ConstantFP::get(
3438 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3439 else if (ScalarTy->isX86_FP80Ty()) {
3441 uint64_t Rearrange[2];
3442 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3443 Rearrange[1] =
Record[0] >> 48;
3444 V = ConstantFP::get(
3445 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3446 }
else if (ScalarTy->isFP128Ty())
3447 V = ConstantFP::get(CurTy,
3448 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3449 else if (ScalarTy->isPPC_FP128Ty())
3450 V = ConstantFP::get(
3451 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3459 return error(
"Invalid aggregate record");
3461 SmallVector<unsigned, 16> Elts;
3465 V = BitcodeConstant::create(
3466 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3468 V = BitcodeConstant::create(
Alloc, CurTy,
3469 BitcodeConstant::ConstantArrayOpcode, Elts);
3471 V = BitcodeConstant::create(
3472 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3481 return error(
"Invalid string record");
3491 return error(
"Invalid data record");
3495 return error(
"Invalid type for value");
3498 SmallString<128> RawData;
3500 for (uint64_t Val : Record) {
3501 const char *Src =
reinterpret_cast<const char *
>(&Val);
3503 Src +=
sizeof(uint64_t) - EltBytes;
3504 RawData.
append(Src, Src + EltBytes);
3509 : ConstantDataArray::getRaw(RawData.str(),
Record.
size(), EltTy);
3514 return error(
"Invalid unary op constexpr record");
3519 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3525 return error(
"Invalid binary op constexpr record");
3531 if (
Record.size() >= 4) {
3532 if (
Opc == Instruction::Add ||
3533 Opc == Instruction::Sub ||
3534 Opc == Instruction::Mul ||
3535 Opc == Instruction::Shl) {
3540 }
else if (
Opc == Instruction::SDiv ||
3541 Opc == Instruction::UDiv ||
3542 Opc == Instruction::LShr ||
3543 Opc == Instruction::AShr) {
3548 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3549 {(unsigned)Record[1], (
unsigned)
Record[2]});
3555 return error(
"Invalid cast constexpr record");
3560 unsigned OpTyID =
Record[1];
3561 Type *OpTy = getTypeByID(OpTyID);
3563 return error(
"Invalid cast constexpr record");
3564 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3576 return error(
"Constant GEP record must have at least two elements");
3578 Type *PointeeType =
nullptr;
3582 PointeeType = getTypeByID(Record[OpNum++]);
3585 std::optional<ConstantRange>
InRange;
3589 unsigned InRangeIndex =
Op >> 1;
3595 Expected<ConstantRange> MaybeInRange =
3596 readBitWidthAndConstantRange(Record, OpNum);
3605 SmallVector<unsigned, 16> Elts;
3606 unsigned BaseTypeID =
Record[OpNum];
3607 while (OpNum !=
Record.size()) {
3608 unsigned ElTyID =
Record[OpNum++];
3609 Type *ElTy = getTypeByID(ElTyID);
3611 return error(
"Invalid getelementptr constexpr record");
3615 if (Elts.
size() < 1)
3616 return error(
"Invalid gep with no operands");
3620 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3621 BaseType = getTypeByID(BaseTypeID);
3626 return error(
"GEP base operand must be pointer or vector of pointer");
3629 PointeeType = getPtrElementTypeByID(BaseTypeID);
3631 return error(
"Missing element type for old-style constant GEP");
3634 V = BitcodeConstant::create(
3636 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3642 return error(
"Invalid select constexpr record");
3644 V = BitcodeConstant::create(
3645 Alloc, CurTy, Instruction::Select,
3646 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3652 return error(
"Invalid extractelement constexpr record");
3653 unsigned OpTyID =
Record[0];
3657 return error(
"Invalid extractelement constexpr record");
3659 if (
Record.size() == 4) {
3660 unsigned IdxTyID =
Record[2];
3661 Type *IdxTy = getTypeByID(IdxTyID);
3663 return error(
"Invalid extractelement constexpr record");
3669 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3670 {(unsigned)Record[1], IdxRecord});
3676 if (
Record.size() < 3 || !OpTy)
3677 return error(
"Invalid insertelement constexpr record");
3679 if (
Record.size() == 4) {
3680 unsigned IdxTyID =
Record[2];
3681 Type *IdxTy = getTypeByID(IdxTyID);
3683 return error(
"Invalid insertelement constexpr record");
3689 V = BitcodeConstant::create(
3690 Alloc, CurTy, Instruction::InsertElement,
3691 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3696 if (
Record.size() < 3 || !OpTy)
3697 return error(
"Invalid shufflevector constexpr record");
3698 V = BitcodeConstant::create(
3699 Alloc, CurTy, Instruction::ShuffleVector,
3700 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3707 if (
Record.size() < 4 || !RTy || !OpTy)
3708 return error(
"Invalid shufflevector constexpr record");
3709 V = BitcodeConstant::create(
3710 Alloc, CurTy, Instruction::ShuffleVector,
3711 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3716 return error(
"Invalid cmp constexpt record");
3717 unsigned OpTyID =
Record[0];
3718 Type *OpTy = getTypeByID(OpTyID);
3720 return error(
"Invalid cmp constexpr record");
3721 V = BitcodeConstant::create(
3724 : Instruction::ICmp),
3725 (uint8_t)Record[3]},
3726 {(unsigned)Record[1], (
unsigned)
Record[2]});
3733 return error(
"Invalid inlineasm record");
3734 std::string AsmStr, ConstrStr;
3735 bool HasSideEffects =
Record[0] & 1;
3736 bool IsAlignStack =
Record[0] >> 1;
3737 unsigned AsmStrSize =
Record[1];
3738 if (2+AsmStrSize >=
Record.size())
3739 return error(
"Invalid inlineasm record");
3740 unsigned ConstStrSize =
Record[2+AsmStrSize];
3741 if (3+AsmStrSize+ConstStrSize >
Record.size())
3742 return error(
"Invalid inlineasm record");
3744 for (
unsigned i = 0; i != AsmStrSize; ++i)
3745 AsmStr += (
char)
Record[2+i];
3746 for (
unsigned i = 0; i != ConstStrSize; ++i)
3747 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3750 return error(
"Missing element type for old-style inlineasm");
3752 HasSideEffects, IsAlignStack);
3759 return error(
"Invalid inlineasm record");
3760 std::string AsmStr, ConstrStr;
3761 bool HasSideEffects =
Record[0] & 1;
3762 bool IsAlignStack = (
Record[0] >> 1) & 1;
3763 unsigned AsmDialect =
Record[0] >> 2;
3764 unsigned AsmStrSize =
Record[1];
3765 if (2+AsmStrSize >=
Record.size())
3766 return error(
"Invalid inlineasm record");
3767 unsigned ConstStrSize =
Record[2+AsmStrSize];
3768 if (3+AsmStrSize+ConstStrSize >
Record.size())
3769 return error(
"Invalid inlineasm record");
3771 for (
unsigned i = 0; i != AsmStrSize; ++i)
3772 AsmStr += (
char)
Record[2+i];
3773 for (
unsigned i = 0; i != ConstStrSize; ++i)
3774 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3777 return error(
"Missing element type for old-style inlineasm");
3779 HasSideEffects, IsAlignStack,
3786 return error(
"Invalid inlineasm record");
3788 std::string AsmStr, ConstrStr;
3789 bool HasSideEffects =
Record[OpNum] & 1;
3790 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3791 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3792 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3794 unsigned AsmStrSize =
Record[OpNum];
3796 if (OpNum + AsmStrSize >=
Record.size())
3797 return error(
"Invalid inlineasm record");
3798 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3799 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3800 return error(
"Invalid inlineasm record");
3802 for (
unsigned i = 0; i != AsmStrSize; ++i)
3803 AsmStr += (
char)
Record[OpNum + i];
3805 for (
unsigned i = 0; i != ConstStrSize; ++i)
3806 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3809 return error(
"Missing element type for old-style inlineasm");
3811 HasSideEffects, IsAlignStack,
3818 return error(
"Invalid inlineasm record");
3823 return error(
"Invalid inlineasm record");
3824 std::string AsmStr, ConstrStr;
3825 bool HasSideEffects =
Record[OpNum] & 1;
3826 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3827 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3828 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3830 unsigned AsmStrSize =
Record[OpNum];
3832 if (OpNum + AsmStrSize >=
Record.size())
3833 return error(
"Invalid inlineasm record");
3834 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3835 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3836 return error(
"Invalid inlineasm record");
3838 for (
unsigned i = 0; i != AsmStrSize; ++i)
3839 AsmStr += (
char)
Record[OpNum + i];
3841 for (
unsigned i = 0; i != ConstStrSize; ++i)
3842 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3844 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3850 return error(
"Invalid blockaddress record");
3851 unsigned FnTyID =
Record[0];
3852 Type *FnTy = getTypeByID(FnTyID);
3854 return error(
"Invalid blockaddress record");
3855 V = BitcodeConstant::create(
3857 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3863 return error(
"Invalid dso_local record");
3864 unsigned GVTyID =
Record[0];
3865 Type *GVTy = getTypeByID(GVTyID);
3867 return error(
"Invalid dso_local record");
3868 V = BitcodeConstant::create(
3869 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3874 return error(
"Invalid no_cfi record");
3875 unsigned GVTyID =
Record[0];
3876 Type *GVTy = getTypeByID(GVTyID);
3878 return error(
"Invalid no_cfi record");
3879 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3885 return error(
"Invalid ptrauth record");
3887 V = BitcodeConstant::create(
Alloc, CurTy,
3888 BitcodeConstant::ConstantPtrAuthOpcode,
3889 {(unsigned)Record[0], (
unsigned)
Record[1],
3890 (unsigned)Record[2], (
unsigned)
Record[3]});
3895 return error(
"Invalid ptrauth record");
3897 V = BitcodeConstant::create(
3898 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3899 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3900 (
unsigned)
Record[3], (unsigned)Record[4]});
3905 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3912Error BitcodeReader::parseUseLists() {
3917 SmallVector<uint64_t, 64>
Record;
3923 BitstreamEntry
Entry = MaybeEntry.
get();
3925 switch (
Entry.Kind) {
3928 return error(
"Malformed block");
3942 switch (MaybeRecord.
get()) {
3950 if (RecordLength < 3)
3952 return error(
"Invalid uselist record");
3953 unsigned ID =
Record.pop_back_val();
3957 assert(
ID < FunctionBBs.size() &&
"Basic block not found");
3958 V = FunctionBBs[
ID];
3962 if (!
V->hasUseList())
3965 unsigned NumUses = 0;
3966 SmallDenseMap<const Use *, unsigned, 16> Order;
3967 for (
const Use &U :
V->materialized_uses()) {
3968 if (++NumUses >
Record.size())
3970 Order[&
U] =
Record[NumUses - 1];
3977 V->sortUseList([&](
const Use &L,
const Use &R) {
3988Error BitcodeReader::rememberAndSkipMetadata() {
3991 DeferredMetadataInfo.push_back(CurBit);
3999Error BitcodeReader::materializeMetadata() {
4000 for (uint64_t BitPos : DeferredMetadataInfo) {
4004 if (
Error Err = MDLoader->parseModuleMetadata())
4013 NamedMDNode *LinkerOpts =
4015 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
4022 DeferredMetadataInfo.clear();
4026void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
4030Error BitcodeReader::rememberAndSkipFunctionBody() {
4032 if (FunctionsWithBodies.empty())
4033 return error(
"Insufficient function protos");
4035 Function *Fn = FunctionsWithBodies.back();
4036 FunctionsWithBodies.pop_back();
4041 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4042 "Mismatch between VST and scanned function offsets");
4043 DeferredFunctionInfo[Fn] = CurBit;
4051Error BitcodeReader::globalCleanup() {
4053 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4055 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4056 return error(
"Malformed global initializer set");
4060 for (Function &
F : *TheModule) {
4061 MDLoader->upgradeDebugIntrinsics(
F);
4065 !SkipDebugIntrinsicUpgrade))
4066 UpgradedIntrinsics[&
F] = NewFn;
4072 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4073 for (GlobalVariable &GV : TheModule->globals())
4075 UpgradedVariables.emplace_back(&GV, Upgraded);
4076 for (
auto &Pair : UpgradedVariables) {
4077 Pair.first->eraseFromParent();
4078 TheModule->insertGlobalVariable(Pair.second);
4081 for (
size_t ValueID = 0; ValueID < GUIDList.size(); ValueID++) {
4082 const auto GUID = GUIDList[ValueID];
4086 const auto *
Value = ValueList[ValueID];
4087 TheModule->insertGUID(
Value, GUID);
4092 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4093 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4101Error BitcodeReader::rememberAndSkipFunctionBodies() {
4106 return error(
"Could not find function in stream");
4108 if (!SeenFirstFunctionBody)
4109 return error(
"Trying to materialize functions before seeing function blocks");
4113 assert(SeenValueSymbolTable);
4116 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4119 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4121 switch (
Entry.Kind) {
4123 return error(
"Expect SubBlock");
4127 return error(
"Expect function block");
4129 if (
Error Err = rememberAndSkipFunctionBody())
4138Error BitcodeReaderBase::readBlockInfo() {
4139 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4141 if (!MaybeNewBlockInfo)
4143 std::optional<BitstreamBlockInfo> NewBlockInfo =
4144 std::move(MaybeNewBlockInfo.
get());
4146 return error(
"Malformed block");
4147 BlockInfo = std::move(*NewBlockInfo);
4151Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4155 std::tie(Name, Record) = readNameFromStrtab(Record);
4158 return error(
"Invalid comdat record");
4160 std::string OldFormatName;
4163 return error(
"Invalid comdat record");
4164 unsigned ComdatNameSize =
Record[1];
4165 if (ComdatNameSize >
Record.size() - 2)
4166 return error(
"Comdat name size too large");
4167 OldFormatName.reserve(ComdatNameSize);
4168 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4169 OldFormatName += (
char)
Record[2 + i];
4170 Name = OldFormatName;
4172 Comdat *
C = TheModule->getOrInsertComdat(Name);
4173 C->setSelectionKind(SK);
4174 ComdatList.push_back(
C);
4188 Meta.NoAddress =
true;
4190 Meta.NoHWAddress =
true;
4194 Meta.IsDynInit =
true;
4198Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4206 std::tie(Name, Record) = readNameFromStrtab(Record);
4209 return error(
"Invalid global variable record");
4210 unsigned TyID =
Record[0];
4211 Type *Ty = getTypeByID(TyID);
4213 return error(
"Invalid global variable record");
4215 bool explicitType =
Record[1] & 2;
4221 return error(
"Invalid type for value");
4223 TyID = getContainedTypeID(TyID);
4224 Ty = getTypeByID(TyID);
4226 return error(
"Missing element type for old-style global");
4229 uint64_t RawLinkage =
Record[3];
4231 MaybeAlign Alignment;
4232 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4236 if (Record[5] - 1 >= SectionTable.size())
4237 return error(
"Invalid ID");
4246 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4254 bool ExternallyInitialized =
false;
4256 ExternallyInitialized =
Record[9];
4258 GlobalVariable *NewGV =
4268 if (
Record.size() > 10) {
4280 if (
unsigned InitID = Record[2])
4281 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4283 if (
Record.size() > 11) {
4284 if (
unsigned ComdatID = Record[11]) {
4285 if (ComdatID > ComdatList.size())
4286 return error(
"Invalid global variable comdat ID");
4287 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4290 ImplicitComdatObjects.
insert(NewGV);
4293 if (
Record.size() > 12) {
4298 if (
Record.size() > 13) {
4307 if (
Record.size() > 16 && Record[16]) {
4308 llvm::GlobalValue::SanitizerMetadata
Meta =
4313 if (
Record.size() > 17 && Record[17]) {
4317 return error(
"Invalid global variable code model");
4323void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4324 if (ValueTypeCallback) {
4325 (*ValueTypeCallback)(
4326 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4327 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4331Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4337 std::tie(Name, Record) = readNameFromStrtab(Record);
4340 return error(
"Invalid function record");
4341 unsigned FTyID =
Record[0];
4342 Type *FTy = getTypeByID(FTyID);
4344 return error(
"Invalid function record");
4346 FTyID = getContainedTypeID(FTyID, 0);
4347 FTy = getTypeByID(FTyID);
4349 return error(
"Missing element type for old-style function");
4353 return error(
"Invalid type for value");
4354 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4355 if (CC & ~CallingConv::MaxID)
4356 return error(
"Invalid calling convention ID");
4358 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4364 AddrSpace, Name, TheModule);
4367 "Incorrect fully specified type provided for function");
4368 FunctionTypeIDs[
Func] = FTyID;
4370 Func->setCallingConv(CC);
4371 bool isProto =
Record[2];
4372 uint64_t RawLinkage =
Record[3];
4375 callValueTypeCallback(Func, FTyID);
4380 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4381 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4382 Attribute::InAlloca}) {
4383 if (!
Func->hasParamAttribute(i, Kind))
4386 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4389 Func->removeParamAttr(i, Kind);
4391 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4392 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4394 return error(
"Missing param element type for attribute upgrade");
4398 case Attribute::ByVal:
4399 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4401 case Attribute::StructRet:
4402 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4404 case Attribute::InAlloca:
4405 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4411 Func->addParamAttr(i, NewAttr);
4415 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4416 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4417 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4418 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4420 return error(
"Missing param element type for x86_intrcc upgrade");
4422 Func->addParamAttr(0, NewAttr);
4425 MaybeAlign Alignment;
4426 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4429 Func->setAlignment(*Alignment);
4431 if (Record[6] - 1 >= SectionTable.size())
4432 return error(
"Invalid ID");
4433 Func->setSection(SectionTable[Record[6] - 1]);
4437 if (!
Func->hasLocalLinkage())
4439 if (
Record.size() > 8 && Record[8]) {
4440 if (Record[8] - 1 >= GCTable.size())
4441 return error(
"Invalid ID");
4442 Func->setGC(GCTable[Record[8] - 1]);
4447 Func->setUnnamedAddr(UnnamedAddr);
4449 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4451 OperandInfo.Prologue =
Record[10];
4453 if (
Record.size() > 11) {
4455 if (!
Func->hasLocalLinkage()) {
4462 if (
Record.size() > 12) {
4463 if (
unsigned ComdatID = Record[12]) {
4464 if (ComdatID > ComdatList.size())
4465 return error(
"Invalid function comdat ID");
4466 Func->setComdat(ComdatList[ComdatID - 1]);
4469 ImplicitComdatObjects.
insert(Func);
4473 OperandInfo.Prefix =
Record[13];
4476 OperandInfo.PersonalityFn =
Record[14];
4478 if (
Record.size() > 15) {
4488 Record[17] + Record[18] <= Strtab.
size()) {
4489 Func->setPartition(StringRef(Strtab.
data() + Record[17], Record[18]));
4492 if (
Record.size() > 19) {
4493 MaybeAlign PrefAlignment;
4494 if (
Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4496 Func->setPreferredAlignment(PrefAlignment);
4499 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4501 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4502 FunctionOperands.push_back(OperandInfo);
4507 Func->setIsMaterializable(
true);
4508 FunctionsWithBodies.push_back(Func);
4509 DeferredFunctionInfo[
Func] = 0;
4514Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4515 unsigned BitCode, ArrayRef<uint64_t> Record) {
4525 std::tie(Name, Record) = readNameFromStrtab(Record);
4528 if (
Record.size() < (3 + (
unsigned)NewRecord))
4529 return error(
"Invalid global indirect symbol record");
4534 return error(
"Invalid global indirect symbol record");
4540 return error(
"Invalid type for value");
4541 AddrSpace = PTy->getAddressSpace();
4543 Ty = getTypeByID(
TypeID);
4545 return error(
"Missing element type for old-style indirect symbol");
4547 AddrSpace =
Record[OpNum++];
4550 auto Val =
Record[OpNum++];
4559 nullptr, TheModule);
4563 if (OpNum !=
Record.size()) {
4564 auto VisInd = OpNum++;
4570 if (OpNum !=
Record.size()) {
4571 auto S =
Record[OpNum++];
4578 if (OpNum !=
Record.size())
4580 if (OpNum !=
Record.size())
4583 if (OpNum !=
Record.size())
4588 if (OpNum + 1 <
Record.size()) {
4590 if (Record[OpNum] + Record[OpNum + 1] > Strtab.
size())
4591 return error(
"Malformed partition, too large.");
4593 StringRef(Strtab.
data() + Record[OpNum], Record[OpNum + 1]));
4597 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4601Error BitcodeReader::parseModule(uint64_t ResumeBit,
4602 bool ShouldLazyLoadMetadata,
4603 ParserCallbacks Callbacks) {
4604 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4611 SmallVector<uint64_t, 64>
Record;
4615 bool ResolvedDataLayout =
false;
4620 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4623 Module::GlobalAsmProperties Props;
4625 auto ResolveDataLayout = [&]() ->
Error {
4626 if (ResolvedDataLayout)
4630 ResolvedDataLayout =
true;
4634 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4638 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4639 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4640 TentativeDataLayoutStr = *LayoutOverride;
4648 TheModule->setDataLayout(MaybeDL.
get());
4654 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4657 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4659 switch (
Entry.Kind) {
4661 return error(
"Malformed block");
4663 if (
Error Err = ResolveDataLayout())
4665 return globalCleanup();
4674 if (
Error Err = readBlockInfo())
4678 if (
Error Err = parseAttributeBlock())
4682 if (
Error Err = parseAttributeGroupBlock())
4686 if (
Error Err = parseTypeTable())
4690 if (!SeenValueSymbolTable) {
4696 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4697 if (
Error Err = parseValueSymbolTable())
4699 SeenValueSymbolTable =
true;
4709 if (
Error Err = parseConstants())
4711 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4715 if (ShouldLazyLoadMetadata) {
4716 if (
Error Err = rememberAndSkipMetadata())
4720 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4721 if (
Error Err = MDLoader->parseModuleMetadata())
4725 if (
Error Err = MDLoader->parseMetadataKinds())
4729 if (
Error Err = ResolveDataLayout())
4734 if (!SeenFirstFunctionBody) {
4735 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4736 if (
Error Err = globalCleanup())
4738 SeenFirstFunctionBody =
true;
4741 if (VSTOffset > 0) {
4745 if (!SeenValueSymbolTable) {
4746 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4748 SeenValueSymbolTable =
true;
4770 if (
Error Err = rememberAndSkipFunctionBody())
4777 if (SeenValueSymbolTable) {
4781 return globalCleanup();
4785 if (
Error Err = parseUseLists())
4789 if (
Error Err = parseOperandBundleTags())
4793 if (
Error Err = parseSyncScopeNames())
4805 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
4808 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4811 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4814 UseRelativeIDs = *VersionOrErr >= 1;
4818 if (ResolvedDataLayout)
4819 return error(
"target triple too late in module");
4822 return error(
"Invalid triple record");
4823 TheModule->setTargetTriple(Triple(std::move(S)));
4827 if (ResolvedDataLayout)
4828 return error(
"datalayout too late in module");
4830 return error(
"Invalid data layout record");
4836 return error(
"Invalid module asm record");
4837 size_t SepPos = Str.find(
'\0');
4838 if (SepPos == std::string::npos)
4839 return error(
"Invalid module asm record");
4840 if (!Props.
set(StringRef(Str.data(), SepPos), Str.substr(SepPos + 1)))
4841 return error(
"Unknown module asm property");
4847 return error(
"Invalid asm record");
4848 TheModule->appendModuleInlineAsm(Module::GlobalAsmFragment(S, Props));
4856 return error(
"Invalid deplib record");
4863 return error(
"Invalid section name record");
4864 SectionTable.push_back(S);
4870 return error(
"Invalid gcname record");
4871 GCTable.push_back(S);
4875 if (
Error Err = parseComdatRecord(Record))
4884 if (
Error Err = parseGlobalVarRecord(Record))
4888 if (
Error Err = ResolveDataLayout())
4890 if (
Error Err = parseFunctionRecord(Record))
4896 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4902 return error(
"Invalid vstoffset record");
4906 VSTOffset =
Record[0] - 1;
4911 GUIDList.reserve(GUIDList.size() +
Record.size() / 2);
4912 for (
size_t i = 0; i <
Record.size(); i += 2)
4913 GUIDList.push_back(Record[i] << 32 | Record[i + 1]);
4919 return error(
"Invalid source filename record");
4920 TheModule->setSourceFileName(
ValueName);
4926 this->ValueTypeCallback = std::nullopt;
4930Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4932 ParserCallbacks Callbacks) {
4934 MetadataLoaderCallbacks MDCallbacks;
4935 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(
ID); };
4937 return getContainedTypeID(
I, J);
4940 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4942 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4945Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4947 return error(
"Load/Store operand is not a pointer type");
4948 if (!PointerType::isLoadableOrStorableType(ValType))
4949 return error(
"Cannot load/store from pointer");
4953Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4954 ArrayRef<unsigned> ArgTyIDs) {
4956 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4957 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4958 Attribute::InAlloca}) {
4959 if (!
Attrs.hasParamAttr(i, Kind) ||
4960 Attrs.getParamAttr(i, Kind).getValueAsType())
4963 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4965 return error(
"Missing element type for typed attribute upgrade");
4969 case Attribute::ByVal:
4970 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4972 case Attribute::StructRet:
4973 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4975 case Attribute::InAlloca:
4976 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4989 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
4993 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
4994 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4996 return error(
"Missing element type for inline asm upgrade");
4999 Attribute::get(
Context, Attribute::ElementType, ElemTy));
5007 case Intrinsic::preserve_array_access_index:
5008 case Intrinsic::preserve_struct_access_index:
5009 case Intrinsic::aarch64_ldaxr:
5010 case Intrinsic::aarch64_ldxr:
5011 case Intrinsic::aarch64_stlxr:
5012 case Intrinsic::aarch64_stxr:
5013 case Intrinsic::arm_ldaex:
5014 case Intrinsic::arm_ldrex:
5015 case Intrinsic::arm_stlex:
5016 case Intrinsic::arm_strex: {
5019 case Intrinsic::aarch64_stlxr:
5020 case Intrinsic::aarch64_stxr:
5021 case Intrinsic::arm_stlex:
5022 case Intrinsic::arm_strex:
5029 if (!
Attrs.getParamElementType(ArgNo)) {
5030 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5032 return error(
"Missing element type for elementtype upgrade");
5047Error BitcodeReader::parseFunctionBody(Function *
F) {
5052 if (MDLoader->hasFwdRefs())
5053 return error(
"Invalid function metadata: incoming forward references");
5055 InstructionList.
clear();
5056 unsigned ModuleValueListSize = ValueList.
size();
5057 unsigned ModuleMDLoaderSize = MDLoader->size();
5061 unsigned FTyID = FunctionTypeIDs[
F];
5062 for (Argument &
I :
F->args()) {
5063 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
5064 assert(
I.getType() == getTypeByID(ArgTyID) &&
5065 "Incorrect fully specified type for Function Argument");
5069 unsigned NextValueNo = ValueList.
size();
5071 unsigned CurBBNo = 0;
5076 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
5080 auto getLastInstruction = [&]() -> Instruction * {
5081 if (CurBB && !CurBB->
empty())
5082 return &CurBB->
back();
5083 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5084 !FunctionBBs[CurBBNo - 1]->
empty())
5085 return &FunctionBBs[CurBBNo - 1]->back();
5089 std::vector<OperandBundleDef> OperandBundles;
5092 SmallVector<uint64_t, 64>
Record;
5095 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
5098 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
5100 switch (
Entry.Kind) {
5102 return error(
"Malformed block");
5104 goto OutOfRecordLoop;
5113 if (
Error Err = parseConstants())
5115 NextValueNo = ValueList.
size();
5118 if (
Error Err = parseValueSymbolTable())
5122 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5126 assert(DeferredMetadataInfo.empty() &&
5127 "Must read all module-level metadata before function-level");
5128 if (
Error Err = MDLoader->parseFunctionMetadata())
5132 if (
Error Err = parseUseLists())
5146 unsigned ResTypeID = InvalidTypeID;
5147 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
5150 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5152 return error(
"Invalid value");
5154 if (
Record.empty() || Record[0] == 0)
5155 return error(
"Invalid declareblocks record");
5157 FunctionBBs.resize(Record[0]);
5160 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5161 if (BBFRI == BasicBlockFwdRefs.
end()) {
5162 for (BasicBlock *&BB : FunctionBBs)
5165 auto &BBRefs = BBFRI->second;
5167 if (BBRefs.size() > FunctionBBs.size())
5168 return error(
"Invalid ID");
5169 assert(!BBRefs.empty() &&
"Unexpected empty array");
5170 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5171 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5173 if (
I < RE && BBRefs[
I]) {
5174 BBRefs[
I]->insertInto(
F);
5175 FunctionBBs[
I] = BBRefs[
I];
5181 BasicBlockFwdRefs.
erase(BBFRI);
5184 CurBB = FunctionBBs[0];
5191 return error(
"Invalid blockaddr users record");
5205 for (uint64_t ValID : Record)
5207 BackwardRefFunctions.push_back(
F);
5209 return error(
"Invalid blockaddr users record");
5216 I = getLastInstruction();
5219 return error(
"Invalid debug_loc_again record");
5220 I->setDebugLoc(LastLoc);
5225 I = getLastInstruction();
5227 return error(
"Invalid debug loc record");
5232 uint64_t AtomGroup =
Record.size() == 7 ?
Record[5] : 0;
5235 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5238 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5240 return error(
"Invalid debug loc record");
5244 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5246 return error(
"Invalid debug loc record");
5249 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5250 isImplicitCode, AtomGroup, AtomRank);
5251 I->setDebugLoc(LastLoc);
5259 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5261 return error(
"Invalid unary operator record");
5265 return error(
"Invalid unary operator record");
5269 if (OpNum <
Record.size()) {
5273 I->setFastMathFlags(FMF);
5282 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5286 return error(
"Invalid binary operator record");
5290 return error(
"Invalid binary operator record");
5294 if (OpNum <
Record.size()) {
5295 if (
Opc == Instruction::Add ||
5296 Opc == Instruction::Sub ||
5297 Opc == Instruction::Mul ||
5298 Opc == Instruction::Shl) {
5303 }
else if (
Opc == Instruction::SDiv ||
5304 Opc == Instruction::UDiv ||
5305 Opc == Instruction::LShr ||
5306 Opc == Instruction::AShr) {
5309 }
else if (
Opc == Instruction::Or) {
5315 I->setFastMathFlags(FMF);
5324 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5325 OpNum + 1 >
Record.size())
5326 return error(
"Invalid cast record");
5328 ResTypeID =
Record[OpNum++];
5329 Type *ResTy = getTypeByID(ResTypeID);
5332 if (
Opc == -1 || !ResTy)
5333 return error(
"Invalid cast record");
5338 assert(CurBB &&
"No current BB?");
5344 return error(
"Invalid cast");
5348 if (OpNum <
Record.size()) {
5349 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5352 }
else if (
Opc == Instruction::Trunc) {
5364 I->setFastMathFlags(FMF);
5383 Ty = getTypeByID(TyID);
5387 TyID = InvalidTypeID;
5392 unsigned BasePtrTypeID;
5393 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5395 return error(
"Invalid gep record");
5398 TyID = getContainedTypeID(BasePtrTypeID);
5399 if (
BasePtr->getType()->isVectorTy())
5400 TyID = getContainedTypeID(TyID);
5401 Ty = getTypeByID(TyID);
5404 SmallVector<Value*, 16> GEPIdx;
5405 while (OpNum !=
Record.size()) {
5408 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5409 return error(
"Invalid gep record");
5420 unsigned SubType = 0;
5421 if (GTI.isStruct()) {
5423 Idx->getType()->isVectorTy()
5425 :
cast<ConstantInt>(Idx);
5428 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5435 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5436 if (
I->getType()->isVectorTy())
5437 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5440 GEP->setNoWrapFlags(NW);
5449 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5450 return error(
"Invalid extractvalue record");
5453 unsigned RecSize =
Record.size();
5454 if (OpNum == RecSize)
5455 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5457 SmallVector<unsigned, 4> EXTRACTVALIdx;
5458 ResTypeID = AggTypeID;
5459 for (; OpNum != RecSize; ++OpNum) {
5464 if (!IsStruct && !IsArray)
5465 return error(
"EXTRACTVAL: Invalid type");
5466 if ((
unsigned)Index != Index)
5467 return error(
"Invalid value");
5469 return error(
"EXTRACTVAL: Invalid struct index");
5471 return error(
"EXTRACTVAL: Invalid array index");
5472 EXTRACTVALIdx.
push_back((
unsigned)Index);
5476 ResTypeID = getContainedTypeID(ResTypeID, Index);
5479 ResTypeID = getContainedTypeID(ResTypeID);
5493 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5494 return error(
"Invalid insertvalue record");
5497 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5498 return error(
"Invalid insertvalue record");
5500 unsigned RecSize =
Record.size();
5501 if (OpNum == RecSize)
5502 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5504 SmallVector<unsigned, 4> INSERTVALIdx;
5506 for (; OpNum != RecSize; ++OpNum) {
5511 if (!IsStruct && !IsArray)
5512 return error(
"INSERTVAL: Invalid type");
5513 if ((
unsigned)Index != Index)
5514 return error(
"Invalid value");
5516 return error(
"INSERTVAL: Invalid struct index");
5518 return error(
"INSERTVAL: Invalid array index");
5520 INSERTVALIdx.
push_back((
unsigned)Index);
5528 return error(
"Inserted value type doesn't match aggregate type");
5531 ResTypeID = AggTypeID;
5543 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5545 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5547 popValue(Record, OpNum, NextValueNo, CondType,
5548 getVirtualTypeID(CondType),
Cond, CurBB))
5549 return error(
"Invalid select record");
5562 unsigned ValTypeID, CondTypeID;
5563 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5565 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5567 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5568 return error(
"Invalid vector select record");
5571 if (VectorType* vector_type =
5574 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5575 return error(
"Invalid type for value");
5579 return error(
"Invalid type for value");
5583 ResTypeID = ValTypeID;
5588 I->setFastMathFlags(FMF);
5596 unsigned VecTypeID, IdxTypeID;
5597 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5598 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5599 return error(
"Invalid extractelement record");
5601 return error(
"Invalid type for value");
5603 ResTypeID = getContainedTypeID(VecTypeID);
5610 Value *Vec, *Elt, *Idx;
5611 unsigned VecTypeID, IdxTypeID;
5612 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5613 return error(
"Invalid insertelement record");
5615 return error(
"Invalid type for value");
5616 if (popValue(Record, OpNum, NextValueNo,
5618 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5619 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5620 return error(
"Invalid insert element record");
5622 ResTypeID = VecTypeID;
5630 unsigned Vec1TypeID;
5631 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5633 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5635 return error(
"Invalid shufflevector record");
5637 unsigned MaskTypeID;
5638 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5639 return error(
"Invalid shufflevector record");
5641 return error(
"Invalid type for value");
5643 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5645 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5660 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5661 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5663 return error(
"Invalid comparison record");
5665 if (OpNum >=
Record.size())
5667 "Invalid record: operand number exceeded available operands");
5672 if (IsFP &&
Record.size() > OpNum+1)
5677 return error(
"Invalid fcmp predicate");
5678 I =
new FCmpInst(PredVal,
LHS,
RHS);
5681 return error(
"Invalid icmp predicate");
5682 I =
new ICmpInst(PredVal,
LHS,
RHS);
5683 if (
Record.size() > OpNum + 1 &&
5688 if (OpNum + 1 !=
Record.size())
5689 return error(
"Invalid comparison record");
5691 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5693 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5696 I->setFastMathFlags(FMF);
5713 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5714 return error(
"Invalid ret record");
5715 if (OpNum !=
Record.size())
5716 return error(
"Invalid ret record");
5724 return error(
"Invalid br record");
5725 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5727 return error(
"Invalid br record");
5729 if (
Record.size() == 1) {
5734 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5737 getVirtualTypeID(CondType), CurBB);
5738 if (!FalseDest || !
Cond)
5739 return error(
"Invalid br record");
5747 return error(
"Invalid cleanupret record");
5750 Value *CleanupPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5751 getVirtualTypeID(TokenTy), CurBB);
5753 return error(
"Invalid cleanupret record");
5755 if (
Record.size() == 2) {
5756 UnwindDest = getBasicBlock(Record[Idx++]);
5758 return error(
"Invalid cleanupret record");
5767 return error(
"Invalid catchret record");
5770 Value *CatchPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5771 getVirtualTypeID(TokenTy), CurBB);
5773 return error(
"Invalid catchret record");
5774 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5776 return error(
"Invalid catchret record");
5785 return error(
"Invalid catchswitch record");
5790 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5791 getVirtualTypeID(TokenTy), CurBB);
5793 return error(
"Invalid catchswitch record");
5795 unsigned NumHandlers =
Record[Idx++];
5798 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5799 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5801 return error(
"Invalid catchswitch record");
5806 if (Idx + 1 ==
Record.size()) {
5807 UnwindDest = getBasicBlock(Record[Idx++]);
5809 return error(
"Invalid catchswitch record");
5812 if (
Record.size() != Idx)
5813 return error(
"Invalid catchswitch record");
5817 for (BasicBlock *Handler : Handlers)
5818 CatchSwitch->addHandler(Handler);
5820 ResTypeID = getVirtualTypeID(
I->getType());
5828 return error(
"Invalid catchpad/cleanuppad record");
5833 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5834 getVirtualTypeID(TokenTy), CurBB);
5836 return error(
"Invalid catchpad/cleanuppad record");
5838 unsigned NumArgOperands =
Record[Idx++];
5840 SmallVector<Value *, 2>
Args;
5841 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5844 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5845 return error(
"Invalid catchpad/cleanuppad record");
5846 Args.push_back(Val);
5849 if (
Record.size() != Idx)
5850 return error(
"Invalid catchpad/cleanuppad record");
5856 ResTypeID = getVirtualTypeID(
I->getType());
5862 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5868 unsigned OpTyID =
Record[1];
5869 Type *OpTy = getTypeByID(OpTyID);
5875 return error(
"Invalid switch record");
5877 unsigned NumCases =
Record[4];
5882 unsigned CurIdx = 5;
5883 for (
unsigned i = 0; i != NumCases; ++i) {
5885 unsigned NumItems =
Record[CurIdx++];
5886 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5887 bool isSingleNumber =
Record[CurIdx++];
5890 unsigned ActiveWords = 1;
5891 if (ValueBitWidth > 64)
5892 ActiveWords =
Record[CurIdx++];
5895 CurIdx += ActiveWords;
5897 if (!isSingleNumber) {
5899 if (ValueBitWidth > 64)
5900 ActiveWords =
Record[CurIdx++];
5903 CurIdx += ActiveWords;
5914 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5915 for (ConstantInt *Cst : CaseVals)
5916 SI->addCase(Cst, DestBB);
5925 return error(
"Invalid switch record");
5926 unsigned OpTyID =
Record[0];
5927 Type *OpTy = getTypeByID(OpTyID);
5931 return error(
"Invalid switch record");
5932 unsigned NumCases = (
Record.size()-3)/2;
5935 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5937 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
5938 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5939 if (!CaseVal || !DestBB) {
5941 return error(
"Invalid switch record");
5943 SI->addCase(CaseVal, DestBB);
5950 return error(
"Invalid indirectbr record");
5951 unsigned OpTyID =
Record[0];
5952 Type *OpTy = getTypeByID(OpTyID);
5955 return error(
"Invalid indirectbr record");
5956 unsigned NumDests =
Record.size()-2;
5959 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5960 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5964 return error(
"Invalid indirectbr record");
5974 return error(
"Invalid invoke record");
5977 unsigned CCInfo =
Record[OpNum++];
5978 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5979 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5981 unsigned FTyID = InvalidTypeID;
5982 FunctionType *FTy =
nullptr;
5983 if ((CCInfo >> 13) & 1) {
5987 return error(
"Explicit invoke type is not a function type");
5991 unsigned CalleeTypeID;
5992 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5994 return error(
"Invalid invoke record");
5998 return error(
"Callee is not a pointer");
6000 FTyID = getContainedTypeID(CalleeTypeID);
6003 return error(
"Callee is not of pointer to function type");
6005 if (
Record.size() < FTy->getNumParams() + OpNum)
6006 return error(
"Insufficient operands to call");
6008 SmallVector<Value*, 16>
Ops;
6009 SmallVector<unsigned, 16> ArgTyIDs;
6010 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6011 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6012 Ops.push_back(
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6016 return error(
"Invalid invoke record");
6019 if (!FTy->isVarArg()) {
6020 if (
Record.size() != OpNum)
6021 return error(
"Invalid invoke record");
6024 while (OpNum !=
Record.size()) {
6027 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6028 return error(
"Invalid invoke record");
6035 if (!OperandBundles.empty())
6040 ResTypeID = getContainedTypeID(FTyID);
6041 OperandBundles.clear();
6044 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
6055 Value *Val =
nullptr;
6057 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
6058 return error(
"Invalid resume record");
6067 unsigned CCInfo =
Record[OpNum++];
6069 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
6070 unsigned NumIndirectDests =
Record[OpNum++];
6071 SmallVector<BasicBlock *, 16> IndirectDests;
6072 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
6073 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
6075 unsigned FTyID = InvalidTypeID;
6076 FunctionType *FTy =
nullptr;
6081 return error(
"Explicit call type is not a function type");
6085 unsigned CalleeTypeID;
6086 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6088 return error(
"Invalid callbr record");
6092 return error(
"Callee is not a pointer type");
6094 FTyID = getContainedTypeID(CalleeTypeID);
6097 return error(
"Callee is not of pointer to function type");
6099 if (
Record.size() < FTy->getNumParams() + OpNum)
6100 return error(
"Insufficient operands to call");
6102 SmallVector<Value*, 16>
Args;
6103 SmallVector<unsigned, 16> ArgTyIDs;
6105 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6107 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6108 if (FTy->getParamType(i)->isLabelTy())
6109 Arg = getBasicBlock(Record[OpNum]);
6111 Arg =
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6114 return error(
"Invalid callbr record");
6115 Args.push_back(Arg);
6120 if (!FTy->isVarArg()) {
6121 if (OpNum !=
Record.size())
6122 return error(
"Invalid callbr record");
6124 while (OpNum !=
Record.size()) {
6127 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6128 return error(
"Invalid callbr record");
6135 if (!OperandBundles.empty())
6140 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6143 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6148 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6149 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6150 unsigned LabelNo = ArgNo - FirstBlockArg;
6152 if (!BA || BA->getFunction() !=
F ||
6153 LabelNo > IndirectDests.
size() ||
6154 BA->getBasicBlock() != IndirectDests[LabelNo])
6155 return error(
"callbr argument does not match indirect dest");
6160 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6164 for (
Value *Arg : Args)
6167 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6170 std::string Constraints =
IA->getConstraintString().str();
6173 for (
const auto &CI : ConstraintInfo) {
6175 if (ArgNo >= FirstBlockArg)
6176 Constraints.insert(Pos,
"!");
6181 Pos = Constraints.find(
',', Pos);
6182 if (Pos == std::string::npos)
6188 IA->hasSideEffects(),
IA->isAlignStack(),
6189 IA->getDialect(),
IA->canThrow());
6195 ResTypeID = getContainedTypeID(FTyID);
6196 OperandBundles.clear();
6213 return error(
"Invalid phi record");
6215 unsigned TyID =
Record[0];
6216 Type *Ty = getTypeByID(TyID);
6218 return error(
"Invalid phi record");
6223 size_t NumArgs = (
Record.size() - 1) / 2;
6227 return error(
"Invalid phi record");
6231 SmallDenseMap<BasicBlock *, Value *>
Args;
6232 for (
unsigned i = 0; i != NumArgs; i++) {
6233 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6236 return error(
"Invalid phi BB");
6243 auto It =
Args.find(BB);
6245 if (It !=
Args.end()) {
6259 if (!PhiConstExprBB)
6261 EdgeBB = PhiConstExprBB;
6269 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6271 V =
getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6275 return error(
"Invalid phi record");
6278 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6279 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6280 PhiConstExprBB =
nullptr;
6283 Args.insert({BB,
V});
6289 if (
Record.size() % 2 == 0) {
6293 I->setFastMathFlags(FMF);
6305 return error(
"Invalid landingpad record");
6309 return error(
"Invalid landingpad record");
6311 ResTypeID =
Record[Idx++];
6312 Type *Ty = getTypeByID(ResTypeID);
6314 return error(
"Invalid landingpad record");
6316 Value *PersFn =
nullptr;
6317 unsigned PersFnTypeID;
6318 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6320 return error(
"Invalid landingpad record");
6322 if (!
F->hasPersonalityFn())
6325 return error(
"Personality function mismatch");
6328 bool IsCleanup = !!
Record[Idx++];
6329 unsigned NumClauses =
Record[Idx++];
6332 for (
unsigned J = 0; J != NumClauses; ++J) {
6338 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6341 return error(
"Invalid landingpad record");
6346 "Catch clause has a invalid type!");
6349 "Filter clause has invalid type!");
6360 return error(
"Invalid alloca record");
6361 using APV = AllocaPackedValues;
6362 const uint64_t Rec =
Record[3];
6365 unsigned TyID =
Record[0];
6366 Type *Ty = getTypeByID(TyID);
6368 TyID = getContainedTypeID(TyID);
6369 Ty = getTypeByID(TyID);
6371 return error(
"Missing element type for old-style alloca");
6373 unsigned OpTyID =
Record[1];
6374 Type *OpTy = getTypeByID(OpTyID);
6375 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6380 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6384 return error(
"Invalid alloca record");
6386 const DataLayout &
DL = TheModule->getDataLayout();
6387 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6389 SmallPtrSet<Type *, 4> Visited;
6390 if (!Align && !Ty->
isSized(&Visited))
6391 return error(
"alloca of unsized type");
6393 Align =
DL.getPrefTypeAlign(Ty);
6395 if (!
Size->getType()->isIntegerTy())
6396 return error(
"alloca element count must have integer type");
6398 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6402 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6410 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6411 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6412 return error(
"Invalid load record");
6415 return error(
"Load operand is not a pointer type");
6418 if (OpNum + 3 ==
Record.size()) {
6419 ResTypeID =
Record[OpNum++];
6420 Ty = getTypeByID(ResTypeID);
6422 ResTypeID = getContainedTypeID(OpTypeID);
6423 Ty = getTypeByID(ResTypeID);
6427 return error(
"Missing load type");
6429 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6433 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6435 SmallPtrSet<Type *, 4> Visited;
6436 if (!Align && !Ty->
isSized(&Visited))
6437 return error(
"load of unsized type");
6439 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6440 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6449 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6450 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size()))
6451 return error(
"Invalid load atomic record");
6454 return error(
"Load operand is not a pointer type");
6457 if (OpNum + 5 ==
Record.size()) {
6458 ResTypeID =
Record[OpNum++];
6459 Ty = getTypeByID(ResTypeID);
6461 ResTypeID = getContainedTypeID(OpTypeID);
6462 Ty = getTypeByID(ResTypeID);
6466 return error(
"Missing atomic load type");
6468 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6472 if (Ordering == AtomicOrdering::NotAtomic ||
6473 Ordering == AtomicOrdering::Release ||
6474 Ordering == AtomicOrdering::AcquireRelease)
6475 return error(
"Invalid load atomic record");
6476 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6477 return error(
"Invalid load atomic record");
6478 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6481 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6484 return error(
"Alignment missing from atomic load");
6485 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align, Ordering, SSID);
6493 unsigned PtrTypeID, ValTypeID;
6494 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6495 return error(
"Invalid store record");
6498 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6499 return error(
"Invalid store record");
6501 ValTypeID = getContainedTypeID(PtrTypeID);
6502 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6503 ValTypeID, Val, CurBB))
6504 return error(
"Invalid store record");
6507 if (OpNum + 2 !=
Record.size())
6508 return error(
"Invalid store record");
6513 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6515 SmallPtrSet<Type *, 4> Visited;
6517 return error(
"store of unsized type");
6519 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6520 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6529 unsigned PtrTypeID, ValTypeID;
6530 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6532 return error(
"Invalid store atomic record");
6534 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6535 return error(
"Invalid store atomic record");
6537 ValTypeID = getContainedTypeID(PtrTypeID);
6538 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6539 ValTypeID, Val, CurBB))
6540 return error(
"Invalid store atomic record");
6543 if (OpNum + 4 !=
Record.size())
6544 return error(
"Invalid store atomic record");
6549 if (Ordering == AtomicOrdering::NotAtomic ||
6550 Ordering == AtomicOrdering::Acquire ||
6551 Ordering == AtomicOrdering::AcquireRelease)
6552 return error(
"Invalid store atomic record");
6553 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6554 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6555 return error(
"Invalid store atomic record");
6558 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6561 return error(
"Alignment missing from atomic store");
6562 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6569 const size_t NumRecords =
Record.size();
6571 Value *Ptr =
nullptr;
6573 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6574 return error(
"Invalid cmpxchg record");
6577 return error(
"Cmpxchg operand is not a pointer type");
6580 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6581 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6582 CmpTypeID, Cmp, CurBB))
6583 return error(
"Invalid cmpxchg record");
6586 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6588 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6589 return error(
"Invalid cmpxchg record");
6593 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6594 SuccessOrdering == AtomicOrdering::Unordered)
6595 return error(
"Invalid cmpxchg record");
6597 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6599 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6607 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6608 FailureOrdering == AtomicOrdering::Unordered)
6609 return error(
"Invalid cmpxchg record");
6611 const Align Alignment(
6612 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6614 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6615 FailureOrdering, SSID);
6618 if (NumRecords < 8) {
6622 I->insertInto(CurBB, CurBB->
end());
6624 ResTypeID = CmpTypeID;
6627 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6628 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6637 const size_t NumRecords =
Record.size();
6639 Value *Ptr =
nullptr;
6641 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6642 return error(
"Invalid cmpxchg record");
6645 return error(
"Cmpxchg operand is not a pointer type");
6649 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6650 return error(
"Invalid cmpxchg record");
6652 Value *Val =
nullptr;
6653 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6655 return error(
"Invalid cmpxchg record");
6657 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6658 return error(
"Invalid cmpxchg record");
6660 const bool IsVol =
Record[OpNum];
6665 return error(
"Invalid cmpxchg success ordering");
6667 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6669 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6675 return error(
"Invalid cmpxchg failure ordering");
6677 const bool IsWeak =
Record[OpNum + 4];
6679 MaybeAlign Alignment;
6681 if (NumRecords == (OpNum + 6)) {
6682 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6687 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6689 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6690 FailureOrdering, SSID);
6694 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6695 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6704 const size_t NumRecords =
Record.size();
6707 Value *Ptr =
nullptr;
6709 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6710 return error(
"Invalid atomicrmw record");
6713 return error(
"Invalid atomicrmw record");
6715 Value *Val =
nullptr;
6716 unsigned ValTypeID = InvalidTypeID;
6718 ValTypeID = getContainedTypeID(PtrTypeID);
6719 if (popValue(Record, OpNum, NextValueNo,
6720 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6721 return error(
"Invalid atomicrmw record");
6723 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6724 return error(
"Invalid atomicrmw record");
6727 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6728 return error(
"Invalid atomicrmw record");
6730 bool IsElementwise =
false;
6735 return error(
"Invalid atomicrmw record");
6737 const bool IsVol =
Record[OpNum + 1];
6740 if (Ordering == AtomicOrdering::NotAtomic ||
6741 Ordering == AtomicOrdering::Unordered)
6742 return error(
"Invalid atomicrmw record");
6744 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6746 MaybeAlign Alignment;
6748 if (NumRecords == (OpNum + 5)) {
6749 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6755 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6757 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID,
6759 ResTypeID = ValTypeID;
6767 return error(
"Invalid fence record");
6769 if (Ordering == AtomicOrdering::NotAtomic ||
6770 Ordering == AtomicOrdering::Unordered ||
6771 Ordering == AtomicOrdering::Monotonic)
6772 return error(
"Invalid fence record");
6774 I =
new FenceInst(
Context, Ordering, SSID);
6781 SeenDebugRecord =
true;
6784 return error(
"Invalid dbg record: missing instruction");
6787 Inst->
getParent()->insertDbgRecordBefore(
6798 SeenDebugRecord =
true;
6801 return error(
"Invalid dbg record: missing instruction");
6818 DILocalVariable *Var =
6820 DIExpression *Expr =
6833 unsigned SlotBefore =
Slot;
6834 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6835 return error(
"Invalid dbg record: invalid value");
6837 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6840 RawLocation = getFnMetadataByID(Record[Slot++]);
6843 DbgVariableRecord *DVR =
nullptr;
6847 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6848 DbgVariableRecord::LocationType::Value);
6851 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6852 DbgVariableRecord::LocationType::Declare);
6855 DVR =
new DbgVariableRecord(
6856 RawLocation, Var, Expr, DIL,
6857 DbgVariableRecord::LocationType::DeclareValue);
6861 DIExpression *AddrExpr =
6863 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6864 DVR =
new DbgVariableRecord(RawLocation, Var, Expr,
ID, Addr, AddrExpr,
6877 return error(
"Invalid call record");
6881 unsigned CCInfo =
Record[OpNum++];
6887 return error(
"Fast math flags indicator set for call with no FMF");
6890 unsigned FTyID = InvalidTypeID;
6891 FunctionType *FTy =
nullptr;
6896 return error(
"Explicit call type is not a function type");
6900 unsigned CalleeTypeID;
6901 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6903 return error(
"Invalid call record");
6907 return error(
"Callee is not a pointer type");
6909 FTyID = getContainedTypeID(CalleeTypeID);
6912 return error(
"Callee is not of pointer to function type");
6914 if (
Record.size() < FTy->getNumParams() + OpNum)
6915 return error(
"Insufficient operands to call");
6917 SmallVector<Value*, 16>
Args;
6918 SmallVector<unsigned, 16> ArgTyIDs;
6920 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6921 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6922 if (FTy->getParamType(i)->isLabelTy())
6923 Args.push_back(getBasicBlock(Record[OpNum]));
6926 FTy->getParamType(i), ArgTyID, CurBB));
6929 return error(
"Invalid call record");
6933 if (!FTy->isVarArg()) {
6934 if (OpNum !=
Record.size())
6935 return error(
"Invalid call record");
6937 while (OpNum !=
Record.size()) {
6940 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6941 return error(
"Invalid call record");
6948 if (!OperandBundles.empty())
6952 ResTypeID = getContainedTypeID(FTyID);
6953 OperandBundles.clear();
6967 SeenDebugIntrinsic =
true;
6974 return error(
"Fast-math-flags specified for call without "
6975 "floating-point scalar or vector return type");
6976 I->setFastMathFlags(FMF);
6982 return error(
"Invalid va_arg record");
6983 unsigned OpTyID =
Record[0];
6984 Type *OpTy = getTypeByID(OpTyID);
6987 Type *ResTy = getTypeByID(ResTypeID);
6988 if (!OpTy || !
Op || !ResTy)
6989 return error(
"Invalid va_arg record");
6990 I =
new VAArgInst(
Op, ResTy);
7000 if (
Record.empty() || Record[0] >= BundleTags.size())
7001 return error(
"Invalid operand bundle record");
7003 std::vector<Value *> Inputs;
7006 while (OpNum !=
Record.size()) {
7008 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
7009 return error(
"Invalid operand bundle record");
7010 Inputs.push_back(
Op);
7013 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
7021 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7022 return error(
"Invalid freeze record");
7023 if (OpNum !=
Record.size())
7024 return error(
"Invalid freeze record");
7026 I =
new FreezeInst(
Op);
7027 ResTypeID = OpTypeID;
7037 return error(
"Invalid instruction with no BB");
7039 if (!OperandBundles.empty()) {
7041 return error(
"Operand bundles found with no consumer");
7043 I->insertInto(CurBB, CurBB->
end());
7046 if (
I->isTerminator()) {
7048 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
7052 if (!
I->getType()->isVoidTy()) {
7053 assert(
I->getType() == getTypeByID(ResTypeID) &&
7054 "Incorrect result type ID");
7062 if (!OperandBundles.empty())
7063 return error(
"Operand bundles found with no consumer");
7067 if (!
A->getParent()) {
7069 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
7075 return error(
"Never resolved value found in function");
7080 if (MDLoader->hasFwdRefs())
7081 return error(
"Invalid function metadata: outgoing forward refs");
7086 for (
const auto &Pair : ConstExprEdgeBBs) {
7097 ValueList.
shrinkTo(ModuleValueListSize);
7098 MDLoader->shrinkTo(ModuleMDLoaderSize);
7099 std::vector<BasicBlock*>().swap(FunctionBBs);
7104Error BitcodeReader::findFunctionInStream(
7106 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7107 while (DeferredFunctionInfoIterator->second == 0) {
7112 assert(VSTOffset == 0 || !
F->hasName());
7115 if (
Error Err = rememberAndSkipFunctionBodies())
7121SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7124 if (Val >= SSIDs.
size())
7133Error BitcodeReader::materialize(GlobalValue *GV) {
7136 if (!
F || !
F->isMaterializable())
7139 auto DFII = DeferredFunctionInfo.
find(
F);
7140 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7143 if (DFII->second == 0)
7144 if (
Error Err = findFunctionInStream(
F, DFII))
7148 if (
Error Err = materializeMetadata())
7155 if (
Error Err = parseFunctionBody(
F))
7157 F->setIsMaterializable(
false);
7161 if (SeenDebugIntrinsic && SeenDebugRecord)
7162 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7168 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7169 F->setSubprogram(SP);
7172 if (!MDLoader->isStrippingTBAA()) {
7174 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7177 MDLoader->setStripTBAA(
true);
7184 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7185 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7191 unsigned ExpectedNumOperands = 0;
7193 ExpectedNumOperands = 2;
7195 ExpectedNumOperands =
SI->getNumSuccessors();
7197 ExpectedNumOperands = 1;
7201 ExpectedNumOperands = 2;
7208 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7209 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7215 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7216 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7218 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7219 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7220 CI->getArgOperand(ArgNo)->getType(),
7221 CI->getParamAttributes(ArgNo)));
7224 if (Function *OldFn = CI->getCalledFunction()) {
7225 auto It = UpgradedIntrinsics.
find(OldFn);
7226 if (It != UpgradedIntrinsics.
end())
7230 BC && BC->getSrcTy() == BC->getDestTy() &&
7236 CI && CI->isMustTailCall() && CI->getNextNode() == BC) {
7237 BC->replaceAllUsesWith(CI);
7238 BC->eraseFromParent();
7248 return materializeForwardReferencedFunctions();
7251Error BitcodeReader::materializeModule() {
7252 if (
Error Err = materializeMetadata())
7256 WillMaterializeAllForwardRefs =
true;
7260 for (Function &
F : *TheModule) {
7261 if (
Error Err = materialize(&
F))
7267 if (LastFunctionBlockBit || NextUnreadBit)
7269 ? LastFunctionBlockBit
7275 if (!BasicBlockFwdRefs.
empty())
7276 return error(
"Never resolved function from blockaddress");
7282 for (
auto &[OldFn, NewFn] : UpgradedIntrinsics) {
7283 for (User *U : OldFn->users()) {
7287 if (OldFn != NewFn) {
7288 if (!OldFn->use_empty())
7289 OldFn->replaceAllUsesWith(NewFn);
7290 OldFn->eraseFromParent();
7293 UpgradedIntrinsics.clear();
7308std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7309 return IdentifiedStructTypes;
7312ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7313 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7314 StringRef ModulePath, std::function<
bool(StringRef)> IsPrevailing,
7315 std::function<
void(ValueInfo)> OnValueInfo)
7316 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7317 ModulePath(ModulePath), IsPrevailing(IsPrevailing),
7318 OnValueInfo(OnValueInfo) {}
7320void ModuleSummaryIndexBitcodeReader::addThisModule() {
7325ModuleSummaryIndexBitcodeReader::getThisModule() {
7329template <
bool AllowNullValueInfo>
7330std::pair<ValueInfo, GlobalValue::GUID>
7331ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7332 auto VGI = ValueIdToValueInfoMap[ValueId];
7339 assert(AllowNullValueInfo || std::get<0>(VGI));
7343void ModuleSummaryIndexBitcodeReader::setValueGUID(
7345 StringRef SourceFileName) {
7347 if (ValueID < DefinedGUIDs.size())
7348 ValueGUID = DefinedGUIDs[ValueID];
7355 auto OriginalNameID = ValueGUID;
7359 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7367 ValueIdToValueInfoMap[ValueID] = std::make_pair(VI, OriginalNameID);
7375Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7377 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7384 if (!MaybeCurrentBit)
7386 uint64_t CurrentBit = MaybeCurrentBit.
get();
7391 SmallVector<uint64_t, 64>
Record;
7400 BitstreamEntry
Entry = MaybeEntry.
get();
7402 switch (
Entry.Kind) {
7405 return error(
"Malformed block");
7421 switch (MaybeRecord.
get()) {
7426 return error(
"Invalid vst_code_entry record");
7427 unsigned ValueID =
Record[0];
7429 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7430 assert(VLI != ValueIdToLinkageMap.
end() &&
7431 "No linkage found for VST entry?");
7440 return error(
"Invalid vst_code_fnentry record");
7441 unsigned ValueID =
Record[0];
7443 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7444 assert(VLI != ValueIdToLinkageMap.
end() &&
7445 "No linkage found for VST entry?");
7453 unsigned ValueID =
Record[0];
7457 ValueIdToValueInfoMap[ValueID] =
7468Error ModuleSummaryIndexBitcodeReader::parseModule() {
7472 SmallVector<uint64_t, 64>
Record;
7473 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7474 unsigned ValueId = 0;
7478 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
7481 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7483 switch (
Entry.Kind) {
7485 return error(
"Malformed block");
7497 if (
Error Err = readBlockInfo())
7503 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7504 !SeenGlobalValSummary) &&
7505 "Expected early VST parse via VSTOffset record");
7512 if (!SourceFileName.
empty())
7514 assert(!SeenValueSymbolTable &&
7515 "Already read VST when parsing summary block?");
7520 if (VSTOffset > 0) {
7521 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7523 SeenValueSymbolTable =
true;
7525 SeenGlobalValSummary =
true;
7526 if (
Error Err = parseEntireSummary(
Entry.ID))
7530 if (
Error Err = parseModuleStringTable())
7538 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7541 switch (MaybeBitCode.
get()) {
7545 if (
Error Err = parseVersionRecord(Record).takeError())
7553 return error(
"Invalid source filename record");
7560 return error(
"Invalid hash length " + Twine(
Record.size()));
7561 auto &Hash = getThisModule()->second;
7563 for (
auto &Val : Record) {
7564 assert(!(Val >> 32) &&
"Unexpected high bits set");
7572 return error(
"Invalid vstoffset record");
7576 VSTOffset =
Record[0] - 1;
7581 DefinedGUIDs.reserve(DefinedGUIDs.size() +
Record.size() / 2);
7582 for (
size_t i = 0; i <
Record.size(); i += 2)
7583 DefinedGUIDs.push_back(Record[i] << 32 | Record[i + 1]);
7593 ArrayRef<uint64_t> GVRecord;
7594 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7595 if (GVRecord.
size() <= 3)
7596 return error(
"Invalid global record");
7597 uint64_t RawLinkage = GVRecord[3];
7600 ValueIdToLinkageMap[ValueId++] =
Linkage;
7604 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7615ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7618 for (uint64_t RefValueId : Record)
7619 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7624ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7625 bool IsOldProfileFormat,
7626 bool HasProfile,
bool HasRelBF) {
7630 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7635 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7637 bool HasTailCall =
false;
7639 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7640 if (IsOldProfileFormat) {
7644 }
else if (HasProfile)
7645 std::tie(Hotness, HasTailCall) =
7679 static_cast<size_t>(
Record[Slot + 1])};
7702 while (Slot <
Record.size())
7706std::vector<FunctionSummary::ParamAccess>
7707ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7708 auto ReadRange = [&]() {
7710 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7712 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7719 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7720 while (!
Record.empty()) {
7721 PendingParamAccesses.emplace_back();
7722 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7724 ParamAccess.
Use = ReadRange();
7729 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7730 Call.Offsets = ReadRange();
7733 return PendingParamAccesses;
7736void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7737 ArrayRef<uint64_t> Record,
size_t &Slot,
7740 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7744void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7745 ArrayRef<uint64_t> Record) {
7753 while (Slot <
Record.size())
7754 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7757SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7758 ArrayRef<uint64_t> Record,
unsigned &
I) {
7759 SmallVector<unsigned> StackIdList;
7763 if (RadixArray.empty()) {
7764 unsigned NumStackEntries =
Record[
I++];
7766 StackIdList.
reserve(NumStackEntries);
7767 for (
unsigned J = 0; J < NumStackEntries; J++) {
7768 assert(Record[
I] < StackIds.size());
7769 StackIdList.
push_back(getStackIdIndex(Record[
I++]));
7772 unsigned RadixIndex =
Record[
I++];
7778 assert(RadixIndex < RadixArray.size());
7779 unsigned NumStackIds = RadixArray[RadixIndex++];
7780 StackIdList.
reserve(NumStackIds);
7781 while (NumStackIds--) {
7782 assert(RadixIndex < RadixArray.size());
7783 unsigned Elem = RadixArray[RadixIndex];
7784 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7785 RadixIndex = RadixIndex - Elem;
7786 assert(RadixIndex < RadixArray.size());
7787 Elem = RadixArray[RadixIndex];
7789 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7792 StackIdList.
push_back(getStackIdIndex(Elem));
7802 unsigned FirstWORef = Refs.
size() - WOCnt;
7803 unsigned RefNo = FirstWORef - ROCnt;
7804 for (; RefNo < FirstWORef; ++RefNo)
7805 Refs[RefNo].setReadOnly();
7806 for (; RefNo < Refs.
size(); ++RefNo)
7807 Refs[RefNo].setWriteOnly();
7812Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7815 SmallVector<uint64_t, 64>
Record;
7822 BitstreamEntry
Entry = MaybeEntry.
get();
7825 return error(
"Invalid Summary Block: record for version expected");
7830 return error(
"Invalid Summary Block: version expected");
7833 const bool IsOldProfileFormat =
Version == 1;
7836 const bool MemProfAfterFunctionSummary =
Version >= 13;
7838 return error(
"Invalid summary version " + Twine(
Version) +
" in module '" +
7839 ModulePath +
"'. Version should be in the range [1-" +
7845 GlobalValueSummary *LastSeenSummary =
nullptr;
7855 FunctionSummary *CurrentPrevailingFS =
nullptr;
7860 std::vector<GlobalValue::GUID> PendingTypeTests;
7861 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7862 PendingTypeCheckedLoadVCalls;
7863 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7864 PendingTypeCheckedLoadConstVCalls;
7865 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7867 std::vector<CallsiteInfo> PendingCallsites;
7868 std::vector<AllocInfo> PendingAllocs;
7869 std::vector<uint64_t> PendingContextIds;
7875 BitstreamEntry
Entry = MaybeEntry.
get();
7877 switch (
Entry.Kind) {
7880 return error(
"Malformed block");
7896 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7899 unsigned BitCode = MaybeBitCode.
get();
7909 uint64_t ValueID =
Record[0];
7916 ValueIdToValueInfoMap[ValueID] =
7934 unsigned ValueID =
Record[0];
7935 uint64_t RawFlags =
Record[1];
7936 unsigned InstCount =
Record[2];
7937 uint64_t RawFunFlags = 0;
7938 unsigned NumRefs =
Record[3];
7939 unsigned NumRORefs = 0, NumWORefs = 0;
7940 int RefListStartIndex = 4;
7944 RefListStartIndex = 5;
7947 RefListStartIndex = 6;
7950 RefListStartIndex = 7;
7961 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7963 "Record size inconsistent with number of references");
7965 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7970 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7971 IsOldProfileFormat, HasProfile, HasRelBF);
7973 auto [
VI,
GUID] = getValueInfoFromValueId(ValueID);
7980 IsPrevailing(
VI.name());
7986 assert(!MemProfAfterFunctionSummary ||
7987 (PendingCallsites.empty() && PendingAllocs.empty()));
7988 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
7989 PendingCallsites.clear();
7990 PendingAllocs.clear();
7993 auto FS = std::make_unique<FunctionSummary>(
7995 std::move(Calls), std::move(PendingTypeTests),
7996 std::move(PendingTypeTestAssumeVCalls),
7997 std::move(PendingTypeCheckedLoadVCalls),
7998 std::move(PendingTypeTestAssumeConstVCalls),
7999 std::move(PendingTypeCheckedLoadConstVCalls),
8000 std::move(PendingParamAccesses), std::move(PendingCallsites),
8001 std::move(PendingAllocs));
8002 FS->setModulePath(getThisModule()->first());
8003 FS->setOriginalName(GUID);
8006 if (MemProfAfterFunctionSummary) {
8007 if (IsPrevailingSym)
8008 CurrentPrevailingFS =
FS.get();
8010 CurrentPrevailingFS =
nullptr;
8019 unsigned ValueID =
Record[0];
8020 uint64_t RawFlags =
Record[1];
8021 unsigned AliaseeID =
Record[2];
8023 auto AS = std::make_unique<AliasSummary>(Flags);
8029 AS->setModulePath(getThisModule()->first());
8031 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
8033 if (!AliaseeInModule)
8034 return error(
"Alias expects aliasee summary to be parsed");
8035 AS->setAliasee(AliaseeVI, AliaseeInModule);
8037 auto GUID = getValueInfoFromValueId(ValueID);
8038 AS->setOriginalName(std::get<1>(GUID));
8044 unsigned ValueID =
Record[0];
8045 uint64_t RawFlags =
Record[1];
8046 unsigned RefArrayStart = 2;
8047 GlobalVarSummary::GVarFlags GVF(
false,
8057 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8059 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8060 FS->setModulePath(getThisModule()->first());
8061 auto GUID = getValueInfoFromValueId(ValueID);
8062 FS->setOriginalName(std::get<1>(GUID));
8070 unsigned ValueID =
Record[0];
8071 uint64_t RawFlags =
Record[1];
8073 unsigned NumRefs =
Record[3];
8074 unsigned RefListStartIndex = 4;
8075 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
8078 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8080 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
8081 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
8086 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8087 VS->setModulePath(getThisModule()->first());
8088 VS->setVTableFuncs(VTableFuncs);
8089 auto GUID = getValueInfoFromValueId(ValueID);
8090 VS->setOriginalName(std::get<1>(GUID));
8102 unsigned ValueID =
Record[0];
8103 uint64_t ModuleId =
Record[1];
8104 uint64_t RawFlags =
Record[2];
8105 unsigned InstCount =
Record[3];
8106 uint64_t RawFunFlags = 0;
8107 unsigned NumRefs =
Record[4];
8108 unsigned NumRORefs = 0, NumWORefs = 0;
8109 int RefListStartIndex = 5;
8113 RefListStartIndex = 6;
8114 size_t NumRefsIndex = 5;
8116 unsigned NumRORefsOffset = 1;
8117 RefListStartIndex = 7;
8120 RefListStartIndex = 8;
8122 RefListStartIndex = 9;
8124 NumRORefsOffset = 2;
8127 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
8129 NumRefs =
Record[NumRefsIndex];
8133 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8135 "Record size inconsistent with number of references");
8137 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8140 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8141 IsOldProfileFormat, HasProfile,
false);
8142 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8144 auto FS = std::make_unique<FunctionSummary>(
8146 std::move(Edges), std::move(PendingTypeTests),
8147 std::move(PendingTypeTestAssumeVCalls),
8148 std::move(PendingTypeCheckedLoadVCalls),
8149 std::move(PendingTypeTestAssumeConstVCalls),
8150 std::move(PendingTypeCheckedLoadConstVCalls),
8151 std::move(PendingParamAccesses), std::move(PendingCallsites),
8152 std::move(PendingAllocs));
8153 LastSeenSummary =
FS.get();
8154 if (MemProfAfterFunctionSummary)
8155 CurrentPrevailingFS =
FS.get();
8156 LastSeenGUID =
VI.getGUID();
8157 FS->setModulePath(ModuleIdMap[ModuleId]);
8165 unsigned ValueID =
Record[0];
8166 uint64_t ModuleId =
Record[1];
8167 uint64_t RawFlags =
Record[2];
8168 unsigned AliaseeValueId =
Record[3];
8170 auto AS = std::make_unique<AliasSummary>(Flags);
8171 LastSeenSummary = AS.get();
8172 AS->setModulePath(ModuleIdMap[ModuleId]);
8174 auto AliaseeVI = std::get<0>(
8175 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8177 auto AliaseeInModule =
8179 AS->setAliasee(AliaseeVI, AliaseeInModule);
8181 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8182 LastSeenGUID =
VI.getGUID();
8188 unsigned ValueID =
Record[0];
8189 uint64_t ModuleId =
Record[1];
8190 uint64_t RawFlags =
Record[2];
8191 unsigned RefArrayStart = 3;
8192 GlobalVarSummary::GVarFlags GVF(
false,
8202 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8204 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8205 LastSeenSummary =
FS.get();
8206 FS->setModulePath(ModuleIdMap[ModuleId]);
8207 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8208 LastSeenGUID =
VI.getGUID();
8214 uint64_t OriginalName =
Record[0];
8215 if (!LastSeenSummary)
8216 return error(
"Name attachment that does not follow a combined record");
8220 LastSeenSummary =
nullptr;
8225 assert(PendingTypeTests.empty());
8230 assert(PendingTypeTestAssumeVCalls.empty());
8231 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8232 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8236 assert(PendingTypeCheckedLoadVCalls.empty());
8237 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8238 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8242 PendingTypeTestAssumeConstVCalls.push_back(
8247 PendingTypeCheckedLoadConstVCalls.push_back(
8254 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8255 StringRef
Name(Strtab.
data() + Record[
I],
8256 static_cast<size_t>(Record[
I + 1]));
8259 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, GUID);
8262 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8264 StringRef
Name(Strtab.
data() + Record[
I + 1],
8265 static_cast<size_t>(Record[
I + 2]));
8266 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8275 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8276 StringRef
Name(Strtab.
data() + Record[
I],
8277 static_cast<size_t>(Record[
I + 1]));
8280 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, GUID);
8283 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8285 StringRef
Name(Strtab.
data() + Record[
I + 1],
8286 static_cast<size_t>(Record[
I + 2]));
8287 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8298 parseTypeIdCompatibleVtableSummaryRecord(Record);
8306 PendingParamAccesses = parseParamAccesses(Record);
8313 assert(StackIds.empty());
8315 StackIds = ArrayRef<uint64_t>(Record);
8321 StackIds.reserve(
Record.size() / 2);
8322 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8323 StackIds.push_back(*R << 32 | *(R + 1));
8325 assert(StackIdToIndex.empty());
8327 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8332 RadixArray = ArrayRef<uint64_t>(Record);
8339 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8341 unsigned ValueID =
Record[0];
8342 SmallVector<unsigned> StackIdList;
8344 assert(R < StackIds.size());
8345 StackIdList.
push_back(getStackIdIndex(R));
8347 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8348 if (MemProfAfterFunctionSummary)
8350 CallsiteInfo({
VI, std::move(StackIdList)}));
8352 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8359 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8360 auto RecordIter =
Record.begin();
8361 unsigned ValueID = *RecordIter++;
8362 unsigned NumStackIds = *RecordIter++;
8363 unsigned NumVersions = *RecordIter++;
8364 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8365 SmallVector<unsigned> StackIdList;
8366 for (
unsigned J = 0; J < NumStackIds; J++) {
8367 assert(*RecordIter < StackIds.size());
8368 StackIdList.
push_back(getStackIdIndex(*RecordIter++));
8370 SmallVector<unsigned> Versions;
8371 for (
unsigned J = 0; J < NumVersions; J++)
8373 ValueInfo
VI = std::get<0>(
8374 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8375 if (MemProfAfterFunctionSummary)
8377 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8379 PendingCallsites.push_back(
8380 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8387 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8392 PendingContextIds.reserve(
Record.size() / 2);
8393 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8394 PendingContextIds.push_back(*R << 32 | *(R + 1));
8401 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8402 PendingContextIds.clear();
8406 std::vector<MIBInfo> MIBs;
8407 unsigned NumMIBs = 0;
8410 unsigned MIBsRead = 0;
8411 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8415 auto StackIdList = parseAllocInfoContext(Record,
I);
8416 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8422 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8424 assert(!PendingContextIds.empty() &&
8425 "Missing context ids for alloc sizes");
8426 unsigned ContextIdIndex = 0;
8432 while (MIBsRead++ < NumMIBs) {
8434 unsigned NumContextSizeInfoEntries =
Record[
I++];
8436 std::vector<ContextTotalSize> ContextSizes;
8437 ContextSizes.reserve(NumContextSizeInfoEntries);
8438 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8439 assert(ContextIdIndex < PendingContextIds.size());
8441 if (PendingContextIds[ContextIdIndex] == 0) {
8450 ContextSizes.push_back(
8451 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8453 AllContextSizes.push_back(std::move(ContextSizes));
8455 PendingContextIds.clear();
8457 AllocInfo AI(std::move(MIBs));
8458 if (!AllContextSizes.empty()) {
8459 assert(AI.MIBs.size() == AllContextSizes.size());
8460 AI.ContextSizeInfos = std::move(AllContextSizes);
8463 if (MemProfAfterFunctionSummary)
8464 CurrentPrevailingFS->
addAlloc(std::move(AI));
8466 PendingAllocs.push_back(std::move(AI));
8474 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8476 std::vector<MIBInfo> MIBs;
8477 unsigned NumMIBs =
Record[
I++];
8478 unsigned NumVersions =
Record[
I++];
8479 unsigned MIBsRead = 0;
8480 while (MIBsRead++ < NumMIBs) {
8483 SmallVector<unsigned> StackIdList;
8485 StackIdList = parseAllocInfoContext(Record,
I);
8486 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8489 SmallVector<uint8_t> Versions;
8490 for (
unsigned J = 0; J < NumVersions; J++)
8493 AllocInfo AI(std::move(Versions), std::move(MIBs));
8494 if (MemProfAfterFunctionSummary)
8495 CurrentPrevailingFS->
addAlloc(std::move(AI));
8497 PendingAllocs.push_back(std::move(AI));
8507Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8511 SmallVector<uint64_t, 64>
Record;
8513 SmallString<128> ModulePath;
8520 BitstreamEntry
Entry = MaybeEntry.
get();
8522 switch (
Entry.Kind) {
8525 return error(
"Malformed block");
8537 switch (MaybeRecord.
get()) {
8542 uint64_t ModuleId =
Record[0];
8545 return error(
"Invalid code_entry record");
8547 LastSeenModule = TheIndex.
addModule(ModulePath);
8548 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8556 return error(
"Invalid hash length " + Twine(
Record.size()));
8557 if (!LastSeenModule)
8558 return error(
"Invalid hash that does not follow a module path");
8560 for (
auto &Val : Record) {
8561 assert(!(Val >> 32) &&
"Unexpected high bits set");
8562 LastSeenModule->
second[Pos++] = Val;
8565 LastSeenModule =
nullptr;
8578class BitcodeErrorCategoryType :
public std::error_category {
8579 const char *
name()
const noexcept
override {
8580 return "llvm.bitcode";
8583 std::string message(
int IE)
const override {
8586 case BitcodeError::CorruptedBitcode:
8587 return "Corrupted bitcode";
8596 static BitcodeErrorCategoryType ErrorCategory;
8597 return ErrorCategory;
8601 unsigned Block,
unsigned RecordID) {
8603 return std::move(Err);
8612 switch (Entry.Kind) {
8617 return error(
"Malformed block");
8621 return std::move(Err);
8631 if (MaybeRecord.
get() == RecordID)
8642Expected<std::vector<BitcodeModule>>
8646 return FOrErr.takeError();
8647 return std::move(FOrErr->Mods);
8672 switch (Entry.Kind) {
8675 return error(
"Malformed block");
8678 uint64_t IdentificationBit = -1ull;
8682 return std::move(Err);
8688 Entry = MaybeEntry.
get();
8693 return error(
"Malformed block");
8699 return std::move(Err);
8718 if (!
I.Strtab.empty())
8725 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8726 F.StrtabForSymtab = *Strtab;
8742 if (
F.Symtab.empty())
8743 F.Symtab = *SymtabOrErr;
8748 return std::move(Err);
8753 return std::move(E);
8768BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8769 bool ShouldLazyLoadMetadata,
bool IsImporting,
8773 std::string ProducerIdentification;
8774 if (IdentificationBit != -1ull) {
8776 return std::move(JumpFailed);
8779 return std::move(
E);
8785 Triple BitcodeTargetTriple;
8786 BitstreamCursor TripleStream(Buffer);
8787 if (Expected<std::string> TripleStr =
readTriple(TripleStream))
8788 BitcodeTargetTriple = Triple(*TripleStr);
8793 return std::move(JumpFailed);
8794 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8795 Context, BitcodeTargetTriple);
8797 std::unique_ptr<Module>
M =
8798 std::make_unique<Module>(ModuleIdentifier,
Context);
8799 M->setMaterializer(R);
8802 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8803 IsImporting, Callbacks))
8804 return std::move(Err);
8806 if (MaterializeAll) {
8808 if (
Error Err =
M->materializeAll())
8809 return std::move(Err);
8812 if (
Error Err =
R->materializeForwardReferencedFunctions())
8813 return std::move(Err);
8816 return std::move(M);
8819Expected<std::unique_ptr<Module>>
8822 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8832 std::function<
bool(
StringRef)> IsPrevailing,
8833 std::function<
void(
ValueInfo)> OnValueInfo) {
8838 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8839 ModulePath, IsPrevailing, OnValueInfo);
8840 return R.parseModule();
8847 return std::move(JumpFailed);
8849 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8850 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8851 ModuleIdentifier, 0);
8853 if (
Error Err = R.parseModule())
8854 return std::move(Err);
8856 return std::move(Index);
8862 return std::move(Err);
8868 return std::move(
E);
8870 switch (Entry.Kind) {
8873 return error(
"Malformed block");
8876 return std::make_pair(
false,
false);
8888 switch (MaybeBitCode.
get()) {
8894 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
8896 bool EnableSplitLTOUnit = Flags & 0x8;
8897 bool UnifiedLTO = Flags & 0x200;
8898 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8909 return std::move(JumpFailed);
8912 return std::move(Err);
8917 return std::move(E);
8919 switch (Entry.Kind) {
8921 return error(
"Malformed block");
8932 return Flags.takeError();
8942 return std::move(Err);
8949 return StreamFailed.takeError();
8959 if (MsOrErr->size() != 1)
8960 return error(
"Expected a single module");
8962 return (*MsOrErr)[0];
8965Expected<std::unique_ptr<Module>>
8967 bool ShouldLazyLoadMetadata,
bool IsImporting,
8973 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8978 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
8979 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
8981 IsImporting, Callbacks);
8983 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8989 return getModuleImpl(Context,
true,
false,
false, Callbacks);
9001 return BM->parseModule(Context, Callbacks);
9034 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
9043 return BM->getSummary();
9051 return BM->getLTOInfo();
9056 bool IgnoreEmptyThinLTOIndexFile) {
9061 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< 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)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
bool isIntPredicate() const
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
static Constant * getRaw(StringRef Data, uint64_t NumElements, Type *ElementTy)
getRaw() constructor - Return a constant with vector type with an element count and element type matc...
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
LLVM_ABI bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static DeadOnReturnInfo createFromIntValue(uint64_t Data)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
Convenience struct for specifying and reasoning about fast-math flags.
void setFast(bool B=true)
void setAllowContract(bool B=true)
void setAllowReciprocal(bool B=true)
void setNoSignedZeros(bool B=true)
void setNoNaNs(bool B=true)
void setAllowReassoc(bool B=true)
Flag setters.
void setApproxFunc(bool B=true)
void setNoInfs(bool B=true)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
void addCallsite(CallsiteInfo &&Callsite)
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
void addAlloc(AllocInfo &&Alloc)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
BasicBlockListType::iterator iterator
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
bool hasDefaultVisibility() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
bool hasExternalWeakLinkage() const
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
LLVM_ABI void setPartition(StringRef Part)
void setAttributes(AttributeSet A)
Set attribute list for this global.
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
std::vector< ConstraintInfo > ConstraintInfoVector
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
const char * getOpcodeName() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
@ MIN_INT_BITS
Minimum number of bits that can be specified.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
LLVM_ABI StringRef getString() const
ValueT lookup(const KeyT &Key) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static MemoryEffectsBase readOnly()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase createFromIntValue(uint32_t Data)
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
StringRef saveString(StringRef String)
LLVM_ABI void setFlags(uint64_t Flags)
CfiFunctionIndex & cfiFunctionDecls()
void addBlockCount(uint64_t C)
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
CfiFunctionIndex & cfiFunctionDefs()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
void append(StringRef RHS)
Append from a StringRef.
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
LLVM_ABI void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Triple - Helper class for working with autoconf configuration names.
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
Type * getArrayElementType() const
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
const ParentTy * getParent() const
self_iterator getIterator()
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
@ BasicBlock
Various leaf nodes.
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
@ System
Synchronized with respect to all concurrently executing threads.
@ TYPE_CODE_OPAQUE_POINTER
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_CE_INBOUNDS_GEP
@ CST_CODE_INLINEASM_OLD3
@ CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_INLINEASM_OLD2
@ CST_CODE_CE_GEP_WITH_INRANGE
@ VST_CODE_COMBINED_ENTRY
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_INACCESSIBLEMEM_ONLY
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_ATOMICRMW_OLD
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
@ FUNC_CODE_INST_STOREATOMIC_OLD
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_INST_LANDINGPAD_OLD
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_STORE_OLD
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_CMPXCHG_OLD
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
constexpr bool IsBigEndianHost
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
StringMapEntry< Value * > ValueName
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI const std::error_category & BitcodeErrorCategory()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI void UpgradeInlineAsmString(std::string *AsmStr)
Upgrade comment in call to inline asm that represents an objc retain release marker.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
std::error_code make_error_code(BitcodeError E)
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto uninitialized_copy(R &&Src, IterTy Dst)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
bool isa_and_nonnull(const Y &Val)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
LLVM_ABI void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
auto reverse(ContainerTy &&C)
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI std::string UpgradeDataLayoutString(StringRef DL, StringRef Triple)
Upgrade the datalayout string by adding a section for address space pointers.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ ArgMem
Access to memory via argument pointers.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
LLVM_ABI Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
MaybeAlign decodeMaybeAlign(unsigned Value)
Dual operation of the encode function above.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Basic information extracted from a bitcode module to be used for LTO.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
static constexpr DenormalFPEnv createFromIntValue(uint32_t Data)
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const char * BranchWeights
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
std::optional< DataLayoutCallbackFuncTy > DataLayout
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
bool SkipDebugIntrinsicUpgrade
If true, do not auto-upgrade debug intrinsic calls (llvm.dbg.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
Kind
Specifies which kind of type check we should emit for this byte array.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Struct that holds a reference to a particular GUID in a global value summary.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName