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;
585 uint64_t NextUnreadBit = 0;
587 uint64_t LastFunctionBlockBit = 0;
588 bool SeenValueSymbolTable =
false;
589 uint64_t VSTOffset = 0;
591 std::vector<std::string> SectionTable;
592 std::vector<std::string> GCTable;
594 std::vector<Type *> TypeList;
598 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
605 DenseMap<std::pair<Type *, unsigned>,
unsigned> VirtualTypeIDs;
606 DenseMap<Function *, unsigned> FunctionTypeIDs;
611 BitcodeReaderValueList ValueList;
612 std::optional<MetadataLoader> MDLoader;
613 std::vector<Comdat *> ComdatList;
614 DenseSet<GlobalObject *> ImplicitComdatObjects;
617 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
618 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
620 struct FunctionOperandInfo {
622 unsigned PersonalityFn;
626 std::vector<FunctionOperandInfo> FunctionOperands;
630 std::vector<AttributeList> MAttributes;
633 std::map<unsigned, AttributeList> MAttributeGroups;
637 std::vector<BasicBlock*> FunctionBBs;
641 std::vector<Function*> FunctionsWithBodies;
645 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
646 UpdatedIntrinsicMap 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 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
702 StringRef ProducerIdentification, LLVMContext &
Context);
704 Error materializeForwardReferencedFunctions();
706 Error materialize(GlobalValue *GV)
override;
707 Error materializeModule()
override;
708 std::vector<StructType *> getIdentifiedStructTypes()
const override;
712 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
713 bool IsImporting, ParserCallbacks Callbacks = {});
715 static uint64_t decodeSignRotatedValue(uint64_t V);
718 Error materializeMetadata()
override;
720 void setStripDebugInfo()
override;
723 std::vector<StructType *> IdentifiedStructTypes;
724 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
725 StructType *createIdentifiedStructType(LLVMContext &
Context);
727 static constexpr unsigned InvalidTypeID = ~0
u;
729 Type *getTypeByID(
unsigned ID);
730 Type *getPtrElementTypeByID(
unsigned ID);
731 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
732 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
735 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
736 Expected<Constant *> getValueForInitializer(
unsigned ID);
738 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
739 BasicBlock *ConstExprInsertBB) {
746 return MDLoader->getMetadataFwdRefOrLoad(
ID);
750 if (
ID >= FunctionBBs.size())
return nullptr;
751 return FunctionBBs[
ID];
755 if (i-1 < MAttributes.size())
756 return MAttributes[i-1];
757 return AttributeList();
763 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
764 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
765 BasicBlock *ConstExprInsertBB) {
766 if (Slot ==
Record.size())
return true;
767 unsigned ValNo = (unsigned)Record[Slot++];
770 ValNo = InstNum - ValNo;
771 if (ValNo < InstNum) {
775 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
777 "Incorrect type ID stored for value");
778 return ResVal ==
nullptr;
780 if (Slot ==
Record.size())
783 TypeID = (unsigned)Record[Slot++];
784 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
786 return ResVal ==
nullptr;
789 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
790 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
791 BasicBlock *ConstExprInsertBB) {
792 if (Slot ==
Record.size())
797 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
800 if (Slot ==
Record.size())
802 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
810 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
811 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
812 BasicBlock *ConstExprInsertBB) {
813 if (
getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
821 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
822 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
823 BasicBlock *ConstExprInsertBB) {
824 ResVal =
getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
825 return ResVal ==
nullptr;
830 Value *
getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
831 unsigned InstNum,
Type *Ty,
unsigned TyID,
832 BasicBlock *ConstExprInsertBB) {
833 if (Slot ==
Record.size())
return nullptr;
834 unsigned ValNo = (unsigned)Record[Slot];
837 ValNo = InstNum - ValNo;
838 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
842 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
843 unsigned InstNum,
Type *Ty,
unsigned TyID,
844 BasicBlock *ConstExprInsertBB) {
845 if (Slot ==
Record.size())
return nullptr;
846 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
849 ValNo = InstNum - ValNo;
850 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
853 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
856 if (
Record.size() - OpNum < 2)
857 return error(
"Too few records for range");
859 unsigned LowerActiveWords =
Record[OpNum];
860 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
861 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
862 return error(
"Too few records for range");
865 OpNum += LowerActiveWords;
868 OpNum += UpperActiveWords;
871 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
872 int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
873 return ConstantRange(APInt(
BitWidth, Start,
true),
878 Expected<ConstantRange>
879 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
880 if (
Record.size() - OpNum < 1)
881 return error(
"Too few records for range");
883 return readConstantRange(Record, OpNum,
BitWidth);
889 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
894 Error parseAlignmentValue(uint64_t
Exponent, MaybeAlign &Alignment);
895 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
897 ParserCallbacks Callbacks = {});
899 Error parseComdatRecord(ArrayRef<uint64_t> Record);
900 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
901 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
902 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
903 ArrayRef<uint64_t> Record);
905 Error parseAttributeBlock();
906 Error parseAttributeGroupBlock();
907 Error parseTypeTable();
908 Error parseTypeTableBody();
909 Error parseOperandBundleTags();
910 Error parseSyncScopeNames();
912 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
913 unsigned NameIndex, Triple &TT);
914 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta, Function *
F,
915 ArrayRef<uint64_t> Record);
917 Error parseGlobalValueSymbolTable();
918 Error parseConstants();
919 Error rememberAndSkipFunctionBodies();
920 Error rememberAndSkipFunctionBody();
922 Error rememberAndSkipMetadata();
924 Error parseFunctionBody(Function *
F);
925 Error globalCleanup();
926 Error resolveGlobalAndIndirectSymbolInits();
927 Error parseUseLists();
928 Error findFunctionInStream(
930 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
937class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
939 ModuleSummaryIndex &TheIndex;
943 bool SeenGlobalValSummary =
false;
946 bool SeenValueSymbolTable =
false;
950 uint64_t VSTOffset = 0;
960 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
961 ValueIdToValueInfoMap;
967 DenseMap<uint64_t, StringRef> ModuleIdMap;
970 std::string SourceFileName;
974 StringRef ModulePath;
982 std::vector<uint64_t> StackIds;
986 std::vector<uint64_t> RadixArray;
991 std::vector<unsigned> StackIdToIndex;
994 ModuleSummaryIndexBitcodeReader(
995 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
996 StringRef ModulePath,
1002 void setValueGUID(uint64_t ValueID, StringRef
ValueName,
1004 StringRef SourceFileName);
1005 Error parseValueSymbolTable(
1007 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1010 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1011 bool HasProfile,
bool HasRelBF);
1012 Error parseEntireSummary(
unsigned ID);
1013 Error parseModuleStringTable();
1014 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1015 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1017 std::vector<FunctionSummary::ParamAccess>
1018 parseParamAccesses(ArrayRef<uint64_t> Record);
1019 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1023 static constexpr unsigned UninitializedStackIdIndex =
1024 std::numeric_limits<unsigned>::max();
1026 unsigned getStackIdIndex(
unsigned LocalIndex) {
1027 unsigned &
Index = StackIdToIndex[LocalIndex];
1030 if (Index == UninitializedStackIdIndex)
1035 template <
bool AllowNullValueInfo = false>
1036 std::pair<ValueInfo, GlobalValue::GUID>
1037 getValueInfoFromValueId(
unsigned ValueId);
1039 void addThisModule();
1055 return std::error_code();
1061 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1062 ValueList(this->Stream.SizeInBytes(),
1064 return materializeValue(
ValID, InsertBB);
1066 this->ProducerIdentification = std::string(ProducerIdentification);
1069Error BitcodeReader::materializeForwardReferencedFunctions() {
1070 if (WillMaterializeAllForwardRefs)
1074 WillMaterializeAllForwardRefs =
true;
1076 while (!BasicBlockFwdRefQueue.empty()) {
1077 Function *
F = BasicBlockFwdRefQueue.front();
1078 BasicBlockFwdRefQueue.pop_front();
1079 assert(
F &&
"Expected valid function");
1080 if (!BasicBlockFwdRefs.
count(
F))
1088 if (!
F->isMaterializable())
1089 return error(
"Never resolved function from blockaddress");
1092 if (
Error Err = materialize(
F))
1095 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1097 for (Function *
F : BackwardRefFunctions)
1098 if (
Error Err = materialize(
F))
1100 BackwardRefFunctions.clear();
1103 WillMaterializeAllForwardRefs =
false;
1168 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1169 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1170 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1171 Flags.NoInline = (RawFlags >> 4) & 0x1;
1172 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1173 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1174 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1175 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1176 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1192 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1);
1193 RawFlags = RawFlags >> 4;
1194 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1198 bool Live = (RawFlags & 0x2) || Version < 3;
1199 bool Local = (RawFlags & 0x4);
1200 bool AutoHide = (RawFlags & 0x8);
1203 Live,
Local, AutoHide, IK,
1204 NoRenameOnPromotion);
1210 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1211 (RawFlags & 0x4) ?
true :
false,
1215static std::pair<CalleeInfo::HotnessType, bool>
1219 bool HasTailCall = (RawFlags & 0x8);
1220 return {Hotness, HasTailCall};
1225 bool &HasTailCall) {
1226 static constexpr unsigned RelBlockFreqBits = 28;
1227 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1228 RelBF = RawFlags & RelBlockFreqMask;
1229 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1254 case 0:
return false;
1255 case 1:
return true;
1317 bool IsFP = Ty->isFPOrFPVectorTy();
1319 if (!IsFP && !Ty->isIntOrIntVectorTy())
1326 return IsFP ? Instruction::FNeg : -1;
1331 bool IsFP = Ty->isFPOrFPVectorTy();
1333 if (!IsFP && !Ty->isIntOrIntVectorTy())
1340 return IsFP ? Instruction::FAdd : Instruction::Add;
1342 return IsFP ? Instruction::FSub : Instruction::Sub;
1344 return IsFP ? Instruction::FMul : Instruction::Mul;
1346 return IsFP ? -1 : Instruction::UDiv;
1348 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1350 return IsFP ? -1 : Instruction::URem;
1352 return IsFP ? Instruction::FRem : Instruction::SRem;
1354 return IsFP ? -1 : Instruction::Shl;
1356 return IsFP ? -1 : Instruction::LShr;
1358 return IsFP ? -1 : Instruction::AShr;
1360 return IsFP ? -1 : Instruction::And;
1362 return IsFP ? -1 : Instruction::Or;
1364 return IsFP ? -1 : Instruction::Xor;
1369 bool &IsElementwise) {
1467Type *BitcodeReader::getTypeByID(
unsigned ID) {
1469 if (
ID >= TypeList.size())
1472 if (
Type *Ty = TypeList[
ID])
1477 return TypeList[
ID] = createIdentifiedStructType(
Context);
1480unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1481 auto It = ContainedTypeIDs.
find(
ID);
1482 if (It == ContainedTypeIDs.
end())
1483 return InvalidTypeID;
1485 if (Idx >= It->second.size())
1486 return InvalidTypeID;
1488 return It->second[Idx];
1491Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1492 if (
ID >= TypeList.size())
1499 return getTypeByID(getContainedTypeID(
ID, 0));
1502unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1503 ArrayRef<unsigned> ChildTypeIDs) {
1504 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1505 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1506 auto It = VirtualTypeIDs.
find(CacheKey);
1507 if (It != VirtualTypeIDs.
end()) {
1513 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1514 "Incorrect cached contained type IDs");
1518 unsigned TypeID = TypeList.size();
1519 TypeList.push_back(Ty);
1520 if (!ChildTypeIDs.
empty())
1541 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1555 if (Opcode == Instruction::GetElementPtr)
1559 case Instruction::FNeg:
1560 case Instruction::Select:
1561 case Instruction::ICmp:
1562 case Instruction::FCmp:
1569Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1570 BasicBlock *InsertBB) {
1572 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1574 return ValueList[StartValID];
1576 SmallDenseMap<unsigned, Value *> MaterializedValues;
1577 SmallVector<unsigned> Worklist;
1579 while (!Worklist.
empty()) {
1580 unsigned ValID = Worklist.
back();
1581 if (MaterializedValues.
count(ValID)) {
1587 if (ValID >= ValueList.
size() || !ValueList[ValID])
1588 return error(
"Invalid value ID");
1590 Value *
V = ValueList[ValID];
1593 MaterializedValues.
insert({ValID,
V});
1601 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1602 auto It = MaterializedValues.
find(OpID);
1603 if (It != MaterializedValues.
end())
1604 Ops.push_back(It->second);
1611 if (
Ops.size() != BC->getOperandIDs().size())
1613 std::reverse(
Ops.begin(),
Ops.end());
1630 switch (BC->Opcode) {
1631 case BitcodeConstant::ConstantPtrAuthOpcode: {
1634 return error(
"ptrauth key operand must be ConstantInt");
1638 return error(
"ptrauth disc operand must be ConstantInt");
1641 ConstOps.
size() > 4 ? ConstOps[4]
1646 "ptrauth deactivation symbol operand must be a pointer");
1649 DeactivationSymbol);
1652 case BitcodeConstant::NoCFIOpcode: {
1655 return error(
"no_cfi operand must be GlobalValue");
1659 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1662 return error(
"dso_local operand must be GlobalValue");
1666 case BitcodeConstant::BlockAddressOpcode: {
1669 return error(
"blockaddress operand must be a function");
1674 unsigned BBID = BC->BlockAddressBB;
1677 return error(
"Invalid ID");
1680 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1682 return error(
"Invalid ID");
1689 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1691 BasicBlockFwdRefQueue.push_back(Fn);
1692 if (FwdBBs.size() < BBID + 1)
1693 FwdBBs.resize(BBID + 1);
1701 case BitcodeConstant::ConstantStructOpcode: {
1703 if (
ST->getNumElements() != ConstOps.
size())
1704 return error(
"Invalid number of elements in struct initializer");
1706 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1707 if (
Op->getType() != Ty)
1708 return error(
"Incorrect type in struct initializer");
1713 case BitcodeConstant::ConstantArrayOpcode: {
1715 if (AT->getNumElements() != ConstOps.
size())
1716 return error(
"Invalid number of elements in array initializer");
1718 for (Constant *
Op : ConstOps)
1719 if (
Op->getType() != AT->getElementType())
1720 return error(
"Incorrect type in array initializer");
1725 case BitcodeConstant::ConstantVectorOpcode: {
1727 if (VT->getNumElements() != ConstOps.size())
1728 return error(
"Invalid number of elements in vector initializer");
1730 for (Constant *
Op : ConstOps)
1731 if (
Op->getType() != VT->getElementType())
1732 return error(
"Incorrect type in vector initializer");
1737 case Instruction::GetElementPtr:
1739 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1742 case Instruction::ExtractElement:
1745 case Instruction::InsertElement:
1749 case Instruction::ShuffleVector: {
1750 SmallVector<int, 16>
Mask;
1762 MaterializedValues.
insert({ValID,
C});
1768 return error(Twine(
"Value referenced by initializer is an unsupported "
1769 "constant expression of type ") +
1770 BC->getOpcodeName());
1776 BC->getType(),
"constexpr", InsertBB);
1779 "constexpr", InsertBB);
1782 Ops[1],
"constexpr", InsertBB);
1785 I->setHasNoSignedWrap();
1787 I->setHasNoUnsignedWrap();
1793 switch (BC->Opcode) {
1794 case BitcodeConstant::ConstantVectorOpcode: {
1795 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1798 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1805 case BitcodeConstant::ConstantStructOpcode:
1806 case BitcodeConstant::ConstantArrayOpcode: {
1810 "constexpr.ins", InsertBB);
1814 case Instruction::ICmp:
1815 case Instruction::FCmp:
1818 "constexpr", InsertBB);
1820 case Instruction::GetElementPtr:
1826 case Instruction::Select:
1829 case Instruction::ExtractElement:
1832 case Instruction::InsertElement:
1836 case Instruction::ShuffleVector:
1837 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1845 MaterializedValues.
insert({ValID,
I});
1849 return MaterializedValues[StartValID];
1852Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1853 Expected<Value *> MaybeV = materializeValue(
ID,
nullptr);
1861StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1864 IdentifiedStructTypes.push_back(Ret);
1868StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1870 IdentifiedStructTypes.push_back(Ret);
1886 case Attribute::ZExt:
return 1 << 0;
1887 case Attribute::SExt:
return 1 << 1;
1888 case Attribute::NoReturn:
return 1 << 2;
1889 case Attribute::InReg:
return 1 << 3;
1890 case Attribute::StructRet:
return 1 << 4;
1891 case Attribute::NoUnwind:
return 1 << 5;
1892 case Attribute::NoAlias:
return 1 << 6;
1893 case Attribute::ByVal:
return 1 << 7;
1894 case Attribute::Nest:
return 1 << 8;
1895 case Attribute::ReadNone:
return 1 << 9;
1896 case Attribute::ReadOnly:
return 1 << 10;
1897 case Attribute::NoInline:
return 1 << 11;
1898 case Attribute::AlwaysInline:
return 1 << 12;
1899 case Attribute::OptimizeForSize:
return 1 << 13;
1900 case Attribute::StackProtect:
return 1 << 14;
1901 case Attribute::StackProtectReq:
return 1 << 15;
1902 case Attribute::Alignment:
return 31 << 16;
1904 case Attribute::NoRedZone:
return 1 << 22;
1905 case Attribute::NoImplicitFloat:
return 1 << 23;
1906 case Attribute::Naked:
return 1 << 24;
1907 case Attribute::InlineHint:
return 1 << 25;
1908 case Attribute::StackAlignment:
return 7 << 26;
1909 case Attribute::ReturnsTwice:
return 1 << 29;
1910 case Attribute::UWTable:
return 1 << 30;
1911 case Attribute::NonLazyBind:
return 1U << 31;
1912 case Attribute::SanitizeAddress:
return 1ULL << 32;
1913 case Attribute::MinSize:
return 1ULL << 33;
1914 case Attribute::NoDuplicate:
return 1ULL << 34;
1915 case Attribute::StackProtectStrong:
return 1ULL << 35;
1916 case Attribute::SanitizeThread:
return 1ULL << 36;
1917 case Attribute::SanitizeMemory:
return 1ULL << 37;
1918 case Attribute::NoBuiltin:
return 1ULL << 38;
1919 case Attribute::Returned:
return 1ULL << 39;
1920 case Attribute::Cold:
return 1ULL << 40;
1921 case Attribute::Builtin:
return 1ULL << 41;
1922 case Attribute::OptimizeNone:
return 1ULL << 42;
1923 case Attribute::InAlloca:
return 1ULL << 43;
1924 case Attribute::NonNull:
return 1ULL << 44;
1925 case Attribute::JumpTable:
return 1ULL << 45;
1926 case Attribute::Convergent:
return 1ULL << 46;
1927 case Attribute::SafeStack:
return 1ULL << 47;
1928 case Attribute::NoRecurse:
return 1ULL << 48;
1931 case Attribute::SwiftSelf:
return 1ULL << 51;
1932 case Attribute::SwiftError:
return 1ULL << 52;
1933 case Attribute::WriteOnly:
return 1ULL << 53;
1934 case Attribute::Speculatable:
return 1ULL << 54;
1935 case Attribute::StrictFP:
return 1ULL << 55;
1936 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1937 case Attribute::NoCfCheck:
return 1ULL << 57;
1938 case Attribute::OptForFuzzing:
return 1ULL << 58;
1939 case Attribute::ShadowCallStack:
return 1ULL << 59;
1940 case Attribute::SpeculativeLoadHardening:
1942 case Attribute::ImmArg:
1944 case Attribute::WillReturn:
1946 case Attribute::NoFree:
1962 if (
I == Attribute::Alignment)
1963 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1964 else if (
I == Attribute::StackAlignment)
1965 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1967 B.addTypeAttr(
I,
nullptr);
1981 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1983 "Alignment must be a power of two.");
1986 B.addAlignmentAttr(Alignment);
1988 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1989 (EncodedAttrs & 0xffff);
1991 if (AttrIdx == AttributeList::FunctionIndex) {
1994 if (Attrs & (1ULL << 9)) {
1996 Attrs &= ~(1ULL << 9);
1999 if (Attrs & (1ULL << 10)) {
2001 Attrs &= ~(1ULL << 10);
2004 if (Attrs & (1ULL << 49)) {
2006 Attrs &= ~(1ULL << 49);
2009 if (Attrs & (1ULL << 50)) {
2011 Attrs &= ~(1ULL << 50);
2014 if (Attrs & (1ULL << 53)) {
2016 Attrs &= ~(1ULL << 53);
2020 B.addMemoryAttr(ME);
2024 if (Attrs & (1ULL << 21)) {
2025 Attrs &= ~(1ULL << 21);
2032Error BitcodeReader::parseAttributeBlock() {
2036 if (!MAttributes.empty())
2037 return error(
"Invalid multiple blocks");
2039 SmallVector<uint64_t, 64>
Record;
2048 BitstreamEntry
Entry = MaybeEntry.
get();
2050 switch (
Entry.Kind) {
2053 return error(
"Malformed block");
2066 switch (MaybeRecord.
get()) {
2072 return error(
"Invalid parameter attribute record");
2074 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2080 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2084 for (uint64_t Val : Record)
2085 Attrs.push_back(MAttributeGroups[Val]);
2087 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2100 return Attribute::Alignment;
2102 return Attribute::AlwaysInline;
2104 return Attribute::Builtin;
2106 return Attribute::ByVal;
2108 return Attribute::InAlloca;
2110 return Attribute::Cold;
2112 return Attribute::Convergent;
2114 return Attribute::DisableSanitizerInstrumentation;
2116 return Attribute::ElementType;
2118 return Attribute::FnRetThunkExtern;
2120 return Attribute::Flatten;
2122 return Attribute::InlineHint;
2124 return Attribute::InReg;
2126 return Attribute::JumpTable;
2128 return Attribute::Memory;
2130 return Attribute::NoFPClass;
2132 return Attribute::MinSize;
2134 return Attribute::Naked;
2136 return Attribute::Nest;
2138 return Attribute::NoAlias;
2140 return Attribute::NoBuiltin;
2142 return Attribute::NoCallback;
2144 return Attribute::NoDivergenceSource;
2146 return Attribute::NoDuplicate;
2148 return Attribute::NoFree;
2150 return Attribute::NoImplicitFloat;
2152 return Attribute::NoInline;
2154 return Attribute::NoRecurse;
2156 return Attribute::NoMerge;
2158 return Attribute::NonLazyBind;
2160 return Attribute::NonNull;
2162 return Attribute::Dereferenceable;
2164 return Attribute::DereferenceableOrNull;
2166 return Attribute::AllocAlign;
2168 return Attribute::AllocKind;
2170 return Attribute::AllocSize;
2172 return Attribute::AllocatedPointer;
2174 return Attribute::NoRedZone;
2176 return Attribute::NoReturn;
2178 return Attribute::NoSync;
2180 return Attribute::NoCfCheck;
2182 return Attribute::NoProfile;
2184 return Attribute::SkipProfile;
2186 return Attribute::NoUnwind;
2188 return Attribute::NoSanitizeBounds;
2190 return Attribute::NoSanitizeCoverage;
2192 return Attribute::NullPointerIsValid;
2194 return Attribute::OptimizeForDebugging;
2196 return Attribute::OptForFuzzing;
2198 return Attribute::OptimizeForSize;
2200 return Attribute::OptimizeNone;
2202 return Attribute::ReadNone;
2204 return Attribute::ReadOnly;
2206 return Attribute::Returned;
2208 return Attribute::ReturnsTwice;
2210 return Attribute::SExt;
2212 return Attribute::Speculatable;
2214 return Attribute::StackAlignment;
2216 return Attribute::StackProtect;
2218 return Attribute::StackProtectReq;
2220 return Attribute::StackProtectStrong;
2222 return Attribute::SafeStack;
2224 return Attribute::ShadowCallStack;
2226 return Attribute::StrictFP;
2228 return Attribute::StructRet;
2230 return Attribute::SanitizeAddress;
2232 return Attribute::SanitizeHWAddress;
2234 return Attribute::SanitizeThread;
2236 return Attribute::SanitizeType;
2238 return Attribute::SanitizeMemory;
2240 return Attribute::SanitizeNumericalStability;
2242 return Attribute::SanitizeRealtime;
2244 return Attribute::SanitizeRealtimeBlocking;
2246 return Attribute::SanitizeAllocToken;
2248 return Attribute::SpeculativeLoadHardening;
2250 return Attribute::SwiftError;
2252 return Attribute::SwiftSelf;
2254 return Attribute::SwiftAsync;
2256 return Attribute::UWTable;
2258 return Attribute::VScaleRange;
2260 return Attribute::WillReturn;
2262 return Attribute::WriteOnly;
2264 return Attribute::ZExt;
2266 return Attribute::ImmArg;
2268 return Attribute::SanitizeMemTag;
2270 return Attribute::Preallocated;
2272 return Attribute::NoUndef;
2274 return Attribute::ByRef;
2276 return Attribute::MustProgress;
2278 return Attribute::Hot;
2280 return Attribute::PresplitCoroutine;
2282 return Attribute::Writable;
2284 return Attribute::CoroDestroyOnlyWhenComplete;
2286 return Attribute::DeadOnUnwind;
2288 return Attribute::Range;
2290 return Attribute::Initializes;
2292 return Attribute::CoroElideSafe;
2294 return Attribute::NoExt;
2296 return Attribute::Captures;
2298 return Attribute::DeadOnReturn;
2300 return Attribute::NoCreateUndefOrPoison;
2302 return Attribute::DenormalFPEnv;
2304 return Attribute::NoOutline;
2309 MaybeAlign &Alignment) {
2312 if (
Exponent > Value::MaxAlignmentExponent + 1)
2313 return error(
"Invalid alignment value");
2318Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2320 if (*Kind == Attribute::None)
2321 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2326 switch (EncodedKind) {
2350Error BitcodeReader::parseAttributeGroupBlock() {
2354 if (!MAttributeGroups.empty())
2355 return error(
"Invalid multiple blocks");
2357 SmallVector<uint64_t, 64>
Record;
2364 BitstreamEntry
Entry = MaybeEntry.
get();
2366 switch (
Entry.Kind) {
2369 return error(
"Malformed block");
2382 switch (MaybeRecord.
get()) {
2387 return error(
"Invalid grp record");
2389 uint64_t GrpID =
Record[0];
2390 uint64_t Idx =
Record[1];
2394 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2395 if (Record[i] == 0) {
2396 Attribute::AttrKind
Kind;
2397 uint64_t EncodedKind =
Record[++i];
2398 if (Idx == AttributeList::FunctionIndex &&
2407 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2413 if (Kind == Attribute::ByVal)
2414 B.addByValAttr(
nullptr);
2415 else if (Kind == Attribute::StructRet)
2416 B.addStructRetAttr(
nullptr);
2417 else if (Kind == Attribute::InAlloca)
2418 B.addInAllocaAttr(
nullptr);
2419 else if (Kind == Attribute::UWTable)
2420 B.addUWTableAttr(UWTableKind::Default);
2421 else if (Kind == Attribute::DeadOnReturn)
2422 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2423 else if (Attribute::isEnumAttrKind(Kind))
2424 B.addAttribute(Kind);
2426 return error(
"Not an enum attribute");
2427 }
else if (Record[i] == 1) {
2428 Attribute::AttrKind
Kind;
2429 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2431 if (!Attribute::isIntAttrKind(Kind))
2432 return error(
"Not an int attribute");
2433 if (Kind == Attribute::Alignment)
2434 B.addAlignmentAttr(Record[++i]);
2435 else if (Kind == Attribute::StackAlignment)
2436 B.addStackAlignmentAttr(Record[++i]);
2437 else if (Kind == Attribute::Dereferenceable)
2438 B.addDereferenceableAttr(Record[++i]);
2439 else if (Kind == Attribute::DereferenceableOrNull)
2440 B.addDereferenceableOrNullAttr(Record[++i]);
2441 else if (Kind == Attribute::DeadOnReturn)
2442 B.addDeadOnReturnAttr(
2444 else if (Kind == Attribute::AllocSize)
2445 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2446 else if (Kind == Attribute::VScaleRange)
2447 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2448 else if (Kind == Attribute::UWTable)
2450 else if (Kind == Attribute::AllocKind)
2451 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2452 else if (Kind == Attribute::Memory) {
2453 uint64_t EncodedME =
Record[++i];
2454 const uint8_t
Version = (EncodedME >> 56);
2466 B.addMemoryAttr(ME);
2471 EncodedME & 0x00FFFFFFFFFFFFFFULL));
2473 }
else if (Kind == Attribute::Captures)
2475 else if (Kind == Attribute::NoFPClass)
2478 else if (Kind == Attribute::DenormalFPEnv) {
2479 B.addDenormalFPEnvAttr(
2482 }
else if (Record[i] == 3 || Record[i] == 4) {
2484 SmallString<64> KindStr;
2485 SmallString<64> ValStr;
2487 while (Record[i] != 0 && i != e)
2489 assert(Record[i] == 0 &&
"Kind string not null terminated");
2494 while (Record[i] != 0 && i != e)
2496 assert(Record[i] == 0 &&
"Value string not null terminated");
2499 B.addAttribute(KindStr.
str(), ValStr.
str());
2500 }
else if (Record[i] == 5 || Record[i] == 6) {
2501 bool HasType =
Record[i] == 6;
2502 Attribute::AttrKind
Kind;
2503 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2505 if (!Attribute::isTypeAttrKind(Kind))
2506 return error(
"Not a type attribute");
2508 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2509 }
else if (Record[i] == 7) {
2510 Attribute::AttrKind
Kind;
2513 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2515 if (!Attribute::isConstantRangeAttrKind(Kind))
2516 return error(
"Not a ConstantRange attribute");
2518 Expected<ConstantRange> MaybeCR =
2519 readBitWidthAndConstantRange(Record, i);
2524 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2525 }
else if (Record[i] == 8) {
2526 Attribute::AttrKind
Kind;
2529 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2531 if (!Attribute::isConstantRangeListAttrKind(Kind))
2532 return error(
"Not a constant range list attribute");
2536 return error(
"Too few records for constant range list");
2537 unsigned RangeSize =
Record[i++];
2539 for (
unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2540 Expected<ConstantRange> MaybeCR =
2541 readConstantRange(Record, i,
BitWidth);
2549 return error(
"Invalid (unordered or overlapping) range list");
2550 B.addConstantRangeListAttr(Kind, Val);
2552 return error(
"Invalid attribute group entry");
2557 B.addMemoryAttr(ME);
2560 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2567Error BitcodeReader::parseTypeTable() {
2571 return parseTypeTableBody();
2574Error BitcodeReader::parseTypeTableBody() {
2575 if (!TypeList.empty())
2576 return error(
"Invalid multiple blocks");
2578 SmallVector<uint64_t, 64>
Record;
2579 unsigned NumRecords = 0;
2588 BitstreamEntry
Entry = MaybeEntry.
get();
2590 switch (
Entry.Kind) {
2593 return error(
"Malformed block");
2595 if (NumRecords != TypeList.size())
2596 return error(
"Malformed block");
2605 Type *ResultTy =
nullptr;
2606 SmallVector<unsigned> ContainedIDs;
2610 switch (MaybeRecord.
get()) {
2612 return error(
"Invalid value");
2617 return error(
"Invalid numentry record");
2618 TypeList.resize(Record[0]);
2621 ResultTy = Type::getVoidTy(
Context);
2624 ResultTy = Type::getHalfTy(
Context);
2627 ResultTy = Type::getBFloatTy(
Context);
2630 ResultTy = Type::getFloatTy(
Context);
2633 ResultTy = Type::getDoubleTy(
Context);
2636 ResultTy = Type::getX86_FP80Ty(
Context);
2639 ResultTy = Type::getFP128Ty(
Context);
2642 ResultTy = Type::getPPC_FP128Ty(
Context);
2645 ResultTy = Type::getLabelTy(
Context);
2648 ResultTy = Type::getMetadataTy(
Context);
2656 ResultTy = Type::getX86_AMXTy(
Context);
2659 ResultTy = Type::getTokenTy(
Context);
2663 return error(
"Invalid record");
2665 uint64_t NumBits =
Record[0];
2668 return error(
"Bitwidth for byte type out of range");
2674 return error(
"Invalid integer record");
2676 uint64_t NumBits =
Record[0];
2679 return error(
"Bitwidth for integer type out of range");
2686 return error(
"Invalid pointer record");
2690 ResultTy = getTypeByID(Record[0]);
2692 !PointerType::isValidElementType(ResultTy))
2693 return error(
"Invalid type");
2700 return error(
"Invalid opaque pointer record");
2709 return error(
"Invalid function record");
2711 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2712 if (
Type *
T = getTypeByID(Record[i]))
2718 ResultTy = getTypeByID(Record[2]);
2719 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2720 return error(
"Invalid type");
2723 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2729 return error(
"Invalid function record");
2731 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2732 if (
Type *
T = getTypeByID(Record[i])) {
2733 if (!FunctionType::isValidArgumentType(
T))
2734 return error(
"Invalid function argument type");
2741 ResultTy = getTypeByID(Record[1]);
2742 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2743 return error(
"Invalid type");
2746 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2751 return error(
"Invalid anon struct record");
2753 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2754 if (
Type *
T = getTypeByID(Record[i]))
2760 return error(
"Invalid type");
2767 return error(
"Invalid struct name record");
2772 return error(
"Invalid named struct record");
2774 if (NumRecords >= TypeList.size())
2775 return error(
"Invalid TYPE table");
2781 TypeList[NumRecords] =
nullptr;
2783 Res = createIdentifiedStructType(
Context, TypeName);
2787 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2788 if (
Type *
T = getTypeByID(Record[i]))
2794 return error(
"Invalid named struct record");
2803 return error(
"Invalid opaque type record");
2805 if (NumRecords >= TypeList.size())
2806 return error(
"Invalid TYPE table");
2812 TypeList[NumRecords] =
nullptr;
2814 Res = createIdentifiedStructType(
Context, TypeName);
2821 return error(
"Invalid target extension type record");
2823 if (NumRecords >= TypeList.size())
2824 return error(
"Invalid TYPE table");
2826 if (Record[0] >=
Record.size())
2827 return error(
"Too many type parameters");
2829 unsigned NumTys =
Record[0];
2831 SmallVector<unsigned, 8> IntParams;
2832 for (
unsigned i = 0; i < NumTys; i++) {
2833 if (
Type *
T = getTypeByID(Record[i + 1]))
2836 return error(
"Invalid type");
2839 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2840 if (Record[i] > UINT_MAX)
2841 return error(
"Integer parameter too large");
2846 if (
auto E = TTy.takeError())
2854 return error(
"Invalid array type record");
2855 ResultTy = getTypeByID(Record[1]);
2856 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2857 return error(
"Invalid type");
2859 ResultTy = ArrayType::get(ResultTy, Record[0]);
2864 return error(
"Invalid vector type record");
2866 return error(
"Invalid vector length");
2867 ResultTy = getTypeByID(Record[1]);
2868 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2869 return error(
"Invalid type");
2872 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2876 if (NumRecords >= TypeList.size())
2877 return error(
"Invalid TYPE table");
2878 if (TypeList[NumRecords])
2880 "Invalid TYPE table: Only named structs can be forward referenced");
2881 assert(ResultTy &&
"Didn't read a type?");
2882 TypeList[NumRecords] = ResultTy;
2883 if (!ContainedIDs.
empty())
2884 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2889Error BitcodeReader::parseOperandBundleTags() {
2893 if (!BundleTags.empty())
2894 return error(
"Invalid multiple blocks");
2896 SmallVector<uint64_t, 64>
Record;
2902 BitstreamEntry
Entry = MaybeEntry.
get();
2904 switch (
Entry.Kind) {
2907 return error(
"Malformed block");
2921 return error(
"Invalid operand bundle record");
2924 BundleTags.emplace_back();
2926 return error(
"Invalid operand bundle record");
2931Error BitcodeReader::parseSyncScopeNames() {
2936 return error(
"Invalid multiple synchronization scope names blocks");
2938 SmallVector<uint64_t, 64>
Record;
2943 BitstreamEntry
Entry = MaybeEntry.
get();
2945 switch (
Entry.Kind) {
2948 return error(
"Malformed block");
2951 return error(
"Invalid empty synchronization scope names block");
2965 return error(
"Invalid sync scope record");
2967 SmallString<16> SSN;
2969 return error(
"Invalid sync scope record");
2977Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2978 unsigned NameIndex, Triple &TT) {
2981 return error(
"Invalid record");
2982 unsigned ValueID =
Record[0];
2983 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
2984 return error(
"Invalid record");
2985 Value *
V = ValueList[ValueID];
2988 if (NameStr.contains(0))
2989 return error(
"Invalid value name");
2990 V->setName(NameStr);
2992 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
3005 return std::move(JumpFailed);
3011 return error(
"Expected value symbol table subblock");
3015void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
3017 ArrayRef<uint64_t> Record) {
3021 uint64_t FuncWordOffset =
Record[1] - 1;
3022 uint64_t FuncBitOffset = FuncWordOffset * 32;
3023 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3027 if (FuncBitOffset > LastFunctionBlockBit)
3028 LastFunctionBlockBit = FuncBitOffset;
3032Error BitcodeReader::parseGlobalValueSymbolTable() {
3033 unsigned FuncBitcodeOffsetDelta =
3039 SmallVector<uint64_t, 64>
Record;
3044 BitstreamEntry
Entry = MaybeEntry.
get();
3046 switch (
Entry.Kind) {
3049 return error(
"Malformed block");
3060 switch (MaybeRecord.
get()) {
3062 unsigned ValueID =
Record[0];
3063 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3064 return error(
"Invalid value reference in symbol table");
3065 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3075Error BitcodeReader::parseValueSymbolTable(uint64_t
Offset) {
3076 uint64_t CurrentBit;
3082 if (!MaybeCurrentBit)
3084 CurrentBit = MaybeCurrentBit.
get();
3087 if (
Error Err = parseGlobalValueSymbolTable())
3108 unsigned FuncBitcodeOffsetDelta =
3114 SmallVector<uint64_t, 64>
Record;
3125 BitstreamEntry
Entry = MaybeEntry.
get();
3127 switch (
Entry.Kind) {
3130 return error(
"Malformed block");
3146 switch (MaybeRecord.
get()) {
3150 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3158 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3166 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3171 return error(
"Invalid bbentry record");
3174 return error(
"Invalid bbentry record");
3186uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3196Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3197 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3198 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3199 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3201 GlobalInitWorklist.swap(GlobalInits);
3202 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3203 FunctionOperandWorklist.swap(FunctionOperands);
3205 while (!GlobalInitWorklist.empty()) {
3206 unsigned ValID = GlobalInitWorklist.back().second;
3207 if (ValID >= ValueList.
size()) {
3209 GlobalInits.push_back(GlobalInitWorklist.back());
3211 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3214 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3216 GlobalInitWorklist.pop_back();
3219 while (!IndirectSymbolInitWorklist.empty()) {
3220 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3221 if (ValID >= ValueList.
size()) {
3222 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3224 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3228 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3231 return error(
"Alias and aliasee types don't match");
3236 return error(
"Expected an alias or an ifunc");
3239 IndirectSymbolInitWorklist.pop_back();
3242 while (!FunctionOperandWorklist.empty()) {
3243 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3244 if (
Info.PersonalityFn) {
3245 unsigned ValID =
Info.PersonalityFn - 1;
3246 if (ValID < ValueList.
size()) {
3247 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3250 Info.F->setPersonalityFn(MaybeC.
get());
3251 Info.PersonalityFn = 0;
3255 unsigned ValID =
Info.Prefix - 1;
3256 if (ValID < ValueList.
size()) {
3257 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3260 Info.F->setPrefixData(MaybeC.
get());
3264 if (
Info.Prologue) {
3265 unsigned ValID =
Info.Prologue - 1;
3266 if (ValID < ValueList.
size()) {
3267 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3270 Info.F->setPrologueData(MaybeC.
get());
3274 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3275 FunctionOperands.push_back(Info);
3276 FunctionOperandWorklist.pop_back();
3285 BitcodeReader::decodeSignRotatedValue);
3287 return APInt(TypeBits, Words);
3290Error BitcodeReader::parseConstants() {
3298 unsigned Int32TyID = getVirtualTypeID(CurTy);
3299 unsigned CurTyID = Int32TyID;
3300 Type *CurElemTy =
nullptr;
3301 unsigned NextCstNo = ValueList.
size();
3309 switch (Entry.Kind) {
3312 return error(
"Malformed block");
3314 if (NextCstNo != ValueList.
size())
3315 return error(
"Invalid constant reference");
3326 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
3329 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3339 return error(
"Invalid settype record");
3340 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3341 return error(
"Invalid settype record");
3342 if (TypeList[Record[0]] == VoidType)
3343 return error(
"Invalid constant type");
3345 CurTy = TypeList[CurTyID];
3346 CurElemTy = getPtrElementTypeByID(CurTyID);
3350 return error(
"Invalid type for a constant null value");
3353 return error(
"Invalid type for a constant null value");
3358 return error(
"Invalid integer const record");
3363 return error(
"Invalid wide integer const record");
3366 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3367 V = ConstantInt::get(CurTy, VInt);
3372 return error(
"Invalid byte const record");
3373 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]));
3377 return error(
"Invalid wide byte const record");
3380 APInt VByte =
readWideAPInt(Record, ScalarTy->getBitWidth());
3381 V = ConstantByte::get(CurTy, VByte);
3386 return error(
"Invalid float const record");
3389 if (ScalarTy->isHalfTy())
3390 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3391 APInt(16, (uint16_t)Record[0])));
3392 else if (ScalarTy->isBFloatTy())
3393 V = ConstantFP::get(
3394 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3395 else if (ScalarTy->isFloatTy())
3396 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3397 APInt(32, (uint32_t)Record[0])));
3398 else if (ScalarTy->isDoubleTy())
3399 V = ConstantFP::get(
3400 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3401 else if (ScalarTy->isX86_FP80Ty()) {
3403 uint64_t Rearrange[2];
3404 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3405 Rearrange[1] =
Record[0] >> 48;
3406 V = ConstantFP::get(
3407 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3408 }
else if (ScalarTy->isFP128Ty())
3409 V = ConstantFP::get(CurTy,
3410 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3411 else if (ScalarTy->isPPC_FP128Ty())
3412 V = ConstantFP::get(
3413 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3421 return error(
"Invalid aggregate record");
3423 SmallVector<unsigned, 16> Elts;
3427 V = BitcodeConstant::create(
3428 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3430 V = BitcodeConstant::create(
Alloc, CurTy,
3431 BitcodeConstant::ConstantArrayOpcode, Elts);
3433 V = BitcodeConstant::create(
3434 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3443 return error(
"Invalid string record");
3453 return error(
"Invalid data record");
3457 return error(
"Invalid type for value");
3460 SmallString<128> RawData;
3462 for (uint64_t Val : Record) {
3463 const char *Src =
reinterpret_cast<const char *
>(&Val);
3465 Src +=
sizeof(uint64_t) - EltBytes;
3466 RawData.
append(Src, Src + EltBytes);
3471 : ConstantDataArray::getRaw(RawData.str(),
Record.
size(), EltTy);
3476 return error(
"Invalid unary op constexpr record");
3481 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3487 return error(
"Invalid binary op constexpr record");
3493 if (
Record.size() >= 4) {
3494 if (
Opc == Instruction::Add ||
3495 Opc == Instruction::Sub ||
3496 Opc == Instruction::Mul ||
3497 Opc == Instruction::Shl) {
3502 }
else if (
Opc == Instruction::SDiv ||
3503 Opc == Instruction::UDiv ||
3504 Opc == Instruction::LShr ||
3505 Opc == Instruction::AShr) {
3510 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3511 {(unsigned)Record[1], (
unsigned)
Record[2]});
3517 return error(
"Invalid cast constexpr record");
3522 unsigned OpTyID =
Record[1];
3523 Type *OpTy = getTypeByID(OpTyID);
3525 return error(
"Invalid cast constexpr record");
3526 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3538 return error(
"Constant GEP record must have at least two elements");
3540 Type *PointeeType =
nullptr;
3544 PointeeType = getTypeByID(Record[OpNum++]);
3547 std::optional<ConstantRange>
InRange;
3551 unsigned InRangeIndex =
Op >> 1;
3557 Expected<ConstantRange> MaybeInRange =
3558 readBitWidthAndConstantRange(Record, OpNum);
3567 SmallVector<unsigned, 16> Elts;
3568 unsigned BaseTypeID =
Record[OpNum];
3569 while (OpNum !=
Record.size()) {
3570 unsigned ElTyID =
Record[OpNum++];
3571 Type *ElTy = getTypeByID(ElTyID);
3573 return error(
"Invalid getelementptr constexpr record");
3577 if (Elts.
size() < 1)
3578 return error(
"Invalid gep with no operands");
3582 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3583 BaseType = getTypeByID(BaseTypeID);
3588 return error(
"GEP base operand must be pointer or vector of pointer");
3591 PointeeType = getPtrElementTypeByID(BaseTypeID);
3593 return error(
"Missing element type for old-style constant GEP");
3596 V = BitcodeConstant::create(
3598 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3604 return error(
"Invalid select constexpr record");
3606 V = BitcodeConstant::create(
3607 Alloc, CurTy, Instruction::Select,
3608 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3614 return error(
"Invalid extractelement constexpr record");
3615 unsigned OpTyID =
Record[0];
3619 return error(
"Invalid extractelement constexpr record");
3621 if (
Record.size() == 4) {
3622 unsigned IdxTyID =
Record[2];
3623 Type *IdxTy = getTypeByID(IdxTyID);
3625 return error(
"Invalid extractelement constexpr record");
3631 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3632 {(unsigned)Record[1], IdxRecord});
3638 if (
Record.size() < 3 || !OpTy)
3639 return error(
"Invalid insertelement constexpr record");
3641 if (
Record.size() == 4) {
3642 unsigned IdxTyID =
Record[2];
3643 Type *IdxTy = getTypeByID(IdxTyID);
3645 return error(
"Invalid insertelement constexpr record");
3651 V = BitcodeConstant::create(
3652 Alloc, CurTy, Instruction::InsertElement,
3653 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3658 if (
Record.size() < 3 || !OpTy)
3659 return error(
"Invalid shufflevector constexpr record");
3660 V = BitcodeConstant::create(
3661 Alloc, CurTy, Instruction::ShuffleVector,
3662 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3669 if (
Record.size() < 4 || !RTy || !OpTy)
3670 return error(
"Invalid shufflevector constexpr record");
3671 V = BitcodeConstant::create(
3672 Alloc, CurTy, Instruction::ShuffleVector,
3673 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3678 return error(
"Invalid cmp constexpt record");
3679 unsigned OpTyID =
Record[0];
3680 Type *OpTy = getTypeByID(OpTyID);
3682 return error(
"Invalid cmp constexpr record");
3683 V = BitcodeConstant::create(
3686 : Instruction::ICmp),
3687 (uint8_t)Record[3]},
3688 {(unsigned)Record[1], (
unsigned)
Record[2]});
3695 return error(
"Invalid inlineasm record");
3696 std::string AsmStr, ConstrStr;
3697 bool HasSideEffects =
Record[0] & 1;
3698 bool IsAlignStack =
Record[0] >> 1;
3699 unsigned AsmStrSize =
Record[1];
3700 if (2+AsmStrSize >=
Record.size())
3701 return error(
"Invalid inlineasm record");
3702 unsigned ConstStrSize =
Record[2+AsmStrSize];
3703 if (3+AsmStrSize+ConstStrSize >
Record.size())
3704 return error(
"Invalid inlineasm record");
3706 for (
unsigned i = 0; i != AsmStrSize; ++i)
3707 AsmStr += (
char)
Record[2+i];
3708 for (
unsigned i = 0; i != ConstStrSize; ++i)
3709 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3712 return error(
"Missing element type for old-style inlineasm");
3714 HasSideEffects, IsAlignStack);
3721 return error(
"Invalid inlineasm record");
3722 std::string AsmStr, ConstrStr;
3723 bool HasSideEffects =
Record[0] & 1;
3724 bool IsAlignStack = (
Record[0] >> 1) & 1;
3725 unsigned AsmDialect =
Record[0] >> 2;
3726 unsigned AsmStrSize =
Record[1];
3727 if (2+AsmStrSize >=
Record.size())
3728 return error(
"Invalid inlineasm record");
3729 unsigned ConstStrSize =
Record[2+AsmStrSize];
3730 if (3+AsmStrSize+ConstStrSize >
Record.size())
3731 return error(
"Invalid inlineasm record");
3733 for (
unsigned i = 0; i != AsmStrSize; ++i)
3734 AsmStr += (
char)
Record[2+i];
3735 for (
unsigned i = 0; i != ConstStrSize; ++i)
3736 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3739 return error(
"Missing element type for old-style inlineasm");
3741 HasSideEffects, IsAlignStack,
3748 return error(
"Invalid inlineasm record");
3750 std::string AsmStr, ConstrStr;
3751 bool HasSideEffects =
Record[OpNum] & 1;
3752 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3753 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3754 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3756 unsigned AsmStrSize =
Record[OpNum];
3758 if (OpNum + AsmStrSize >=
Record.size())
3759 return error(
"Invalid inlineasm record");
3760 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3761 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3762 return error(
"Invalid inlineasm record");
3764 for (
unsigned i = 0; i != AsmStrSize; ++i)
3765 AsmStr += (
char)
Record[OpNum + i];
3767 for (
unsigned i = 0; i != ConstStrSize; ++i)
3768 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3771 return error(
"Missing element type for old-style inlineasm");
3773 HasSideEffects, IsAlignStack,
3780 return error(
"Invalid inlineasm record");
3785 return error(
"Invalid inlineasm record");
3786 std::string AsmStr, ConstrStr;
3787 bool HasSideEffects =
Record[OpNum] & 1;
3788 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3789 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3790 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3792 unsigned AsmStrSize =
Record[OpNum];
3794 if (OpNum + AsmStrSize >=
Record.size())
3795 return error(
"Invalid inlineasm record");
3796 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3797 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3798 return error(
"Invalid inlineasm record");
3800 for (
unsigned i = 0; i != AsmStrSize; ++i)
3801 AsmStr += (
char)
Record[OpNum + i];
3803 for (
unsigned i = 0; i != ConstStrSize; ++i)
3804 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3806 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3812 return error(
"Invalid blockaddress record");
3813 unsigned FnTyID =
Record[0];
3814 Type *FnTy = getTypeByID(FnTyID);
3816 return error(
"Invalid blockaddress record");
3817 V = BitcodeConstant::create(
3819 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3825 return error(
"Invalid dso_local record");
3826 unsigned GVTyID =
Record[0];
3827 Type *GVTy = getTypeByID(GVTyID);
3829 return error(
"Invalid dso_local record");
3830 V = BitcodeConstant::create(
3831 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3836 return error(
"Invalid no_cfi record");
3837 unsigned GVTyID =
Record[0];
3838 Type *GVTy = getTypeByID(GVTyID);
3840 return error(
"Invalid no_cfi record");
3841 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3847 return error(
"Invalid ptrauth record");
3849 V = BitcodeConstant::create(
Alloc, CurTy,
3850 BitcodeConstant::ConstantPtrAuthOpcode,
3851 {(unsigned)Record[0], (
unsigned)
Record[1],
3852 (unsigned)Record[2], (
unsigned)
Record[3]});
3857 return error(
"Invalid ptrauth record");
3859 V = BitcodeConstant::create(
3860 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3861 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3862 (
unsigned)
Record[3], (unsigned)Record[4]});
3867 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3874Error BitcodeReader::parseUseLists() {
3879 SmallVector<uint64_t, 64>
Record;
3885 BitstreamEntry
Entry = MaybeEntry.
get();
3887 switch (
Entry.Kind) {
3890 return error(
"Malformed block");
3904 switch (MaybeRecord.
get()) {
3912 if (RecordLength < 3)
3914 return error(
"Invalid uselist record");
3915 unsigned ID =
Record.pop_back_val();
3919 assert(
ID < FunctionBBs.size() &&
"Basic block not found");
3920 V = FunctionBBs[
ID];
3924 if (!
V->hasUseList())
3927 unsigned NumUses = 0;
3928 SmallDenseMap<const Use *, unsigned, 16> Order;
3929 for (
const Use &U :
V->materialized_uses()) {
3930 if (++NumUses >
Record.size())
3932 Order[&
U] =
Record[NumUses - 1];
3939 V->sortUseList([&](
const Use &L,
const Use &R) {
3950Error BitcodeReader::rememberAndSkipMetadata() {
3953 DeferredMetadataInfo.push_back(CurBit);
3961Error BitcodeReader::materializeMetadata() {
3962 for (uint64_t BitPos : DeferredMetadataInfo) {
3966 if (
Error Err = MDLoader->parseModuleMetadata())
3975 NamedMDNode *LinkerOpts =
3977 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
3982 DeferredMetadataInfo.clear();
3986void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
3990Error BitcodeReader::rememberAndSkipFunctionBody() {
3992 if (FunctionsWithBodies.empty())
3993 return error(
"Insufficient function protos");
3995 Function *Fn = FunctionsWithBodies.back();
3996 FunctionsWithBodies.pop_back();
4001 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4002 "Mismatch between VST and scanned function offsets");
4003 DeferredFunctionInfo[Fn] = CurBit;
4011Error BitcodeReader::globalCleanup() {
4013 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4015 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4016 return error(
"Malformed global initializer set");
4020 for (Function &
F : *TheModule) {
4021 MDLoader->upgradeDebugIntrinsics(
F);
4024 UpgradedIntrinsics[&
F] = NewFn;
4030 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4031 for (GlobalVariable &GV : TheModule->globals())
4033 UpgradedVariables.emplace_back(&GV, Upgraded);
4034 for (
auto &Pair : UpgradedVariables) {
4035 Pair.first->eraseFromParent();
4036 TheModule->insertGlobalVariable(Pair.second);
4041 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4042 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4050Error BitcodeReader::rememberAndSkipFunctionBodies() {
4055 return error(
"Could not find function in stream");
4057 if (!SeenFirstFunctionBody)
4058 return error(
"Trying to materialize functions before seeing function blocks");
4062 assert(SeenValueSymbolTable);
4065 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4068 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4070 switch (
Entry.Kind) {
4072 return error(
"Expect SubBlock");
4076 return error(
"Expect function block");
4078 if (
Error Err = rememberAndSkipFunctionBody())
4087Error BitcodeReaderBase::readBlockInfo() {
4088 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4090 if (!MaybeNewBlockInfo)
4092 std::optional<BitstreamBlockInfo> NewBlockInfo =
4093 std::move(MaybeNewBlockInfo.
get());
4095 return error(
"Malformed block");
4096 BlockInfo = std::move(*NewBlockInfo);
4100Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4104 std::tie(Name, Record) = readNameFromStrtab(Record);
4107 return error(
"Invalid comdat record");
4109 std::string OldFormatName;
4112 return error(
"Invalid comdat record");
4113 unsigned ComdatNameSize =
Record[1];
4114 if (ComdatNameSize >
Record.size() - 2)
4115 return error(
"Comdat name size too large");
4116 OldFormatName.reserve(ComdatNameSize);
4117 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4118 OldFormatName += (
char)
Record[2 + i];
4119 Name = OldFormatName;
4121 Comdat *
C = TheModule->getOrInsertComdat(Name);
4122 C->setSelectionKind(SK);
4123 ComdatList.push_back(
C);
4137 Meta.NoAddress =
true;
4139 Meta.NoHWAddress =
true;
4143 Meta.IsDynInit =
true;
4147Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4155 std::tie(Name, Record) = readNameFromStrtab(Record);
4158 return error(
"Invalid global variable record");
4159 unsigned TyID =
Record[0];
4160 Type *Ty = getTypeByID(TyID);
4162 return error(
"Invalid global variable record");
4164 bool explicitType =
Record[1] & 2;
4170 return error(
"Invalid type for value");
4172 TyID = getContainedTypeID(TyID);
4173 Ty = getTypeByID(TyID);
4175 return error(
"Missing element type for old-style global");
4178 uint64_t RawLinkage =
Record[3];
4180 MaybeAlign Alignment;
4181 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4185 if (Record[5] - 1 >= SectionTable.size())
4186 return error(
"Invalid ID");
4195 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4203 bool ExternallyInitialized =
false;
4205 ExternallyInitialized =
Record[9];
4207 GlobalVariable *NewGV =
4217 if (
Record.size() > 10) {
4229 if (
unsigned InitID = Record[2])
4230 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4232 if (
Record.size() > 11) {
4233 if (
unsigned ComdatID = Record[11]) {
4234 if (ComdatID > ComdatList.size())
4235 return error(
"Invalid global variable comdat ID");
4236 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4239 ImplicitComdatObjects.
insert(NewGV);
4242 if (
Record.size() > 12) {
4247 if (
Record.size() > 13) {
4256 if (
Record.size() > 16 && Record[16]) {
4257 llvm::GlobalValue::SanitizerMetadata
Meta =
4262 if (
Record.size() > 17 && Record[17]) {
4266 return error(
"Invalid global variable code model");
4272void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4273 if (ValueTypeCallback) {
4274 (*ValueTypeCallback)(
4275 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4276 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4280Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4286 std::tie(Name, Record) = readNameFromStrtab(Record);
4289 return error(
"Invalid function record");
4290 unsigned FTyID =
Record[0];
4291 Type *FTy = getTypeByID(FTyID);
4293 return error(
"Invalid function record");
4295 FTyID = getContainedTypeID(FTyID, 0);
4296 FTy = getTypeByID(FTyID);
4298 return error(
"Missing element type for old-style function");
4302 return error(
"Invalid type for value");
4303 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4304 if (CC & ~CallingConv::MaxID)
4305 return error(
"Invalid calling convention ID");
4307 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4313 AddrSpace, Name, TheModule);
4316 "Incorrect fully specified type provided for function");
4317 FunctionTypeIDs[
Func] = FTyID;
4319 Func->setCallingConv(CC);
4320 bool isProto =
Record[2];
4321 uint64_t RawLinkage =
Record[3];
4324 callValueTypeCallback(Func, FTyID);
4329 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4330 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4331 Attribute::InAlloca}) {
4332 if (!
Func->hasParamAttribute(i, Kind))
4335 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4338 Func->removeParamAttr(i, Kind);
4340 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4341 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4343 return error(
"Missing param element type for attribute upgrade");
4347 case Attribute::ByVal:
4348 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4350 case Attribute::StructRet:
4351 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4353 case Attribute::InAlloca:
4354 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4360 Func->addParamAttr(i, NewAttr);
4364 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4365 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4366 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4367 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4369 return error(
"Missing param element type for x86_intrcc upgrade");
4371 Func->addParamAttr(0, NewAttr);
4374 MaybeAlign Alignment;
4375 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4378 Func->setAlignment(*Alignment);
4380 if (Record[6] - 1 >= SectionTable.size())
4381 return error(
"Invalid ID");
4382 Func->setSection(SectionTable[Record[6] - 1]);
4386 if (!
Func->hasLocalLinkage())
4388 if (
Record.size() > 8 && Record[8]) {
4389 if (Record[8] - 1 >= GCTable.size())
4390 return error(
"Invalid ID");
4391 Func->setGC(GCTable[Record[8] - 1]);
4396 Func->setUnnamedAddr(UnnamedAddr);
4398 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4400 OperandInfo.Prologue =
Record[10];
4402 if (
Record.size() > 11) {
4404 if (!
Func->hasLocalLinkage()) {
4411 if (
Record.size() > 12) {
4412 if (
unsigned ComdatID = Record[12]) {
4413 if (ComdatID > ComdatList.size())
4414 return error(
"Invalid function comdat ID");
4415 Func->setComdat(ComdatList[ComdatID - 1]);
4418 ImplicitComdatObjects.
insert(Func);
4422 OperandInfo.Prefix =
Record[13];
4425 OperandInfo.PersonalityFn =
Record[14];
4427 if (
Record.size() > 15) {
4437 Record[17] + Record[18] <= Strtab.
size()) {
4438 Func->setPartition(StringRef(Strtab.
data() + Record[17], Record[18]));
4441 if (
Record.size() > 19) {
4442 MaybeAlign PrefAlignment;
4443 if (
Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4445 Func->setPreferredAlignment(PrefAlignment);
4448 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4450 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4451 FunctionOperands.push_back(OperandInfo);
4456 Func->setIsMaterializable(
true);
4457 FunctionsWithBodies.push_back(Func);
4458 DeferredFunctionInfo[
Func] = 0;
4463Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4464 unsigned BitCode, ArrayRef<uint64_t> Record) {
4474 std::tie(Name, Record) = readNameFromStrtab(Record);
4477 if (
Record.size() < (3 + (
unsigned)NewRecord))
4478 return error(
"Invalid global indirect symbol record");
4483 return error(
"Invalid global indirect symbol record");
4489 return error(
"Invalid type for value");
4490 AddrSpace = PTy->getAddressSpace();
4492 Ty = getTypeByID(
TypeID);
4494 return error(
"Missing element type for old-style indirect symbol");
4496 AddrSpace =
Record[OpNum++];
4499 auto Val =
Record[OpNum++];
4508 nullptr, TheModule);
4512 if (OpNum !=
Record.size()) {
4513 auto VisInd = OpNum++;
4519 if (OpNum !=
Record.size()) {
4520 auto S =
Record[OpNum++];
4527 if (OpNum !=
Record.size())
4529 if (OpNum !=
Record.size())
4532 if (OpNum !=
Record.size())
4537 if (OpNum + 1 <
Record.size()) {
4539 if (Record[OpNum] + Record[OpNum + 1] > Strtab.
size())
4540 return error(
"Malformed partition, too large.");
4542 StringRef(Strtab.
data() + Record[OpNum], Record[OpNum + 1]));
4546 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4550Error BitcodeReader::parseModule(uint64_t ResumeBit,
4551 bool ShouldLazyLoadMetadata,
4552 ParserCallbacks Callbacks) {
4553 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4560 SmallVector<uint64_t, 64>
Record;
4564 bool ResolvedDataLayout =
false;
4569 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4571 auto ResolveDataLayout = [&]() ->
Error {
4572 if (ResolvedDataLayout)
4576 ResolvedDataLayout =
true;
4580 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4584 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4585 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4586 TentativeDataLayoutStr = *LayoutOverride;
4594 TheModule->setDataLayout(MaybeDL.
get());
4600 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4603 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4605 switch (
Entry.Kind) {
4607 return error(
"Malformed block");
4609 if (
Error Err = ResolveDataLayout())
4611 return globalCleanup();
4620 if (
Error Err = readBlockInfo())
4624 if (
Error Err = parseAttributeBlock())
4628 if (
Error Err = parseAttributeGroupBlock())
4632 if (
Error Err = parseTypeTable())
4636 if (!SeenValueSymbolTable) {
4642 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4643 if (
Error Err = parseValueSymbolTable())
4645 SeenValueSymbolTable =
true;
4655 if (
Error Err = parseConstants())
4657 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4661 if (ShouldLazyLoadMetadata) {
4662 if (
Error Err = rememberAndSkipMetadata())
4666 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4667 if (
Error Err = MDLoader->parseModuleMetadata())
4671 if (
Error Err = MDLoader->parseMetadataKinds())
4675 if (
Error Err = ResolveDataLayout())
4680 if (!SeenFirstFunctionBody) {
4681 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4682 if (
Error Err = globalCleanup())
4684 SeenFirstFunctionBody =
true;
4687 if (VSTOffset > 0) {
4691 if (!SeenValueSymbolTable) {
4692 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4694 SeenValueSymbolTable =
true;
4716 if (
Error Err = rememberAndSkipFunctionBody())
4723 if (SeenValueSymbolTable) {
4727 return globalCleanup();
4731 if (
Error Err = parseUseLists())
4735 if (
Error Err = parseOperandBundleTags())
4739 if (
Error Err = parseSyncScopeNames())
4751 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
4754 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4757 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4760 UseRelativeIDs = *VersionOrErr >= 1;
4764 if (ResolvedDataLayout)
4765 return error(
"target triple too late in module");
4768 return error(
"Invalid triple record");
4769 TheModule->setTargetTriple(Triple(std::move(S)));
4773 if (ResolvedDataLayout)
4774 return error(
"datalayout too late in module");
4776 return error(
"Invalid data layout record");
4782 return error(
"Invalid asm record");
4783 TheModule->setModuleInlineAsm(S);
4790 return error(
"Invalid deplib record");
4797 return error(
"Invalid section name record");
4798 SectionTable.push_back(S);
4804 return error(
"Invalid gcname record");
4805 GCTable.push_back(S);
4809 if (
Error Err = parseComdatRecord(Record))
4818 if (
Error Err = parseGlobalVarRecord(Record))
4822 if (
Error Err = ResolveDataLayout())
4824 if (
Error Err = parseFunctionRecord(Record))
4830 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4836 return error(
"Invalid vstoffset record");
4840 VSTOffset =
Record[0] - 1;
4846 return error(
"Invalid source filename record");
4847 TheModule->setSourceFileName(
ValueName);
4852 this->ValueTypeCallback = std::nullopt;
4856Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4858 ParserCallbacks Callbacks) {
4860 MetadataLoaderCallbacks MDCallbacks;
4861 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(
ID); };
4863 return getContainedTypeID(
I, J);
4866 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4867 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4870Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4872 return error(
"Load/Store operand is not a pointer type");
4873 if (!PointerType::isLoadableOrStorableType(ValType))
4874 return error(
"Cannot load/store from pointer");
4878Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4879 ArrayRef<unsigned> ArgTyIDs) {
4881 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4882 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4883 Attribute::InAlloca}) {
4884 if (!
Attrs.hasParamAttr(i, Kind) ||
4885 Attrs.getParamAttr(i, Kind).getValueAsType())
4888 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4890 return error(
"Missing element type for typed attribute upgrade");
4894 case Attribute::ByVal:
4895 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4897 case Attribute::StructRet:
4898 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4900 case Attribute::InAlloca:
4901 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4914 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
4918 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
4919 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4921 return error(
"Missing element type for inline asm upgrade");
4924 Attribute::get(
Context, Attribute::ElementType, ElemTy));
4932 case Intrinsic::preserve_array_access_index:
4933 case Intrinsic::preserve_struct_access_index:
4934 case Intrinsic::aarch64_ldaxr:
4935 case Intrinsic::aarch64_ldxr:
4936 case Intrinsic::aarch64_stlxr:
4937 case Intrinsic::aarch64_stxr:
4938 case Intrinsic::arm_ldaex:
4939 case Intrinsic::arm_ldrex:
4940 case Intrinsic::arm_stlex:
4941 case Intrinsic::arm_strex: {
4944 case Intrinsic::aarch64_stlxr:
4945 case Intrinsic::aarch64_stxr:
4946 case Intrinsic::arm_stlex:
4947 case Intrinsic::arm_strex:
4954 if (!
Attrs.getParamElementType(ArgNo)) {
4955 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4957 return error(
"Missing element type for elementtype upgrade");
4972Error BitcodeReader::parseFunctionBody(Function *
F) {
4977 if (MDLoader->hasFwdRefs())
4978 return error(
"Invalid function metadata: incoming forward references");
4980 InstructionList.
clear();
4981 unsigned ModuleValueListSize = ValueList.
size();
4982 unsigned ModuleMDLoaderSize = MDLoader->size();
4986 unsigned FTyID = FunctionTypeIDs[
F];
4987 for (Argument &
I :
F->args()) {
4988 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4989 assert(
I.getType() == getTypeByID(ArgTyID) &&
4990 "Incorrect fully specified type for Function Argument");
4994 unsigned NextValueNo = ValueList.
size();
4996 unsigned CurBBNo = 0;
5001 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
5005 auto getLastInstruction = [&]() -> Instruction * {
5006 if (CurBB && !CurBB->
empty())
5007 return &CurBB->
back();
5008 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5009 !FunctionBBs[CurBBNo - 1]->
empty())
5010 return &FunctionBBs[CurBBNo - 1]->back();
5014 std::vector<OperandBundleDef> OperandBundles;
5017 SmallVector<uint64_t, 64>
Record;
5020 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
5023 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
5025 switch (
Entry.Kind) {
5027 return error(
"Malformed block");
5029 goto OutOfRecordLoop;
5038 if (
Error Err = parseConstants())
5040 NextValueNo = ValueList.
size();
5043 if (
Error Err = parseValueSymbolTable())
5047 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5051 assert(DeferredMetadataInfo.empty() &&
5052 "Must read all module-level metadata before function-level");
5053 if (
Error Err = MDLoader->parseFunctionMetadata())
5057 if (
Error Err = parseUseLists())
5071 unsigned ResTypeID = InvalidTypeID;
5072 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
5075 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5077 return error(
"Invalid value");
5079 if (
Record.empty() || Record[0] == 0)
5080 return error(
"Invalid declareblocks record");
5082 FunctionBBs.resize(Record[0]);
5085 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5086 if (BBFRI == BasicBlockFwdRefs.
end()) {
5087 for (BasicBlock *&BB : FunctionBBs)
5090 auto &BBRefs = BBFRI->second;
5092 if (BBRefs.size() > FunctionBBs.size())
5093 return error(
"Invalid ID");
5094 assert(!BBRefs.empty() &&
"Unexpected empty array");
5095 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5096 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5098 if (
I < RE && BBRefs[
I]) {
5099 BBRefs[
I]->insertInto(
F);
5100 FunctionBBs[
I] = BBRefs[
I];
5106 BasicBlockFwdRefs.
erase(BBFRI);
5109 CurBB = FunctionBBs[0];
5116 return error(
"Invalid blockaddr users record");
5130 for (uint64_t ValID : Record)
5132 BackwardRefFunctions.push_back(
F);
5134 return error(
"Invalid blockaddr users record");
5141 I = getLastInstruction();
5144 return error(
"Invalid debug_loc_again record");
5145 I->setDebugLoc(LastLoc);
5150 I = getLastInstruction();
5152 return error(
"Invalid debug loc record");
5157 uint64_t AtomGroup =
Record.size() == 7 ?
Record[5] : 0;
5160 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5163 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5165 return error(
"Invalid debug loc record");
5169 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5171 return error(
"Invalid debug loc record");
5174 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5175 isImplicitCode, AtomGroup, AtomRank);
5176 I->setDebugLoc(LastLoc);
5184 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5186 return error(
"Invalid unary operator record");
5190 return error(
"Invalid unary operator record");
5194 if (OpNum <
Record.size()) {
5198 I->setFastMathFlags(FMF);
5207 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5211 return error(
"Invalid binary operator record");
5215 return error(
"Invalid binary operator record");
5219 if (OpNum <
Record.size()) {
5220 if (
Opc == Instruction::Add ||
5221 Opc == Instruction::Sub ||
5222 Opc == Instruction::Mul ||
5223 Opc == Instruction::Shl) {
5228 }
else if (
Opc == Instruction::SDiv ||
5229 Opc == Instruction::UDiv ||
5230 Opc == Instruction::LShr ||
5231 Opc == Instruction::AShr) {
5234 }
else if (
Opc == Instruction::Or) {
5240 I->setFastMathFlags(FMF);
5249 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5250 OpNum + 1 >
Record.size())
5251 return error(
"Invalid cast record");
5253 ResTypeID =
Record[OpNum++];
5254 Type *ResTy = getTypeByID(ResTypeID);
5257 if (
Opc == -1 || !ResTy)
5258 return error(
"Invalid cast record");
5263 assert(CurBB &&
"No current BB?");
5269 return error(
"Invalid cast");
5273 if (OpNum <
Record.size()) {
5274 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5277 }
else if (
Opc == Instruction::Trunc) {
5289 I->setFastMathFlags(FMF);
5308 Ty = getTypeByID(TyID);
5312 TyID = InvalidTypeID;
5317 unsigned BasePtrTypeID;
5318 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5320 return error(
"Invalid gep record");
5323 TyID = getContainedTypeID(BasePtrTypeID);
5324 if (
BasePtr->getType()->isVectorTy())
5325 TyID = getContainedTypeID(TyID);
5326 Ty = getTypeByID(TyID);
5329 SmallVector<Value*, 16> GEPIdx;
5330 while (OpNum !=
Record.size()) {
5333 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5334 return error(
"Invalid gep record");
5345 unsigned SubType = 0;
5346 if (GTI.isStruct()) {
5348 Idx->getType()->isVectorTy()
5350 :
cast<ConstantInt>(Idx);
5353 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5360 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5361 if (
I->getType()->isVectorTy())
5362 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5365 GEP->setNoWrapFlags(NW);
5374 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5375 return error(
"Invalid extractvalue record");
5378 unsigned RecSize =
Record.size();
5379 if (OpNum == RecSize)
5380 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5382 SmallVector<unsigned, 4> EXTRACTVALIdx;
5383 ResTypeID = AggTypeID;
5384 for (; OpNum != RecSize; ++OpNum) {
5389 if (!IsStruct && !IsArray)
5390 return error(
"EXTRACTVAL: Invalid type");
5391 if ((
unsigned)Index != Index)
5392 return error(
"Invalid value");
5394 return error(
"EXTRACTVAL: Invalid struct index");
5396 return error(
"EXTRACTVAL: Invalid array index");
5397 EXTRACTVALIdx.
push_back((
unsigned)Index);
5401 ResTypeID = getContainedTypeID(ResTypeID, Index);
5404 ResTypeID = getContainedTypeID(ResTypeID);
5418 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5419 return error(
"Invalid insertvalue record");
5422 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5423 return error(
"Invalid insertvalue record");
5425 unsigned RecSize =
Record.size();
5426 if (OpNum == RecSize)
5427 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5429 SmallVector<unsigned, 4> INSERTVALIdx;
5431 for (; OpNum != RecSize; ++OpNum) {
5436 if (!IsStruct && !IsArray)
5437 return error(
"INSERTVAL: Invalid type");
5438 if ((
unsigned)Index != Index)
5439 return error(
"Invalid value");
5441 return error(
"INSERTVAL: Invalid struct index");
5443 return error(
"INSERTVAL: Invalid array index");
5445 INSERTVALIdx.
push_back((
unsigned)Index);
5453 return error(
"Inserted value type doesn't match aggregate type");
5456 ResTypeID = AggTypeID;
5468 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5470 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5472 popValue(Record, OpNum, NextValueNo, CondType,
5473 getVirtualTypeID(CondType),
Cond, CurBB))
5474 return error(
"Invalid select record");
5487 unsigned ValTypeID, CondTypeID;
5488 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5490 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5492 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5493 return error(
"Invalid vector select record");
5496 if (VectorType* vector_type =
5499 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5500 return error(
"Invalid type for value");
5504 return error(
"Invalid type for value");
5508 ResTypeID = ValTypeID;
5513 I->setFastMathFlags(FMF);
5521 unsigned VecTypeID, IdxTypeID;
5522 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5523 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5524 return error(
"Invalid extractelement record");
5526 return error(
"Invalid type for value");
5528 ResTypeID = getContainedTypeID(VecTypeID);
5535 Value *Vec, *Elt, *Idx;
5536 unsigned VecTypeID, IdxTypeID;
5537 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5538 return error(
"Invalid insertelement record");
5540 return error(
"Invalid type for value");
5541 if (popValue(Record, OpNum, NextValueNo,
5543 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5544 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5545 return error(
"Invalid insert element record");
5547 ResTypeID = VecTypeID;
5555 unsigned Vec1TypeID;
5556 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5558 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5560 return error(
"Invalid shufflevector record");
5562 unsigned MaskTypeID;
5563 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5564 return error(
"Invalid shufflevector record");
5566 return error(
"Invalid type for value");
5568 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5570 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5585 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5586 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5588 return error(
"Invalid comparison record");
5590 if (OpNum >=
Record.size())
5592 "Invalid record: operand number exceeded available operands");
5597 if (IsFP &&
Record.size() > OpNum+1)
5602 return error(
"Invalid fcmp predicate");
5603 I =
new FCmpInst(PredVal,
LHS,
RHS);
5606 return error(
"Invalid icmp predicate");
5607 I =
new ICmpInst(PredVal,
LHS,
RHS);
5608 if (
Record.size() > OpNum + 1 &&
5613 if (OpNum + 1 !=
Record.size())
5614 return error(
"Invalid comparison record");
5616 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5618 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5621 I->setFastMathFlags(FMF);
5638 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5639 return error(
"Invalid ret record");
5640 if (OpNum !=
Record.size())
5641 return error(
"Invalid ret record");
5649 return error(
"Invalid br record");
5650 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5652 return error(
"Invalid br record");
5654 if (
Record.size() == 1) {
5659 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5662 getVirtualTypeID(CondType), CurBB);
5663 if (!FalseDest || !
Cond)
5664 return error(
"Invalid br record");
5672 return error(
"Invalid cleanupret record");
5675 Value *CleanupPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5676 getVirtualTypeID(TokenTy), CurBB);
5678 return error(
"Invalid cleanupret record");
5680 if (
Record.size() == 2) {
5681 UnwindDest = getBasicBlock(Record[Idx++]);
5683 return error(
"Invalid cleanupret record");
5692 return error(
"Invalid catchret record");
5695 Value *CatchPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5696 getVirtualTypeID(TokenTy), CurBB);
5698 return error(
"Invalid catchret record");
5699 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5701 return error(
"Invalid catchret record");
5710 return error(
"Invalid catchswitch record");
5715 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5716 getVirtualTypeID(TokenTy), CurBB);
5718 return error(
"Invalid catchswitch record");
5720 unsigned NumHandlers =
Record[Idx++];
5723 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5724 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5726 return error(
"Invalid catchswitch record");
5731 if (Idx + 1 ==
Record.size()) {
5732 UnwindDest = getBasicBlock(Record[Idx++]);
5734 return error(
"Invalid catchswitch record");
5737 if (
Record.size() != Idx)
5738 return error(
"Invalid catchswitch record");
5742 for (BasicBlock *Handler : Handlers)
5743 CatchSwitch->addHandler(Handler);
5745 ResTypeID = getVirtualTypeID(
I->getType());
5753 return error(
"Invalid catchpad/cleanuppad record");
5758 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5759 getVirtualTypeID(TokenTy), CurBB);
5761 return error(
"Invalid catchpad/cleanuppad record");
5763 unsigned NumArgOperands =
Record[Idx++];
5765 SmallVector<Value *, 2>
Args;
5766 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5769 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5770 return error(
"Invalid catchpad/cleanuppad record");
5771 Args.push_back(Val);
5774 if (
Record.size() != Idx)
5775 return error(
"Invalid catchpad/cleanuppad record");
5781 ResTypeID = getVirtualTypeID(
I->getType());
5787 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5793 unsigned OpTyID =
Record[1];
5794 Type *OpTy = getTypeByID(OpTyID);
5800 return error(
"Invalid switch record");
5802 unsigned NumCases =
Record[4];
5807 unsigned CurIdx = 5;
5808 for (
unsigned i = 0; i != NumCases; ++i) {
5810 unsigned NumItems =
Record[CurIdx++];
5811 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5812 bool isSingleNumber =
Record[CurIdx++];
5815 unsigned ActiveWords = 1;
5816 if (ValueBitWidth > 64)
5817 ActiveWords =
Record[CurIdx++];
5820 CurIdx += ActiveWords;
5822 if (!isSingleNumber) {
5824 if (ValueBitWidth > 64)
5825 ActiveWords =
Record[CurIdx++];
5828 CurIdx += ActiveWords;
5839 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5840 for (ConstantInt *Cst : CaseVals)
5841 SI->addCase(Cst, DestBB);
5850 return error(
"Invalid switch record");
5851 unsigned OpTyID =
Record[0];
5852 Type *OpTy = getTypeByID(OpTyID);
5856 return error(
"Invalid switch record");
5857 unsigned NumCases = (
Record.size()-3)/2;
5860 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5862 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
5863 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5864 if (!CaseVal || !DestBB) {
5866 return error(
"Invalid switch record");
5868 SI->addCase(CaseVal, DestBB);
5875 return error(
"Invalid indirectbr record");
5876 unsigned OpTyID =
Record[0];
5877 Type *OpTy = getTypeByID(OpTyID);
5880 return error(
"Invalid indirectbr record");
5881 unsigned NumDests =
Record.size()-2;
5884 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5885 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5889 return error(
"Invalid indirectbr record");
5899 return error(
"Invalid invoke record");
5902 unsigned CCInfo =
Record[OpNum++];
5903 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5904 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5906 unsigned FTyID = InvalidTypeID;
5907 FunctionType *FTy =
nullptr;
5908 if ((CCInfo >> 13) & 1) {
5912 return error(
"Explicit invoke type is not a function type");
5916 unsigned CalleeTypeID;
5917 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5919 return error(
"Invalid invoke record");
5923 return error(
"Callee is not a pointer");
5925 FTyID = getContainedTypeID(CalleeTypeID);
5928 return error(
"Callee is not of pointer to function type");
5930 if (
Record.size() < FTy->getNumParams() + OpNum)
5931 return error(
"Insufficient operands to call");
5933 SmallVector<Value*, 16>
Ops;
5934 SmallVector<unsigned, 16> ArgTyIDs;
5935 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5936 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5937 Ops.push_back(
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5941 return error(
"Invalid invoke record");
5944 if (!FTy->isVarArg()) {
5945 if (
Record.size() != OpNum)
5946 return error(
"Invalid invoke record");
5949 while (OpNum !=
Record.size()) {
5952 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5953 return error(
"Invalid invoke record");
5960 if (!OperandBundles.empty())
5965 ResTypeID = getContainedTypeID(FTyID);
5966 OperandBundles.clear();
5969 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
5980 Value *Val =
nullptr;
5982 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5983 return error(
"Invalid resume record");
5992 unsigned CCInfo =
Record[OpNum++];
5994 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5995 unsigned NumIndirectDests =
Record[OpNum++];
5996 SmallVector<BasicBlock *, 16> IndirectDests;
5997 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
5998 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
6000 unsigned FTyID = InvalidTypeID;
6001 FunctionType *FTy =
nullptr;
6006 return error(
"Explicit call type is not a function type");
6010 unsigned CalleeTypeID;
6011 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6013 return error(
"Invalid callbr record");
6017 return error(
"Callee is not a pointer type");
6019 FTyID = getContainedTypeID(CalleeTypeID);
6022 return error(
"Callee is not of pointer to function type");
6024 if (
Record.size() < FTy->getNumParams() + OpNum)
6025 return error(
"Insufficient operands to call");
6027 SmallVector<Value*, 16>
Args;
6028 SmallVector<unsigned, 16> ArgTyIDs;
6030 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6032 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6033 if (FTy->getParamType(i)->isLabelTy())
6034 Arg = getBasicBlock(Record[OpNum]);
6036 Arg =
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6039 return error(
"Invalid callbr record");
6040 Args.push_back(Arg);
6045 if (!FTy->isVarArg()) {
6046 if (OpNum !=
Record.size())
6047 return error(
"Invalid callbr record");
6049 while (OpNum !=
Record.size()) {
6052 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6053 return error(
"Invalid callbr record");
6060 if (!OperandBundles.empty())
6065 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6068 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6073 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6074 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6075 unsigned LabelNo = ArgNo - FirstBlockArg;
6077 if (!BA || BA->getFunction() !=
F ||
6078 LabelNo > IndirectDests.
size() ||
6079 BA->getBasicBlock() != IndirectDests[LabelNo])
6080 return error(
"callbr argument does not match indirect dest");
6085 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6089 for (
Value *Arg : Args)
6092 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6095 std::string Constraints =
IA->getConstraintString().str();
6098 for (
const auto &CI : ConstraintInfo) {
6100 if (ArgNo >= FirstBlockArg)
6101 Constraints.insert(Pos,
"!");
6106 Pos = Constraints.find(
',', Pos);
6107 if (Pos == std::string::npos)
6113 IA->hasSideEffects(),
IA->isAlignStack(),
6114 IA->getDialect(),
IA->canThrow());
6120 ResTypeID = getContainedTypeID(FTyID);
6121 OperandBundles.clear();
6138 return error(
"Invalid phi record");
6140 unsigned TyID =
Record[0];
6141 Type *Ty = getTypeByID(TyID);
6143 return error(
"Invalid phi record");
6148 size_t NumArgs = (
Record.size() - 1) / 2;
6152 return error(
"Invalid phi record");
6156 SmallDenseMap<BasicBlock *, Value *>
Args;
6157 for (
unsigned i = 0; i != NumArgs; i++) {
6158 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6161 return error(
"Invalid phi BB");
6168 auto It =
Args.find(BB);
6170 if (It !=
Args.end()) {
6184 if (!PhiConstExprBB)
6186 EdgeBB = PhiConstExprBB;
6194 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6196 V =
getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6200 return error(
"Invalid phi record");
6203 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6204 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6205 PhiConstExprBB =
nullptr;
6208 Args.insert({BB,
V});
6214 if (
Record.size() % 2 == 0) {
6218 I->setFastMathFlags(FMF);
6230 return error(
"Invalid landingpad record");
6234 return error(
"Invalid landingpad record");
6236 ResTypeID =
Record[Idx++];
6237 Type *Ty = getTypeByID(ResTypeID);
6239 return error(
"Invalid landingpad record");
6241 Value *PersFn =
nullptr;
6242 unsigned PersFnTypeID;
6243 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6245 return error(
"Invalid landingpad record");
6247 if (!
F->hasPersonalityFn())
6250 return error(
"Personality function mismatch");
6253 bool IsCleanup = !!
Record[Idx++];
6254 unsigned NumClauses =
Record[Idx++];
6257 for (
unsigned J = 0; J != NumClauses; ++J) {
6263 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6266 return error(
"Invalid landingpad record");
6271 "Catch clause has a invalid type!");
6274 "Filter clause has invalid type!");
6285 return error(
"Invalid alloca record");
6286 using APV = AllocaPackedValues;
6287 const uint64_t Rec =
Record[3];
6290 unsigned TyID =
Record[0];
6291 Type *Ty = getTypeByID(TyID);
6293 TyID = getContainedTypeID(TyID);
6294 Ty = getTypeByID(TyID);
6296 return error(
"Missing element type for old-style alloca");
6298 unsigned OpTyID =
Record[1];
6299 Type *OpTy = getTypeByID(OpTyID);
6300 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6305 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6309 return error(
"Invalid alloca record");
6311 const DataLayout &
DL = TheModule->getDataLayout();
6312 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6314 SmallPtrSet<Type *, 4> Visited;
6315 if (!Align && !Ty->
isSized(&Visited))
6316 return error(
"alloca of unsized type");
6318 Align =
DL.getPrefTypeAlign(Ty);
6320 if (!
Size->getType()->isIntegerTy())
6321 return error(
"alloca element count must have integer type");
6323 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6327 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6335 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6336 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6337 return error(
"Invalid load record");
6340 return error(
"Load operand is not a pointer type");
6343 if (OpNum + 3 ==
Record.size()) {
6344 ResTypeID =
Record[OpNum++];
6345 Ty = getTypeByID(ResTypeID);
6347 ResTypeID = getContainedTypeID(OpTypeID);
6348 Ty = getTypeByID(ResTypeID);
6352 return error(
"Missing load type");
6354 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6358 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6360 SmallPtrSet<Type *, 4> Visited;
6361 if (!Align && !Ty->
isSized(&Visited))
6362 return error(
"load of unsized type");
6364 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6365 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6374 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6375 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size()))
6376 return error(
"Invalid load atomic record");
6379 return error(
"Load operand is not a pointer type");
6382 if (OpNum + 5 ==
Record.size()) {
6383 ResTypeID =
Record[OpNum++];
6384 Ty = getTypeByID(ResTypeID);
6386 ResTypeID = getContainedTypeID(OpTypeID);
6387 Ty = getTypeByID(ResTypeID);
6391 return error(
"Missing atomic load type");
6393 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6397 if (Ordering == AtomicOrdering::NotAtomic ||
6398 Ordering == AtomicOrdering::Release ||
6399 Ordering == AtomicOrdering::AcquireRelease)
6400 return error(
"Invalid load atomic record");
6401 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6402 return error(
"Invalid load atomic record");
6403 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6406 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6409 return error(
"Alignment missing from atomic load");
6410 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align, Ordering, SSID);
6418 unsigned PtrTypeID, ValTypeID;
6419 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6420 return error(
"Invalid store record");
6423 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6424 return error(
"Invalid store record");
6426 ValTypeID = getContainedTypeID(PtrTypeID);
6427 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6428 ValTypeID, Val, CurBB))
6429 return error(
"Invalid store record");
6432 if (OpNum + 2 !=
Record.size())
6433 return error(
"Invalid store record");
6438 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6440 SmallPtrSet<Type *, 4> Visited;
6442 return error(
"store of unsized type");
6444 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6445 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6454 unsigned PtrTypeID, ValTypeID;
6455 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6457 return error(
"Invalid store atomic record");
6459 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6460 return error(
"Invalid store atomic record");
6462 ValTypeID = getContainedTypeID(PtrTypeID);
6463 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6464 ValTypeID, Val, CurBB))
6465 return error(
"Invalid store atomic record");
6468 if (OpNum + 4 !=
Record.size())
6469 return error(
"Invalid store atomic record");
6474 if (Ordering == AtomicOrdering::NotAtomic ||
6475 Ordering == AtomicOrdering::Acquire ||
6476 Ordering == AtomicOrdering::AcquireRelease)
6477 return error(
"Invalid store atomic record");
6478 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6479 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6480 return error(
"Invalid store atomic record");
6483 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6486 return error(
"Alignment missing from atomic store");
6487 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6494 const size_t NumRecords =
Record.size();
6496 Value *Ptr =
nullptr;
6498 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6499 return error(
"Invalid cmpxchg record");
6502 return error(
"Cmpxchg operand is not a pointer type");
6505 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6506 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6507 CmpTypeID, Cmp, CurBB))
6508 return error(
"Invalid cmpxchg record");
6511 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6513 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6514 return error(
"Invalid cmpxchg record");
6518 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6519 SuccessOrdering == AtomicOrdering::Unordered)
6520 return error(
"Invalid cmpxchg record");
6522 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6524 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6532 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6533 FailureOrdering == AtomicOrdering::Unordered)
6534 return error(
"Invalid cmpxchg record");
6536 const Align Alignment(
6537 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6539 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6540 FailureOrdering, SSID);
6543 if (NumRecords < 8) {
6547 I->insertInto(CurBB, CurBB->
end());
6549 ResTypeID = CmpTypeID;
6552 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6553 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6562 const size_t NumRecords =
Record.size();
6564 Value *Ptr =
nullptr;
6566 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6567 return error(
"Invalid cmpxchg record");
6570 return error(
"Cmpxchg operand is not a pointer type");
6574 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6575 return error(
"Invalid cmpxchg record");
6577 Value *Val =
nullptr;
6578 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6580 return error(
"Invalid cmpxchg record");
6582 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6583 return error(
"Invalid cmpxchg record");
6585 const bool IsVol =
Record[OpNum];
6590 return error(
"Invalid cmpxchg success ordering");
6592 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6594 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6600 return error(
"Invalid cmpxchg failure ordering");
6602 const bool IsWeak =
Record[OpNum + 4];
6604 MaybeAlign Alignment;
6606 if (NumRecords == (OpNum + 6)) {
6607 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6612 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6614 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6615 FailureOrdering, SSID);
6619 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6620 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6629 const size_t NumRecords =
Record.size();
6632 Value *Ptr =
nullptr;
6634 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6635 return error(
"Invalid atomicrmw record");
6638 return error(
"Invalid atomicrmw record");
6640 Value *Val =
nullptr;
6641 unsigned ValTypeID = InvalidTypeID;
6643 ValTypeID = getContainedTypeID(PtrTypeID);
6644 if (popValue(Record, OpNum, NextValueNo,
6645 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6646 return error(
"Invalid atomicrmw record");
6648 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6649 return error(
"Invalid atomicrmw record");
6652 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6653 return error(
"Invalid atomicrmw record");
6655 bool IsElementwise =
false;
6660 return error(
"Invalid atomicrmw record");
6662 const bool IsVol =
Record[OpNum + 1];
6665 if (Ordering == AtomicOrdering::NotAtomic ||
6666 Ordering == AtomicOrdering::Unordered)
6667 return error(
"Invalid atomicrmw record");
6669 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6671 MaybeAlign Alignment;
6673 if (NumRecords == (OpNum + 5)) {
6674 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6680 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6682 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID,
6684 ResTypeID = ValTypeID;
6692 return error(
"Invalid fence record");
6694 if (Ordering == AtomicOrdering::NotAtomic ||
6695 Ordering == AtomicOrdering::Unordered ||
6696 Ordering == AtomicOrdering::Monotonic)
6697 return error(
"Invalid fence record");
6699 I =
new FenceInst(
Context, Ordering, SSID);
6706 SeenDebugRecord =
true;
6709 return error(
"Invalid dbg record: missing instruction");
6712 Inst->
getParent()->insertDbgRecordBefore(
6723 SeenDebugRecord =
true;
6726 return error(
"Invalid dbg record: missing instruction");
6743 DILocalVariable *Var =
6745 DIExpression *Expr =
6758 unsigned SlotBefore =
Slot;
6759 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6760 return error(
"Invalid dbg record: invalid value");
6762 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6765 RawLocation = getFnMetadataByID(Record[Slot++]);
6768 DbgVariableRecord *DVR =
nullptr;
6772 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6773 DbgVariableRecord::LocationType::Value);
6776 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6777 DbgVariableRecord::LocationType::Declare);
6780 DVR =
new DbgVariableRecord(
6781 RawLocation, Var, Expr, DIL,
6782 DbgVariableRecord::LocationType::DeclareValue);
6786 DIExpression *AddrExpr =
6788 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6789 DVR =
new DbgVariableRecord(RawLocation, Var, Expr,
ID, Addr, AddrExpr,
6802 return error(
"Invalid call record");
6806 unsigned CCInfo =
Record[OpNum++];
6812 return error(
"Fast math flags indicator set for call with no FMF");
6815 unsigned FTyID = InvalidTypeID;
6816 FunctionType *FTy =
nullptr;
6821 return error(
"Explicit call type is not a function type");
6825 unsigned CalleeTypeID;
6826 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6828 return error(
"Invalid call record");
6832 return error(
"Callee is not a pointer type");
6834 FTyID = getContainedTypeID(CalleeTypeID);
6837 return error(
"Callee is not of pointer to function type");
6839 if (
Record.size() < FTy->getNumParams() + OpNum)
6840 return error(
"Insufficient operands to call");
6842 SmallVector<Value*, 16>
Args;
6843 SmallVector<unsigned, 16> ArgTyIDs;
6845 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6846 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6847 if (FTy->getParamType(i)->isLabelTy())
6848 Args.push_back(getBasicBlock(Record[OpNum]));
6851 FTy->getParamType(i), ArgTyID, CurBB));
6854 return error(
"Invalid call record");
6858 if (!FTy->isVarArg()) {
6859 if (OpNum !=
Record.size())
6860 return error(
"Invalid call record");
6862 while (OpNum !=
Record.size()) {
6865 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6866 return error(
"Invalid call record");
6873 if (!OperandBundles.empty())
6877 ResTypeID = getContainedTypeID(FTyID);
6878 OperandBundles.clear();
6892 SeenDebugIntrinsic =
true;
6899 return error(
"Fast-math-flags specified for call without "
6900 "floating-point scalar or vector return type");
6901 I->setFastMathFlags(FMF);
6907 return error(
"Invalid va_arg record");
6908 unsigned OpTyID =
Record[0];
6909 Type *OpTy = getTypeByID(OpTyID);
6912 Type *ResTy = getTypeByID(ResTypeID);
6913 if (!OpTy || !
Op || !ResTy)
6914 return error(
"Invalid va_arg record");
6915 I =
new VAArgInst(
Op, ResTy);
6925 if (
Record.empty() || Record[0] >= BundleTags.size())
6926 return error(
"Invalid operand bundle record");
6928 std::vector<Value *> Inputs;
6931 while (OpNum !=
Record.size()) {
6933 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
6934 return error(
"Invalid operand bundle record");
6935 Inputs.push_back(
Op);
6938 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6946 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6947 return error(
"Invalid freeze record");
6948 if (OpNum !=
Record.size())
6949 return error(
"Invalid freeze record");
6951 I =
new FreezeInst(
Op);
6952 ResTypeID = OpTypeID;
6962 return error(
"Invalid instruction with no BB");
6964 if (!OperandBundles.empty()) {
6966 return error(
"Operand bundles found with no consumer");
6968 I->insertInto(CurBB, CurBB->
end());
6971 if (
I->isTerminator()) {
6973 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
6977 if (!
I->getType()->isVoidTy()) {
6978 assert(
I->getType() == getTypeByID(ResTypeID) &&
6979 "Incorrect result type ID");
6987 if (!OperandBundles.empty())
6988 return error(
"Operand bundles found with no consumer");
6992 if (!
A->getParent()) {
6994 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
7000 return error(
"Never resolved value found in function");
7005 if (MDLoader->hasFwdRefs())
7006 return error(
"Invalid function metadata: outgoing forward refs");
7011 for (
const auto &Pair : ConstExprEdgeBBs) {
7022 ValueList.
shrinkTo(ModuleValueListSize);
7023 MDLoader->shrinkTo(ModuleMDLoaderSize);
7024 std::vector<BasicBlock*>().swap(FunctionBBs);
7029Error BitcodeReader::findFunctionInStream(
7031 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7032 while (DeferredFunctionInfoIterator->second == 0) {
7037 assert(VSTOffset == 0 || !
F->hasName());
7040 if (
Error Err = rememberAndSkipFunctionBodies())
7046SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7049 if (Val >= SSIDs.
size())
7058Error BitcodeReader::materialize(GlobalValue *GV) {
7061 if (!
F || !
F->isMaterializable())
7064 auto DFII = DeferredFunctionInfo.
find(
F);
7065 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7068 if (DFII->second == 0)
7069 if (
Error Err = findFunctionInStream(
F, DFII))
7073 if (
Error Err = materializeMetadata())
7080 if (
Error Err = parseFunctionBody(
F))
7082 F->setIsMaterializable(
false);
7086 if (SeenDebugIntrinsic && SeenDebugRecord)
7087 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7093 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7094 F->setSubprogram(SP);
7097 if (!MDLoader->isStrippingTBAA()) {
7099 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7102 MDLoader->setStripTBAA(
true);
7109 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7110 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7116 unsigned ExpectedNumOperands = 0;
7118 ExpectedNumOperands = 2;
7120 ExpectedNumOperands =
SI->getNumSuccessors();
7122 ExpectedNumOperands = 1;
7126 ExpectedNumOperands = 2;
7133 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7134 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7140 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7141 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7143 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7144 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7145 CI->getArgOperand(ArgNo)->getType(),
7146 CI->getParamAttributes(ArgNo)));
7149 if (Function *OldFn = CI->getCalledFunction()) {
7150 auto It = UpgradedIntrinsics.find(OldFn);
7151 if (It != UpgradedIntrinsics.end())
7162 return materializeForwardReferencedFunctions();
7165Error BitcodeReader::materializeModule() {
7166 if (
Error Err = materializeMetadata())
7170 WillMaterializeAllForwardRefs =
true;
7174 for (Function &
F : *TheModule) {
7175 if (
Error Err = materialize(&
F))
7181 if (LastFunctionBlockBit || NextUnreadBit)
7183 ? LastFunctionBlockBit
7189 if (!BasicBlockFwdRefs.
empty())
7190 return error(
"Never resolved function from blockaddress");
7196 for (
auto &
I : UpgradedIntrinsics) {
7197 for (
auto *U :
I.first->users()) {
7201 if (
I.first !=
I.second) {
7202 if (!
I.first->use_empty())
7203 I.first->replaceAllUsesWith(
I.second);
7204 I.first->eraseFromParent();
7207 UpgradedIntrinsics.clear();
7222std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7223 return IdentifiedStructTypes;
7226ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7227 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7229 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7230 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7232void ModuleSummaryIndexBitcodeReader::addThisModule() {
7237ModuleSummaryIndexBitcodeReader::getThisModule() {
7241template <
bool AllowNullValueInfo>
7242std::pair<ValueInfo, GlobalValue::GUID>
7243ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7244 auto VGI = ValueIdToValueInfoMap[ValueId];
7251 assert(AllowNullValueInfo || std::get<0>(VGI));
7255void ModuleSummaryIndexBitcodeReader::setValueGUID(
7257 StringRef SourceFileName) {
7258 std::string GlobalId =
7261 auto OriginalNameID = ValueGUID;
7265 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7271 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7280Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7282 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7289 if (!MaybeCurrentBit)
7291 uint64_t CurrentBit = MaybeCurrentBit.
get();
7296 SmallVector<uint64_t, 64>
Record;
7305 BitstreamEntry
Entry = MaybeEntry.
get();
7307 switch (
Entry.Kind) {
7310 return error(
"Malformed block");
7326 switch (MaybeRecord.
get()) {
7331 return error(
"Invalid vst_code_entry record");
7332 unsigned ValueID =
Record[0];
7334 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7335 assert(VLI != ValueIdToLinkageMap.
end() &&
7336 "No linkage found for VST entry?");
7345 return error(
"Invalid vst_code_fnentry record");
7346 unsigned ValueID =
Record[0];
7348 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7349 assert(VLI != ValueIdToLinkageMap.
end() &&
7350 "No linkage found for VST entry?");
7358 unsigned ValueID =
Record[0];
7362 ValueIdToValueInfoMap[ValueID] =
7373Error ModuleSummaryIndexBitcodeReader::parseModule() {
7377 SmallVector<uint64_t, 64>
Record;
7378 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7379 unsigned ValueId = 0;
7383 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
7386 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7388 switch (
Entry.Kind) {
7390 return error(
"Malformed block");
7402 if (
Error Err = readBlockInfo())
7408 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7409 !SeenGlobalValSummary) &&
7410 "Expected early VST parse via VSTOffset record");
7417 if (!SourceFileName.
empty())
7419 assert(!SeenValueSymbolTable &&
7420 "Already read VST when parsing summary block?");
7425 if (VSTOffset > 0) {
7426 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7428 SeenValueSymbolTable =
true;
7430 SeenGlobalValSummary =
true;
7431 if (
Error Err = parseEntireSummary(
Entry.ID))
7435 if (
Error Err = parseModuleStringTable())
7443 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7446 switch (MaybeBitCode.
get()) {
7450 if (
Error Err = parseVersionRecord(Record).takeError())
7458 return error(
"Invalid source filename record");
7465 return error(
"Invalid hash length " + Twine(
Record.size()).str());
7466 auto &Hash = getThisModule()->second;
7468 for (
auto &Val : Record) {
7469 assert(!(Val >> 32) &&
"Unexpected high bits set");
7477 return error(
"Invalid vstoffset record");
7481 VSTOffset =
Record[0] - 1;
7491 ArrayRef<uint64_t> GVRecord;
7492 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7493 if (GVRecord.
size() <= 3)
7494 return error(
"Invalid global record");
7495 uint64_t RawLinkage = GVRecord[3];
7498 ValueIdToLinkageMap[ValueId++] =
Linkage;
7502 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7513ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7516 for (uint64_t RefValueId : Record)
7517 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7522ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7523 bool IsOldProfileFormat,
7524 bool HasProfile,
bool HasRelBF) {
7528 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7533 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7535 bool HasTailCall =
false;
7537 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7538 if (IsOldProfileFormat) {
7542 }
else if (HasProfile)
7543 std::tie(Hotness, HasTailCall) =
7577 static_cast<size_t>(
Record[Slot + 1])};
7600 while (Slot <
Record.size())
7604std::vector<FunctionSummary::ParamAccess>
7605ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7606 auto ReadRange = [&]() {
7608 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7610 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7617 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7618 while (!
Record.empty()) {
7619 PendingParamAccesses.emplace_back();
7620 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7622 ParamAccess.
Use = ReadRange();
7627 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7628 Call.Offsets = ReadRange();
7631 return PendingParamAccesses;
7634void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7635 ArrayRef<uint64_t> Record,
size_t &Slot,
7638 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7642void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7643 ArrayRef<uint64_t> Record) {
7651 while (Slot <
Record.size())
7652 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7655SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7656 ArrayRef<uint64_t> Record,
unsigned &
I) {
7657 SmallVector<unsigned> StackIdList;
7661 if (RadixArray.empty()) {
7662 unsigned NumStackEntries =
Record[
I++];
7664 StackIdList.
reserve(NumStackEntries);
7665 for (
unsigned J = 0; J < NumStackEntries; J++) {
7666 assert(Record[
I] < StackIds.size());
7667 StackIdList.
push_back(getStackIdIndex(Record[
I++]));
7670 unsigned RadixIndex =
Record[
I++];
7676 assert(RadixIndex < RadixArray.size());
7677 unsigned NumStackIds = RadixArray[RadixIndex++];
7678 StackIdList.
reserve(NumStackIds);
7679 while (NumStackIds--) {
7680 assert(RadixIndex < RadixArray.size());
7681 unsigned Elem = RadixArray[RadixIndex];
7682 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7683 RadixIndex = RadixIndex - Elem;
7684 assert(RadixIndex < RadixArray.size());
7685 Elem = RadixArray[RadixIndex];
7687 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7690 StackIdList.
push_back(getStackIdIndex(Elem));
7700 unsigned FirstWORef = Refs.
size() - WOCnt;
7701 unsigned RefNo = FirstWORef - ROCnt;
7702 for (; RefNo < FirstWORef; ++RefNo)
7703 Refs[RefNo].setReadOnly();
7704 for (; RefNo < Refs.
size(); ++RefNo)
7705 Refs[RefNo].setWriteOnly();
7710Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7713 SmallVector<uint64_t, 64>
Record;
7720 BitstreamEntry
Entry = MaybeEntry.
get();
7723 return error(
"Invalid Summary Block: record for version expected");
7728 return error(
"Invalid Summary Block: version expected");
7731 const bool IsOldProfileFormat =
Version == 1;
7734 const bool MemProfAfterFunctionSummary =
Version >= 13;
7736 return error(
"Invalid summary version " + Twine(
Version) +
7737 ". Version should be in the range [1-" +
7744 GlobalValueSummary *LastSeenSummary =
nullptr;
7754 FunctionSummary *CurrentPrevailingFS =
nullptr;
7759 std::vector<GlobalValue::GUID> PendingTypeTests;
7760 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7761 PendingTypeCheckedLoadVCalls;
7762 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7763 PendingTypeCheckedLoadConstVCalls;
7764 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7766 std::vector<CallsiteInfo> PendingCallsites;
7767 std::vector<AllocInfo> PendingAllocs;
7768 std::vector<uint64_t> PendingContextIds;
7774 BitstreamEntry
Entry = MaybeEntry.
get();
7776 switch (
Entry.Kind) {
7779 return error(
"Malformed block");
7795 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7798 unsigned BitCode = MaybeBitCode.
get();
7808 uint64_t ValueID =
Record[0];
7815 ValueIdToValueInfoMap[ValueID] =
7833 unsigned ValueID =
Record[0];
7834 uint64_t RawFlags =
Record[1];
7835 unsigned InstCount =
Record[2];
7836 uint64_t RawFunFlags = 0;
7837 unsigned NumRefs =
Record[3];
7838 unsigned NumRORefs = 0, NumWORefs = 0;
7839 int RefListStartIndex = 4;
7843 RefListStartIndex = 5;
7846 RefListStartIndex = 6;
7849 RefListStartIndex = 7;
7860 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7862 "Record size inconsistent with number of references");
7864 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7869 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7870 IsOldProfileFormat, HasProfile, HasRelBF);
7872 auto [
VI,
GUID] = getValueInfoFromValueId(ValueID);
7879 IsPrevailing(
VI.getGUID());
7885 assert(!MemProfAfterFunctionSummary ||
7886 (PendingCallsites.empty() && PendingAllocs.empty()));
7887 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
7888 PendingCallsites.clear();
7889 PendingAllocs.clear();
7892 auto FS = std::make_unique<FunctionSummary>(
7894 std::move(Calls), std::move(PendingTypeTests),
7895 std::move(PendingTypeTestAssumeVCalls),
7896 std::move(PendingTypeCheckedLoadVCalls),
7897 std::move(PendingTypeTestAssumeConstVCalls),
7898 std::move(PendingTypeCheckedLoadConstVCalls),
7899 std::move(PendingParamAccesses), std::move(PendingCallsites),
7900 std::move(PendingAllocs));
7901 FS->setModulePath(getThisModule()->first());
7902 FS->setOriginalName(GUID);
7905 if (MemProfAfterFunctionSummary) {
7906 if (IsPrevailingSym)
7907 CurrentPrevailingFS =
FS.get();
7909 CurrentPrevailingFS =
nullptr;
7918 unsigned ValueID =
Record[0];
7919 uint64_t RawFlags =
Record[1];
7920 unsigned AliaseeID =
Record[2];
7922 auto AS = std::make_unique<AliasSummary>(Flags);
7928 AS->setModulePath(getThisModule()->first());
7930 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7932 if (!AliaseeInModule)
7933 return error(
"Alias expects aliasee summary to be parsed");
7934 AS->setAliasee(AliaseeVI, AliaseeInModule);
7936 auto GUID = getValueInfoFromValueId(ValueID);
7937 AS->setOriginalName(std::get<1>(GUID));
7943 unsigned ValueID =
Record[0];
7944 uint64_t RawFlags =
Record[1];
7945 unsigned RefArrayStart = 2;
7946 GlobalVarSummary::GVarFlags GVF(
false,
7956 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7958 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7959 FS->setModulePath(getThisModule()->first());
7960 auto GUID = getValueInfoFromValueId(ValueID);
7961 FS->setOriginalName(std::get<1>(GUID));
7969 unsigned ValueID =
Record[0];
7970 uint64_t RawFlags =
Record[1];
7972 unsigned NumRefs =
Record[3];
7973 unsigned RefListStartIndex = 4;
7974 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7977 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7979 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
7980 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7985 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7986 VS->setModulePath(getThisModule()->first());
7987 VS->setVTableFuncs(VTableFuncs);
7988 auto GUID = getValueInfoFromValueId(ValueID);
7989 VS->setOriginalName(std::get<1>(GUID));
8001 unsigned ValueID =
Record[0];
8002 uint64_t ModuleId =
Record[1];
8003 uint64_t RawFlags =
Record[2];
8004 unsigned InstCount =
Record[3];
8005 uint64_t RawFunFlags = 0;
8006 unsigned NumRefs =
Record[4];
8007 unsigned NumRORefs = 0, NumWORefs = 0;
8008 int RefListStartIndex = 5;
8012 RefListStartIndex = 6;
8013 size_t NumRefsIndex = 5;
8015 unsigned NumRORefsOffset = 1;
8016 RefListStartIndex = 7;
8019 RefListStartIndex = 8;
8021 RefListStartIndex = 9;
8023 NumRORefsOffset = 2;
8026 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
8028 NumRefs =
Record[NumRefsIndex];
8032 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8034 "Record size inconsistent with number of references");
8036 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8039 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8040 IsOldProfileFormat, HasProfile,
false);
8041 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8043 auto FS = std::make_unique<FunctionSummary>(
8045 std::move(Edges), std::move(PendingTypeTests),
8046 std::move(PendingTypeTestAssumeVCalls),
8047 std::move(PendingTypeCheckedLoadVCalls),
8048 std::move(PendingTypeTestAssumeConstVCalls),
8049 std::move(PendingTypeCheckedLoadConstVCalls),
8050 std::move(PendingParamAccesses), std::move(PendingCallsites),
8051 std::move(PendingAllocs));
8052 LastSeenSummary =
FS.get();
8053 if (MemProfAfterFunctionSummary)
8054 CurrentPrevailingFS =
FS.get();
8055 LastSeenGUID =
VI.getGUID();
8056 FS->setModulePath(ModuleIdMap[ModuleId]);
8064 unsigned ValueID =
Record[0];
8065 uint64_t ModuleId =
Record[1];
8066 uint64_t RawFlags =
Record[2];
8067 unsigned AliaseeValueId =
Record[3];
8069 auto AS = std::make_unique<AliasSummary>(Flags);
8070 LastSeenSummary = AS.get();
8071 AS->setModulePath(ModuleIdMap[ModuleId]);
8073 auto AliaseeVI = std::get<0>(
8074 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8076 auto AliaseeInModule =
8078 AS->setAliasee(AliaseeVI, AliaseeInModule);
8080 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8081 LastSeenGUID =
VI.getGUID();
8087 unsigned ValueID =
Record[0];
8088 uint64_t ModuleId =
Record[1];
8089 uint64_t RawFlags =
Record[2];
8090 unsigned RefArrayStart = 3;
8091 GlobalVarSummary::GVarFlags GVF(
false,
8101 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8103 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8104 LastSeenSummary =
FS.get();
8105 FS->setModulePath(ModuleIdMap[ModuleId]);
8106 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8107 LastSeenGUID =
VI.getGUID();
8113 uint64_t OriginalName =
Record[0];
8114 if (!LastSeenSummary)
8115 return error(
"Name attachment that does not follow a combined record");
8119 LastSeenSummary =
nullptr;
8124 assert(PendingTypeTests.empty());
8129 assert(PendingTypeTestAssumeVCalls.empty());
8130 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8131 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8135 assert(PendingTypeCheckedLoadVCalls.empty());
8136 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8137 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8141 PendingTypeTestAssumeConstVCalls.push_back(
8146 PendingTypeCheckedLoadConstVCalls.push_back(
8152 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8153 StringRef
Name(Strtab.
data() + Record[
I],
8154 static_cast<size_t>(Record[
I + 1]));
8157 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, GUID);
8164 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8165 StringRef
Name(Strtab.
data() + Record[
I],
8166 static_cast<size_t>(Record[
I + 1]));
8169 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, GUID);
8179 parseTypeIdCompatibleVtableSummaryRecord(Record);
8187 PendingParamAccesses = parseParamAccesses(Record);
8194 assert(StackIds.empty());
8196 StackIds = ArrayRef<uint64_t>(Record);
8202 StackIds.reserve(
Record.size() / 2);
8203 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8204 StackIds.push_back(*R << 32 | *(R + 1));
8206 assert(StackIdToIndex.empty());
8208 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8213 RadixArray = ArrayRef<uint64_t>(Record);
8220 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8222 unsigned ValueID =
Record[0];
8223 SmallVector<unsigned> StackIdList;
8225 assert(R < StackIds.size());
8226 StackIdList.
push_back(getStackIdIndex(R));
8228 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8229 if (MemProfAfterFunctionSummary)
8231 CallsiteInfo({
VI, std::move(StackIdList)}));
8233 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8240 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8241 auto RecordIter =
Record.begin();
8242 unsigned ValueID = *RecordIter++;
8243 unsigned NumStackIds = *RecordIter++;
8244 unsigned NumVersions = *RecordIter++;
8245 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8246 SmallVector<unsigned> StackIdList;
8247 for (
unsigned J = 0; J < NumStackIds; J++) {
8248 assert(*RecordIter < StackIds.size());
8249 StackIdList.
push_back(getStackIdIndex(*RecordIter++));
8251 SmallVector<unsigned> Versions;
8252 for (
unsigned J = 0; J < NumVersions; J++)
8254 ValueInfo
VI = std::get<0>(
8255 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8256 if (MemProfAfterFunctionSummary)
8258 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8260 PendingCallsites.push_back(
8261 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8268 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8273 PendingContextIds.reserve(
Record.size() / 2);
8274 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8275 PendingContextIds.push_back(*R << 32 | *(R + 1));
8282 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8283 PendingContextIds.clear();
8287 std::vector<MIBInfo> MIBs;
8288 unsigned NumMIBs = 0;
8291 unsigned MIBsRead = 0;
8292 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8296 auto StackIdList = parseAllocInfoContext(Record,
I);
8297 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8303 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8305 assert(!PendingContextIds.empty() &&
8306 "Missing context ids for alloc sizes");
8307 unsigned ContextIdIndex = 0;
8313 while (MIBsRead++ < NumMIBs) {
8315 unsigned NumContextSizeInfoEntries =
Record[
I++];
8317 std::vector<ContextTotalSize> ContextSizes;
8318 ContextSizes.reserve(NumContextSizeInfoEntries);
8319 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8320 assert(ContextIdIndex < PendingContextIds.size());
8322 if (PendingContextIds[ContextIdIndex] == 0) {
8331 ContextSizes.push_back(
8332 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8334 AllContextSizes.push_back(std::move(ContextSizes));
8336 PendingContextIds.clear();
8338 AllocInfo AI(std::move(MIBs));
8339 if (!AllContextSizes.empty()) {
8340 assert(AI.MIBs.size() == AllContextSizes.size());
8341 AI.ContextSizeInfos = std::move(AllContextSizes);
8344 if (MemProfAfterFunctionSummary)
8345 CurrentPrevailingFS->
addAlloc(std::move(AI));
8347 PendingAllocs.push_back(std::move(AI));
8355 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8357 std::vector<MIBInfo> MIBs;
8358 unsigned NumMIBs =
Record[
I++];
8359 unsigned NumVersions =
Record[
I++];
8360 unsigned MIBsRead = 0;
8361 while (MIBsRead++ < NumMIBs) {
8364 SmallVector<unsigned> StackIdList;
8366 StackIdList = parseAllocInfoContext(Record,
I);
8367 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8370 SmallVector<uint8_t> Versions;
8371 for (
unsigned J = 0; J < NumVersions; J++)
8374 AllocInfo AI(std::move(Versions), std::move(MIBs));
8375 if (MemProfAfterFunctionSummary)
8376 CurrentPrevailingFS->
addAlloc(std::move(AI));
8378 PendingAllocs.push_back(std::move(AI));
8388Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8392 SmallVector<uint64_t, 64>
Record;
8394 SmallString<128> ModulePath;
8401 BitstreamEntry
Entry = MaybeEntry.
get();
8403 switch (
Entry.Kind) {
8406 return error(
"Malformed block");
8418 switch (MaybeRecord.
get()) {
8423 uint64_t ModuleId =
Record[0];
8426 return error(
"Invalid code_entry record");
8428 LastSeenModule = TheIndex.
addModule(ModulePath);
8429 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8437 return error(
"Invalid hash length " + Twine(
Record.size()).str());
8438 if (!LastSeenModule)
8439 return error(
"Invalid hash that does not follow a module path");
8441 for (
auto &Val : Record) {
8442 assert(!(Val >> 32) &&
"Unexpected high bits set");
8443 LastSeenModule->
second[Pos++] = Val;
8446 LastSeenModule =
nullptr;
8459class BitcodeErrorCategoryType :
public std::error_category {
8460 const char *
name()
const noexcept
override {
8461 return "llvm.bitcode";
8464 std::string message(
int IE)
const override {
8467 case BitcodeError::CorruptedBitcode:
8468 return "Corrupted bitcode";
8477 static BitcodeErrorCategoryType ErrorCategory;
8478 return ErrorCategory;
8482 unsigned Block,
unsigned RecordID) {
8484 return std::move(Err);
8493 switch (Entry.Kind) {
8498 return error(
"Malformed block");
8502 return std::move(Err);
8512 if (MaybeRecord.
get() == RecordID)
8523Expected<std::vector<BitcodeModule>>
8527 return FOrErr.takeError();
8528 return std::move(FOrErr->Mods);
8553 switch (Entry.Kind) {
8556 return error(
"Malformed block");
8559 uint64_t IdentificationBit = -1ull;
8563 return std::move(Err);
8569 Entry = MaybeEntry.
get();
8574 return error(
"Malformed block");
8580 return std::move(Err);
8599 if (!
I.Strtab.empty())
8606 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8607 F.StrtabForSymtab = *Strtab;
8623 if (
F.Symtab.empty())
8624 F.Symtab = *SymtabOrErr;
8629 return std::move(Err);
8634 return std::move(E);
8649BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8650 bool ShouldLazyLoadMetadata,
bool IsImporting,
8654 std::string ProducerIdentification;
8655 if (IdentificationBit != -1ull) {
8657 return std::move(JumpFailed);
8660 return std::move(
E);
8664 return std::move(JumpFailed);
8665 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8668 std::unique_ptr<Module>
M =
8669 std::make_unique<Module>(ModuleIdentifier,
Context);
8670 M->setMaterializer(R);
8673 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8674 IsImporting, Callbacks))
8675 return std::move(Err);
8677 if (MaterializeAll) {
8679 if (
Error Err =
M->materializeAll())
8680 return std::move(Err);
8683 if (
Error Err =
R->materializeForwardReferencedFunctions())
8684 return std::move(Err);
8687 return std::move(M);
8690Expected<std::unique_ptr<Module>>
8693 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8708 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8709 ModulePath, IsPrevailing);
8710 return R.parseModule();
8717 return std::move(JumpFailed);
8719 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8720 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8721 ModuleIdentifier, 0);
8723 if (
Error Err = R.parseModule())
8724 return std::move(Err);
8726 return std::move(Index);
8732 return std::move(Err);
8738 return std::move(
E);
8740 switch (Entry.Kind) {
8743 return error(
"Malformed block");
8746 return std::make_pair(
false,
false);
8758 switch (MaybeBitCode.
get()) {
8764 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
8766 bool EnableSplitLTOUnit = Flags & 0x8;
8767 bool UnifiedLTO = Flags & 0x200;
8768 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8779 return std::move(JumpFailed);
8782 return std::move(Err);
8787 return std::move(E);
8789 switch (Entry.Kind) {
8791 return error(
"Malformed block");
8802 return Flags.takeError();
8812 return std::move(Err);
8819 return StreamFailed.takeError();
8829 if (MsOrErr->size() != 1)
8830 return error(
"Expected a single module");
8832 return (*MsOrErr)[0];
8835Expected<std::unique_ptr<Module>>
8837 bool ShouldLazyLoadMetadata,
bool IsImporting,
8843 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8848 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
8849 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
8851 IsImporting, Callbacks);
8853 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8859 return getModuleImpl(Context,
true,
false,
false, Callbacks);
8871 return BM->parseModule(Context, Callbacks);
8904 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8913 return BM->getSummary();
8921 return BM->getLTOInfo();
8926 bool IgnoreEmptyThinLTOIndexFile) {
8931 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 Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
void push_back(Value *V, unsigned TypeID)
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
void shrinkTo(unsigned N)
unsigned getTypeID(unsigned ValNo) const
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
ArrayRef< uint8_t > getBitcodeBytes() const
Expected< word_t > Read(unsigned NumBits)
Expected< BitstreamEntry > advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Expected< BitstreamEntry > advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block.
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
uint64_t getCurrentByteNo() const
LLVM_ABI Expected< std::optional< BitstreamBlockInfo > > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
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()
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase createFromIntValue(uint32_t Data)
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
StringRef saveString(StringRef String)
LLVM_ABI void setFlags(uint64_t Flags)
CfiFunctionIndex & cfiFunctionDecls()
void addBlockCount(uint64_t C)
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
CfiFunctionIndex & cfiFunctionDefs()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
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.
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
@ 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.
FunctionAddr VTableAddr Value
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
StringMapEntry< Value * > ValueName
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI const std::error_category & BitcodeErrorCategory()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI void UpgradeInlineAsmString(std::string *AsmStr)
Upgrade comment in call to inline asm that represents an objc retain release marker.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
std::error_code make_error_code(BitcodeError E)
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto uninitialized_copy(R &&Src, IterTy Dst)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
LLVM_ABI void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
FunctionAddr VTableAddr uintptr_t uintptr_t Version
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
auto reverse(ContainerTy &&C)
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI std::string UpgradeDataLayoutString(StringRef DL, StringRef Triple)
Upgrade the datalayout string by adding a section for address space pointers.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ ArgMem
Access to memory via argument pointers.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
LLVM_ABI Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
MaybeAlign decodeMaybeAlign(unsigned Value)
Dual operation of the encode function above.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
LLVM_ABI void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Basic information extracted from a bitcode module to be used for LTO.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
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
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
std::optional< DataLayoutCallbackFuncTy > DataLayout
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
Kind
Specifies which kind of type check we should emit for this byte array.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName