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) {
489 if (
Record.size() < 2 || Record[0] > Strtab.
size() ||
490 Record[1] > Strtab.
size() - Record[0])
492 return {StringRef(Strtab.
data() + Record[0], Record[1]),
Record.slice(2)};
503class BitcodeConstant final :
public Value,
504 TrailingObjects<BitcodeConstant, unsigned> {
505 friend TrailingObjects;
508 static constexpr uint8_t SubclassID = 255;
516 static constexpr uint8_t ConstantStructOpcode = 255;
517 static constexpr uint8_t ConstantArrayOpcode = 254;
518 static constexpr uint8_t ConstantVectorOpcode = 253;
519 static constexpr uint8_t NoCFIOpcode = 252;
520 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
521 static constexpr uint8_t BlockAddressOpcode = 250;
522 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
523 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
530 unsigned BlockAddressBB = 0;
531 Type *SrcElemTy =
nullptr;
532 std::optional<ConstantRange>
InRange;
534 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0,
Type *SrcElemTy =
nullptr,
535 std::optional<ConstantRange>
InRange = std::nullopt)
536 : Opcode(Opcode),
Flags(
Flags), SrcElemTy(SrcElemTy),
539 ExtraInfo(uint8_t Opcode, uint8_t Flags,
unsigned BlockAddressBB)
540 : Opcode(Opcode),
Flags(
Flags), BlockAddressBB(BlockAddressBB) {}
545 unsigned NumOperands;
546 unsigned BlockAddressBB;
548 std::optional<ConstantRange>
InRange;
551 BitcodeConstant(
Type *Ty,
const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
553 NumOperands(OpIDs.
size()), BlockAddressBB(
Info.BlockAddressBB),
558 BitcodeConstant &operator=(
const BitcodeConstant &) =
delete;
562 const ExtraInfo &Info,
563 ArrayRef<unsigned> OpIDs) {
564 void *Mem =
A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.
size()),
565 alignof(BitcodeConstant));
566 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
569 static bool classof(
const Value *V) {
return V->getValueID() == SubclassID; }
571 ArrayRef<unsigned> getOperandIDs()
const {
572 return ArrayRef(getTrailingObjects(), NumOperands);
575 std::optional<ConstantRange> getInRange()
const {
576 assert(Opcode == Instruction::GetElementPtr);
585class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
587 Module *TheModule =
nullptr;
588 std::optional<Triple> TargetTriple;
593 bool SeenValueSymbolTable =
false;
596 std::vector<std::string> SectionTable;
597 std::vector<std::string> GCTable;
599 std::vector<Type *> TypeList;
603 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
610 DenseMap<std::pair<Type *, unsigned>,
unsigned> VirtualTypeIDs;
611 DenseMap<Function *, unsigned> FunctionTypeIDs;
616 BitcodeReaderValueList ValueList;
617 std::optional<MetadataLoader> MDLoader;
618 std::vector<Comdat *> ComdatList;
619 DenseSet<GlobalObject *> ImplicitComdatObjects;
622 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
623 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
625 struct FunctionOperandInfo {
627 unsigned PersonalityFn;
631 std::vector<FunctionOperandInfo> FunctionOperands;
635 std::vector<AttributeList> MAttributes;
638 std::map<unsigned, AttributeList> MAttributeGroups;
642 std::vector<BasicBlock*> FunctionBBs;
646 std::vector<Function*> FunctionsWithBodies;
650 DenseMap<Function *, Function *> UpgradedIntrinsics;
655 bool SeenFirstFunctionBody =
false;
659 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
664 std::vector<uint64_t> DeferredMetadataInfo;
669 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
670 std::deque<Function *> BasicBlockFwdRefQueue;
677 std::vector<Function *> BackwardRefFunctions;
685 bool UseRelativeIDs =
false;
689 bool WillMaterializeAllForwardRefs =
false;
693 bool SeenDebugIntrinsic =
false;
694 bool SeenDebugRecord =
false;
697 TBAAVerifier TBAAVerifyHelper;
699 std::vector<std::string> BundleTags;
702 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
705 std::vector<GlobalValue::GUID> GUIDList;
711 bool SkipDebugIntrinsicUpgrade =
false;
714 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
715 StringRef ProducerIdentification, LLVMContext &
Context);
717 Error materializeForwardReferencedFunctions();
719 Error materialize(GlobalValue *GV)
override;
720 Error materializeModule()
override;
721 std::vector<StructType *> getIdentifiedStructTypes()
const override;
725 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
726 bool IsImporting, ParserCallbacks Callbacks = {});
731 Error materializeMetadata()
override;
733 void setStripDebugInfo()
override;
736 std::vector<StructType *> IdentifiedStructTypes;
737 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
738 StructType *createIdentifiedStructType(LLVMContext &
Context);
740 static constexpr unsigned InvalidTypeID = ~0
u;
742 Type *getTypeByID(
unsigned ID);
743 Type *getPtrElementTypeByID(
unsigned ID);
744 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
745 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
748 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
749 Expected<Constant *> getValueForInitializer(
unsigned ID);
751 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
752 BasicBlock *ConstExprInsertBB) {
758 Metadata *getFnMetadataByID(
unsigned ID) {
759 return MDLoader->getMetadataFwdRefOrLoad(ID);
762 BasicBlock *getBasicBlock(
unsigned ID)
const {
763 if (ID >= FunctionBBs.size())
return nullptr;
764 return FunctionBBs[
ID];
768 if (i-1 < MAttributes.size())
769 return MAttributes[i-1];
770 return AttributeList();
776 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
777 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
778 BasicBlock *ConstExprInsertBB) {
779 if (Slot ==
Record.size())
return true;
780 unsigned ValNo = (unsigned)Record[Slot++];
783 ValNo = InstNum - ValNo;
784 if (ValNo < InstNum) {
788 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
790 "Incorrect type ID stored for value");
791 return ResVal ==
nullptr;
793 if (Slot ==
Record.size())
796 TypeID = (unsigned)Record[Slot++];
797 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
799 return ResVal ==
nullptr;
802 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
803 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
804 BasicBlock *ConstExprInsertBB) {
805 if (Slot ==
Record.size())
810 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
813 if (Slot ==
Record.size())
815 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
823 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
824 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
825 BasicBlock *ConstExprInsertBB) {
826 if (
getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
834 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
835 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
836 BasicBlock *ConstExprInsertBB) {
837 ResVal =
getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
838 return ResVal ==
nullptr;
843 Value *
getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
844 unsigned InstNum,
Type *Ty,
unsigned TyID,
845 BasicBlock *ConstExprInsertBB) {
846 if (Slot ==
Record.size())
return nullptr;
847 unsigned ValNo = (unsigned)Record[Slot];
850 ValNo = InstNum - ValNo;
851 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
855 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
856 unsigned InstNum,
Type *Ty,
unsigned TyID,
857 BasicBlock *ConstExprInsertBB) {
858 if (Slot ==
Record.size())
return nullptr;
859 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
862 ValNo = InstNum - ValNo;
863 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
866 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
869 if (
Record.size() - OpNum < 2)
870 return error(
"Too few records for range");
872 unsigned LowerActiveWords =
Record[OpNum];
873 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
874 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
875 return error(
"Too few records for range");
878 OpNum += LowerActiveWords;
881 OpNum += UpperActiveWords;
884 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
885 int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
886 return ConstantRange(APInt(
BitWidth, Start,
true),
891 Expected<ConstantRange>
892 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
893 if (
Record.size() - OpNum < 1)
894 return error(
"Too few records for range");
896 return readConstantRange(Record, OpNum,
BitWidth);
900 const Triple &getTargetTriple() {
902 BitstreamCursor TripleStream(Stream.getBitcodeBytes());
903 if (Expected<std::string> TripleStr =
readTriple(TripleStream))
904 TargetTriple.emplace(std::move(*TripleStr));
907 TargetTriple.emplace();
910 return *TargetTriple;
916 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
922 Error parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind);
924 ParserCallbacks Callbacks = {});
926 Error parseComdatRecord(ArrayRef<uint64_t> Record);
927 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
928 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
929 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
930 ArrayRef<uint64_t> Record);
932 Error parseAttributeBlock();
933 Error parseAttributeGroupBlock();
934 Error parseTypeTable();
935 Error parseTypeTableBody();
936 Error parseOperandBundleTags();
937 Error parseSyncScopeNames();
939 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
940 unsigned NameIndex, Triple &TT);
941 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
Function *
F,
942 ArrayRef<uint64_t> Record);
944 Error parseGlobalValueSymbolTable();
945 Error parseConstants();
946 Error rememberAndSkipFunctionBodies();
947 Error rememberAndSkipFunctionBody();
949 Error rememberAndSkipMetadata();
952 Error globalCleanup();
953 Error resolveGlobalAndIndirectSymbolInits();
954 Error parseUseLists();
955 Error findFunctionInStream(
957 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
964class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
966 ModuleSummaryIndex &TheIndex;
970 bool SeenGlobalValSummary =
false;
973 bool SeenValueSymbolTable =
false;
987 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
988 ValueIdToValueInfoMap;
994 DenseMap<uint64_t, StringRef> ModuleIdMap;
997 std::string SourceFileName;
1001 StringRef ModulePath;
1005 std::function<bool(StringRef)> IsPrevailing =
nullptr;
1008 std::function<void(ValueInfo)> OnValueInfo =
nullptr;
1012 std::vector<uint64_t> StackIds;
1016 std::vector<uint64_t> RadixArray;
1021 std::vector<unsigned> StackIdToIndex;
1024 std::vector<uint64_t> DefinedGUIDs;
1027 ModuleSummaryIndexBitcodeReader(
1028 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
1029 StringRef ModulePath,
1030 std::function<
bool(StringRef)> IsPrevailing =
nullptr,
1031 std::function<
void(ValueInfo)> OnValueInfo =
nullptr);
1038 StringRef SourceFileName);
1039 Error parseValueSymbolTable(
1041 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1044 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1045 bool HasProfile,
bool HasRelBF);
1046 Error parseEntireSummary(
unsigned ID);
1047 Error parseModuleStringTable();
1048 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1049 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1051 std::vector<FunctionSummary::ParamAccess>
1052 parseParamAccesses(ArrayRef<uint64_t> Record);
1053 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1057 static constexpr unsigned UninitializedStackIdIndex =
1058 std::numeric_limits<unsigned>::max();
1060 unsigned getStackIdIndex(
unsigned LocalIndex) {
1061 unsigned &
Index = StackIdToIndex[LocalIndex];
1064 if (Index == UninitializedStackIdIndex)
1069 template <
bool AllowNullValueInfo = false>
1070 std::pair<ValueInfo, GlobalValue::GUID>
1071 getValueInfoFromValueId(
unsigned ValueId);
1073 void addThisModule();
1089 return std::error_code();
1095 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1096 ValueList(this->Stream.SizeInBytes(),
1098 return materializeValue(
ValID, InsertBB);
1100 this->ProducerIdentification = std::string(ProducerIdentification);
1103Error BitcodeReader::materializeForwardReferencedFunctions() {
1104 if (WillMaterializeAllForwardRefs)
1108 WillMaterializeAllForwardRefs =
true;
1110 while (!BasicBlockFwdRefQueue.empty()) {
1111 Function *
F = BasicBlockFwdRefQueue.front();
1112 BasicBlockFwdRefQueue.pop_front();
1113 assert(
F &&
"Expected valid function");
1114 if (!BasicBlockFwdRefs.
count(
F))
1122 if (!
F->isMaterializable())
1123 return error(
"Never resolved function from blockaddress");
1126 if (
Error Err = materialize(
F))
1129 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1131 for (
Function *
F : BackwardRefFunctions)
1132 if (
Error Err = materialize(
F))
1134 BackwardRefFunctions.clear();
1137 WillMaterializeAllForwardRefs =
false;
1202 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1203 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1204 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1205 Flags.NoInline = (RawFlags >> 4) & 0x1;
1206 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1207 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1208 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1209 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1210 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1226 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1);
1227 RawFlags = RawFlags >> 4;
1228 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1232 bool Live = (RawFlags & 0x2) || Version < 3;
1233 bool Local = (RawFlags & 0x4);
1234 bool AutoHide = (RawFlags & 0x8);
1237 Live,
Local, AutoHide, IK,
1238 NoRenameOnPromotion);
1244 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1245 (RawFlags & 0x4) ?
true :
false,
1249static std::pair<CalleeInfo::HotnessType, bool>
1253 bool HasTailCall = (RawFlags & 0x8);
1254 return {Hotness, HasTailCall};
1259 bool &HasTailCall) {
1260 static constexpr unsigned RelBlockFreqBits = 28;
1261 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1262 RelBF = RawFlags & RelBlockFreqMask;
1263 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1288 case 0:
return false;
1289 case 1:
return true;
1351 bool IsFP = Ty->isFPOrFPVectorTy();
1353 if (!IsFP && !Ty->isIntOrIntVectorTy())
1360 return IsFP ? Instruction::FNeg : -1;
1365 bool IsFP = Ty->isFPOrFPVectorTy();
1367 if (!IsFP && !Ty->isIntOrIntVectorTy())
1374 return IsFP ? Instruction::FAdd : Instruction::Add;
1376 return IsFP ? Instruction::FSub : Instruction::Sub;
1378 return IsFP ? Instruction::FMul : Instruction::Mul;
1380 return IsFP ? -1 : Instruction::UDiv;
1382 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1384 return IsFP ? -1 : Instruction::URem;
1386 return IsFP ? Instruction::FRem : Instruction::SRem;
1388 return IsFP ? -1 : Instruction::Shl;
1390 return IsFP ? -1 : Instruction::LShr;
1392 return IsFP ? -1 : Instruction::AShr;
1394 return IsFP ? -1 : Instruction::And;
1396 return IsFP ? -1 : Instruction::Or;
1398 return IsFP ? -1 : Instruction::Xor;
1403 bool &IsElementwise) {
1501Type *BitcodeReader::getTypeByID(
unsigned ID) {
1503 if (ID >= TypeList.size())
1506 if (
Type *Ty = TypeList[ID])
1511 return TypeList[
ID] = createIdentifiedStructType(
Context);
1514unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1515 auto It = ContainedTypeIDs.
find(ID);
1516 if (It == ContainedTypeIDs.
end())
1517 return InvalidTypeID;
1519 if (Idx >= It->second.size())
1520 return InvalidTypeID;
1522 return It->second[Idx];
1525Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1526 if (ID >= TypeList.size())
1533 return getTypeByID(getContainedTypeID(ID, 0));
1536unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1537 ArrayRef<unsigned> ChildTypeIDs) {
1538 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1539 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1540 auto It = VirtualTypeIDs.
find(CacheKey);
1541 if (It != VirtualTypeIDs.
end()) {
1547 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1548 "Incorrect cached contained type IDs");
1552 unsigned TypeID = TypeList.size();
1553 TypeList.push_back(Ty);
1554 if (!ChildTypeIDs.
empty())
1575 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1589 if (Opcode == Instruction::GetElementPtr)
1593 case Instruction::FNeg:
1594 case Instruction::Select:
1595 case Instruction::ICmp:
1596 case Instruction::FCmp:
1603Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1604 BasicBlock *InsertBB) {
1606 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1608 return ValueList[StartValID];
1610 SmallDenseMap<unsigned, Value *> MaterializedValues;
1611 SmallVector<unsigned> Worklist;
1613 while (!Worklist.
empty()) {
1614 unsigned ValID = Worklist.
back();
1615 if (MaterializedValues.
count(ValID)) {
1621 if (ValID >= ValueList.
size() || !ValueList[ValID])
1622 return error(
"Invalid value ID");
1624 Value *
V = ValueList[ValID];
1627 MaterializedValues.
insert({ValID,
V});
1635 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1636 auto It = MaterializedValues.
find(OpID);
1637 if (It != MaterializedValues.
end())
1638 Ops.push_back(It->second);
1645 if (
Ops.size() != BC->getOperandIDs().size())
1647 std::reverse(
Ops.begin(),
Ops.end());
1664 switch (BC->Opcode) {
1665 case BitcodeConstant::ConstantPtrAuthOpcode: {
1668 return error(
"ptrauth key operand must be ConstantInt");
1672 return error(
"ptrauth disc operand must be ConstantInt");
1675 ConstOps.
size() > 4 ? ConstOps[4]
1680 "ptrauth deactivation symbol operand must be a pointer");
1683 DeactivationSymbol);
1686 case BitcodeConstant::NoCFIOpcode: {
1689 return error(
"no_cfi operand must be GlobalValue");
1693 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1696 return error(
"dso_local operand must be GlobalValue");
1700 case BitcodeConstant::BlockAddressOpcode: {
1703 return error(
"blockaddress operand must be a function");
1708 unsigned BBID = BC->BlockAddressBB;
1711 return error(
"Invalid ID");
1714 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1716 return error(
"Invalid ID");
1723 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1725 BasicBlockFwdRefQueue.push_back(Fn);
1726 if (FwdBBs.size() < BBID + 1)
1727 FwdBBs.resize(BBID + 1);
1735 case BitcodeConstant::ConstantStructOpcode: {
1737 if (
ST->getNumElements() != ConstOps.
size())
1738 return error(
"Invalid number of elements in struct initializer");
1740 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1741 if (
Op->getType() != Ty)
1742 return error(
"Incorrect type in struct initializer");
1747 case BitcodeConstant::ConstantArrayOpcode: {
1749 if (AT->getNumElements() != ConstOps.
size())
1750 return error(
"Invalid number of elements in array initializer");
1752 for (Constant *
Op : ConstOps)
1753 if (
Op->getType() != AT->getElementType())
1754 return error(
"Incorrect type in array initializer");
1759 case BitcodeConstant::ConstantVectorOpcode: {
1761 if (VT->getNumElements() != ConstOps.size())
1762 return error(
"Invalid number of elements in vector initializer");
1764 for (Constant *
Op : ConstOps)
1765 if (
Op->getType() != VT->getElementType())
1766 return error(
"Incorrect type in vector initializer");
1771 case Instruction::GetElementPtr:
1774 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1778 case Instruction::ExtractElement:
1781 case Instruction::InsertElement:
1785 case Instruction::ShuffleVector: {
1786 SmallVector<int, 16>
Mask;
1798 MaterializedValues.
insert({ValID,
C});
1804 return error(Twine(
"Value referenced by initializer is an unsupported "
1805 "constant expression of type ") +
1806 BC->getOpcodeName());
1812 BC->getType(),
"constexpr", InsertBB);
1815 "constexpr", InsertBB);
1818 Ops[1],
"constexpr", InsertBB);
1821 I->setHasNoSignedWrap();
1823 I->setHasNoUnsignedWrap();
1829 switch (BC->Opcode) {
1830 case BitcodeConstant::ConstantVectorOpcode: {
1831 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1834 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1841 case BitcodeConstant::ConstantStructOpcode:
1842 case BitcodeConstant::ConstantArrayOpcode: {
1846 "constexpr.ins", InsertBB);
1850 case Instruction::ICmp:
1851 case Instruction::FCmp:
1854 "constexpr", InsertBB);
1856 case Instruction::GetElementPtr:
1862 case Instruction::Select:
1865 case Instruction::ExtractElement:
1868 case Instruction::InsertElement:
1872 case Instruction::ShuffleVector:
1873 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1881 MaterializedValues.
insert({ValID,
I});
1885 return MaterializedValues[StartValID];
1888Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1889 Expected<Value *> MaybeV = materializeValue(ID,
nullptr);
1897StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1900 IdentifiedStructTypes.push_back(Ret);
1904StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1906 IdentifiedStructTypes.push_back(Ret);
1922 case Attribute::ZExt:
return 1 << 0;
1923 case Attribute::SExt:
return 1 << 1;
1924 case Attribute::NoReturn:
return 1 << 2;
1925 case Attribute::InReg:
return 1 << 3;
1926 case Attribute::StructRet:
return 1 << 4;
1927 case Attribute::NoUnwind:
return 1 << 5;
1928 case Attribute::NoAlias:
return 1 << 6;
1929 case Attribute::ByVal:
return 1 << 7;
1930 case Attribute::Nest:
return 1 << 8;
1931 case Attribute::ReadNone:
return 1 << 9;
1932 case Attribute::ReadOnly:
return 1 << 10;
1933 case Attribute::NoInline:
return 1 << 11;
1934 case Attribute::AlwaysInline:
return 1 << 12;
1935 case Attribute::OptimizeForSize:
return 1 << 13;
1936 case Attribute::StackProtect:
return 1 << 14;
1937 case Attribute::StackProtectReq:
return 1 << 15;
1938 case Attribute::Alignment:
return 31 << 16;
1940 case Attribute::NoRedZone:
return 1 << 22;
1941 case Attribute::NoImplicitFloat:
return 1 << 23;
1942 case Attribute::Naked:
return 1 << 24;
1943 case Attribute::InlineHint:
return 1 << 25;
1944 case Attribute::StackAlignment:
return 7 << 26;
1945 case Attribute::ReturnsTwice:
return 1 << 29;
1946 case Attribute::UWTable:
return 1 << 30;
1947 case Attribute::NonLazyBind:
return 1U << 31;
1948 case Attribute::SanitizeAddress:
return 1ULL << 32;
1949 case Attribute::MinSize:
return 1ULL << 33;
1950 case Attribute::NoDuplicate:
return 1ULL << 34;
1951 case Attribute::StackProtectStrong:
return 1ULL << 35;
1952 case Attribute::SanitizeThread:
return 1ULL << 36;
1953 case Attribute::SanitizeMemory:
return 1ULL << 37;
1954 case Attribute::NoBuiltin:
return 1ULL << 38;
1955 case Attribute::Returned:
return 1ULL << 39;
1956 case Attribute::Cold:
return 1ULL << 40;
1957 case Attribute::Builtin:
return 1ULL << 41;
1958 case Attribute::OptimizeNone:
return 1ULL << 42;
1959 case Attribute::InAlloca:
return 1ULL << 43;
1960 case Attribute::NonNull:
return 1ULL << 44;
1961 case Attribute::JumpTable:
return 1ULL << 45;
1962 case Attribute::Convergent:
return 1ULL << 46;
1963 case Attribute::SafeStack:
return 1ULL << 47;
1964 case Attribute::NoRecurse:
return 1ULL << 48;
1967 case Attribute::SwiftSelf:
return 1ULL << 51;
1968 case Attribute::SwiftError:
return 1ULL << 52;
1969 case Attribute::WriteOnly:
return 1ULL << 53;
1970 case Attribute::Speculatable:
return 1ULL << 54;
1971 case Attribute::StrictFP:
return 1ULL << 55;
1972 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1973 case Attribute::NoCfCheck:
return 1ULL << 57;
1974 case Attribute::OptForFuzzing:
return 1ULL << 58;
1975 case Attribute::ShadowCallStack:
return 1ULL << 59;
1976 case Attribute::SpeculativeLoadHardening:
1978 case Attribute::ImmArg:
1980 case Attribute::WillReturn:
1982 case Attribute::NoFree:
1998 if (
I == Attribute::Alignment)
1999 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
2000 else if (
I == Attribute::StackAlignment)
2001 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
2003 B.addTypeAttr(
I,
nullptr);
2017 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
2019 "Alignment must be a power of two.");
2022 B.addAlignmentAttr(Alignment);
2024 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
2025 (EncodedAttrs & 0xffff);
2027 if (AttrIdx == AttributeList::FunctionIndex) {
2030 if (Attrs & (1ULL << 9)) {
2032 Attrs &= ~(1ULL << 9);
2035 if (Attrs & (1ULL << 10)) {
2037 Attrs &= ~(1ULL << 10);
2040 if (Attrs & (1ULL << 49)) {
2042 Attrs &= ~(1ULL << 49);
2045 if (Attrs & (1ULL << 50)) {
2047 Attrs &= ~(1ULL << 50);
2050 if (Attrs & (1ULL << 53)) {
2052 Attrs &= ~(1ULL << 53);
2056 B.addMemoryAttr(ME);
2060 if (Attrs & (1ULL << 21)) {
2061 Attrs &= ~(1ULL << 21);
2068Error BitcodeReader::parseAttributeBlock() {
2072 if (!MAttributes.empty())
2073 return error(
"Invalid multiple blocks");
2075 SmallVector<uint64_t, 64>
Record;
2084 BitstreamEntry
Entry = MaybeEntry.
get();
2086 switch (
Entry.Kind) {
2089 return error(
"Malformed block");
2102 switch (MaybeRecord.
get()) {
2108 return error(
"Invalid parameter attribute record");
2110 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2116 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2121 Attrs.push_back(MAttributeGroups[Val]);
2123 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2136 return Attribute::Alignment;
2138 return Attribute::AlwaysInline;
2140 return Attribute::Builtin;
2142 return Attribute::ByVal;
2144 return Attribute::InAlloca;
2146 return Attribute::Cold;
2148 return Attribute::Convergent;
2150 return Attribute::DisableSanitizerInstrumentation;
2152 return Attribute::ElementType;
2154 return Attribute::FnRetThunkExtern;
2156 return Attribute::Flatten;
2158 return Attribute::HybridPatchable;
2160 return Attribute::InlineHint;
2162 return Attribute::InReg;
2164 return Attribute::JumpTable;
2166 return Attribute::Memory;
2168 return Attribute::NoFPClass;
2170 return Attribute::MinSize;
2172 return Attribute::Naked;
2174 return Attribute::Nest;
2176 return Attribute::NoAlias;
2178 return Attribute::NoBuiltin;
2180 return Attribute::NoCallback;
2182 return Attribute::NoDivergenceSource;
2184 return Attribute::NoDuplicate;
2186 return Attribute::NoFree;
2188 return Attribute::NoFreeObj;
2190 return Attribute::NoImplicitFloat;
2192 return Attribute::NoInline;
2194 return Attribute::NoRecurse;
2196 return Attribute::NoMerge;
2198 return Attribute::NonLazyBind;
2200 return Attribute::NonNull;
2202 return Attribute::Dereferenceable;
2204 return Attribute::DereferenceableOrNull;
2206 return Attribute::AllocAlign;
2208 return Attribute::AllocKind;
2210 return Attribute::AllocSize;
2212 return Attribute::AllocatedPointer;
2214 return Attribute::NoRedZone;
2216 return Attribute::NoReturn;
2218 return Attribute::NoSync;
2220 return Attribute::NoCfCheck;
2222 return Attribute::NoProfile;
2224 return Attribute::SkipProfile;
2226 return Attribute::NoUnwind;
2228 return Attribute::NoSanitizeBounds;
2230 return Attribute::NoSanitizeCoverage;
2232 return Attribute::NullPointerIsValid;
2234 return Attribute::OptimizeForDebugging;
2236 return Attribute::OptForFuzzing;
2238 return Attribute::OptimizeForSize;
2240 return Attribute::OptimizeNone;
2242 return Attribute::ReadNone;
2244 return Attribute::ReadOnly;
2246 return Attribute::Returned;
2248 return Attribute::ReturnsTwice;
2250 return Attribute::SExt;
2252 return Attribute::Speculatable;
2254 return Attribute::StackAlignment;
2256 return Attribute::StackProtect;
2258 return Attribute::StackProtectReq;
2260 return Attribute::StackProtectStrong;
2262 return Attribute::SafeStack;
2264 return Attribute::ShadowCallStack;
2266 return Attribute::StrictFP;
2268 return Attribute::StructRet;
2270 return Attribute::SanitizeAddress;
2272 return Attribute::SanitizeHWAddress;
2274 return Attribute::SanitizeThread;
2276 return Attribute::SanitizeType;
2278 return Attribute::SanitizeMemory;
2280 return Attribute::SanitizeNumericalStability;
2282 return Attribute::SanitizeRealtime;
2284 return Attribute::SanitizeRealtimeBlocking;
2286 return Attribute::SanitizeAllocToken;
2288 return Attribute::SpeculativeLoadHardening;
2290 return Attribute::SwiftError;
2292 return Attribute::SwiftSelf;
2294 return Attribute::SwiftAsync;
2296 return Attribute::UWTable;
2298 return Attribute::VScaleRange;
2300 return Attribute::WillReturn;
2302 return Attribute::WriteOnly;
2304 return Attribute::ZExt;
2306 return Attribute::ImmArg;
2308 return Attribute::SanitizeMemTag;
2310 return Attribute::Preallocated;
2312 return Attribute::NoUndef;
2314 return Attribute::ByRef;
2316 return Attribute::MustProgress;
2318 return Attribute::Hot;
2320 return Attribute::PresplitCoroutine;
2322 return Attribute::Writable;
2324 return Attribute::CoroDestroyOnlyWhenComplete;
2326 return Attribute::DeadOnUnwind;
2328 return Attribute::Range;
2330 return Attribute::Initializes;
2332 return Attribute::CoroElideSafe;
2334 return Attribute::NoExt;
2336 return Attribute::Captures;
2338 return Attribute::DeadOnReturn;
2340 return Attribute::NoCreateUndefOrPoison;
2342 return Attribute::DenormalFPEnv;
2344 return Attribute::NoOutline;
2346 return Attribute::NoIPA;
2351 MaybeAlign &Alignment) {
2354 if (
Exponent > Value::MaxAlignmentExponent + 1)
2355 return error(
"Invalid alignment value");
2360Error BitcodeReader::parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind) {
2362 if (*Kind == Attribute::None)
2363 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2368 switch (EncodedKind) {
2392Error BitcodeReader::parseAttributeGroupBlock() {
2396 if (!MAttributeGroups.empty())
2397 return error(
"Invalid multiple blocks");
2399 SmallVector<uint64_t, 64>
Record;
2406 BitstreamEntry
Entry = MaybeEntry.
get();
2408 switch (
Entry.Kind) {
2411 return error(
"Malformed block");
2424 switch (MaybeRecord.
get()) {
2429 return error(
"Invalid grp record");
2436 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2437 if (Record[i] == 0) {
2438 Attribute::AttrKind
Kind;
2440 if (Idx == AttributeList::FunctionIndex &&
2449 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2455 if (Kind == Attribute::ByVal)
2456 B.addByValAttr(
nullptr);
2457 else if (Kind == Attribute::StructRet)
2458 B.addStructRetAttr(
nullptr);
2459 else if (Kind == Attribute::InAlloca)
2460 B.addInAllocaAttr(
nullptr);
2461 else if (Kind == Attribute::UWTable)
2462 B.addUWTableAttr(UWTableKind::Default);
2463 else if (Kind == Attribute::DeadOnReturn)
2464 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2465 else if (Attribute::isEnumAttrKind(Kind))
2466 B.addAttribute(Kind);
2468 return error(
"Not an enum attribute");
2469 }
else if (Record[i] == 1) {
2470 Attribute::AttrKind
Kind;
2471 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2473 if (!Attribute::isIntAttrKind(Kind))
2474 return error(
"Not an int attribute");
2475 if (Kind == Attribute::Alignment)
2476 B.addAlignmentAttr(Record[++i]);
2477 else if (Kind == Attribute::StackAlignment)
2478 B.addStackAlignmentAttr(Record[++i]);
2479 else if (Kind == Attribute::Dereferenceable)
2480 B.addDereferenceableAttr(Record[++i]);
2481 else if (Kind == Attribute::DereferenceableOrNull)
2482 B.addDereferenceableOrNullAttr(Record[++i]);
2483 else if (Kind == Attribute::DeadOnReturn)
2484 B.addDeadOnReturnAttr(
2486 else if (Kind == Attribute::AllocSize)
2487 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2488 else if (Kind == Attribute::VScaleRange)
2489 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2490 else if (Kind == Attribute::UWTable)
2492 else if (Kind == Attribute::AllocKind)
2493 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2494 else if (Kind == Attribute::Memory) {
2496 const uint8_t
Version = (EncodedME >> 56);
2510 if (getTargetTriple().isAArch64())
2515 B.addMemoryAttr(ME);
2520 EncodedME & 0x00FFFFFFFFFFFFFFULL);
2523 if (
Version == 1 && getTargetTriple().isAArch64())
2525 IRMemLocation::TargetMem0,
2526 ME.
getModRef(IRMemLocation::InaccessibleMem)) |
2528 IRMemLocation::TargetMem1,
2529 ME.
getModRef(IRMemLocation::InaccessibleMem));
2530 B.addMemoryAttr(ME);
2532 }
else if (Kind == Attribute::Captures)
2534 else if (Kind == Attribute::NoFPClass)
2537 else if (Kind == Attribute::DenormalFPEnv) {
2538 B.addDenormalFPEnvAttr(
2541 }
else if (Record[i] == 3 || Record[i] == 4) {
2543 SmallString<64> KindStr;
2544 SmallString<64> ValStr;
2546 while (Record[i] != 0 && i != e)
2548 assert(Record[i] == 0 &&
"Kind string not null terminated");
2553 while (Record[i] != 0 && i != e)
2555 assert(Record[i] == 0 &&
"Value string not null terminated");
2558 B.addAttribute(KindStr.
str(), ValStr.
str());
2559 }
else if (Record[i] == 5 || Record[i] == 6) {
2560 bool HasType =
Record[i] == 6;
2561 Attribute::AttrKind
Kind;
2562 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2564 if (!Attribute::isTypeAttrKind(Kind))
2565 return error(
"Not a type attribute");
2567 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2568 }
else if (Record[i] == 7) {
2569 Attribute::AttrKind
Kind;
2572 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2574 if (!Attribute::isConstantRangeAttrKind(Kind))
2575 return error(
"Not a ConstantRange attribute");
2577 Expected<ConstantRange> MaybeCR =
2578 readBitWidthAndConstantRange(Record, i);
2583 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2584 }
else if (Record[i] == 8) {
2585 Attribute::AttrKind
Kind;
2588 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2590 if (!Attribute::isConstantRangeListAttrKind(Kind))
2591 return error(
"Not a constant range list attribute");
2595 return error(
"Too few records for constant range list");
2596 unsigned RangeSize =
Record[i++];
2598 for (
unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2599 Expected<ConstantRange> MaybeCR =
2600 readConstantRange(Record, i,
BitWidth);
2608 return error(
"Invalid (unordered or overlapping) range list");
2609 B.addConstantRangeListAttr(Kind, Val);
2611 return error(
"Invalid attribute group entry");
2616 B.addMemoryAttr(ME);
2619 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2626Error BitcodeReader::parseTypeTable() {
2630 return parseTypeTableBody();
2633Error BitcodeReader::parseTypeTableBody() {
2634 if (!TypeList.empty())
2635 return error(
"Invalid multiple blocks");
2637 SmallVector<uint64_t, 64>
Record;
2638 unsigned NumRecords = 0;
2647 BitstreamEntry
Entry = MaybeEntry.
get();
2649 switch (
Entry.Kind) {
2652 return error(
"Malformed block");
2654 if (NumRecords != TypeList.size())
2655 return error(
"Malformed block");
2664 Type *ResultTy =
nullptr;
2665 SmallVector<unsigned> ContainedIDs;
2669 switch (MaybeRecord.
get()) {
2671 return error(
"Invalid value");
2676 return error(
"Invalid numentry record");
2677 TypeList.resize(Record[0]);
2680 ResultTy = Type::getVoidTy(
Context);
2683 ResultTy = Type::getHalfTy(
Context);
2686 ResultTy = Type::getBFloatTy(
Context);
2689 ResultTy = Type::getFloatTy(
Context);
2692 ResultTy = Type::getDoubleTy(
Context);
2695 ResultTy = Type::getX86_FP80Ty(
Context);
2698 ResultTy = Type::getFP128Ty(
Context);
2701 ResultTy = Type::getPPC_FP128Ty(
Context);
2704 ResultTy = Type::getLabelTy(
Context);
2707 ResultTy = Type::getMetadataTy(
Context);
2715 ResultTy = Type::getX86_AMXTy(
Context);
2718 ResultTy = Type::getTokenTy(
Context);
2722 return error(
"Invalid record");
2727 return error(
"Bitwidth for byte type out of range");
2733 return error(
"Invalid integer record");
2738 return error(
"Bitwidth for integer type out of range");
2745 return error(
"Invalid pointer record");
2749 ResultTy = getTypeByID(Record[0]);
2751 !PointerType::isValidElementType(ResultTy))
2752 return error(
"Invalid type");
2759 return error(
"Invalid opaque pointer record");
2768 return error(
"Invalid function record");
2770 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2771 if (
Type *
T = getTypeByID(Record[i]))
2777 ResultTy = getTypeByID(Record[2]);
2778 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2779 return error(
"Invalid type");
2782 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2788 return error(
"Invalid function record");
2790 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2791 if (
Type *
T = getTypeByID(Record[i])) {
2792 if (!FunctionType::isValidArgumentType(
T))
2793 return error(
"Invalid function argument type");
2800 ResultTy = getTypeByID(Record[1]);
2801 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2802 return error(
"Invalid type");
2805 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2810 return error(
"Invalid anon struct record");
2812 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2813 if (
Type *
T = getTypeByID(Record[i]))
2819 return error(
"Invalid type");
2826 return error(
"Invalid struct name record");
2831 return error(
"Invalid named struct record");
2833 if (NumRecords >= TypeList.size())
2834 return error(
"Invalid TYPE table");
2840 TypeList[NumRecords] =
nullptr;
2842 Res = createIdentifiedStructType(
Context, TypeName);
2846 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2847 if (
Type *
T = getTypeByID(Record[i]))
2853 return error(
"Invalid named struct record");
2862 return error(
"Invalid opaque type record");
2864 if (NumRecords >= TypeList.size())
2865 return error(
"Invalid TYPE table");
2871 TypeList[NumRecords] =
nullptr;
2873 Res = createIdentifiedStructType(
Context, TypeName);
2880 return error(
"Invalid target extension type record");
2882 if (NumRecords >= TypeList.size())
2883 return error(
"Invalid TYPE table");
2885 if (Record[0] >=
Record.size())
2886 return error(
"Too many type parameters");
2888 unsigned NumTys =
Record[0];
2890 SmallVector<unsigned, 8> IntParams;
2891 for (
unsigned i = 0; i < NumTys; i++) {
2892 if (
Type *
T = getTypeByID(Record[i + 1]))
2895 return error(
"Invalid type");
2898 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2899 if (Record[i] > UINT_MAX)
2900 return error(
"Integer parameter too large");
2905 if (
auto E = TTy.takeError())
2913 return error(
"Invalid array type record");
2914 ResultTy = getTypeByID(Record[1]);
2915 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2916 return error(
"Invalid type");
2918 ResultTy = ArrayType::get(ResultTy, Record[0]);
2923 return error(
"Invalid vector type record");
2925 return error(
"Invalid vector length");
2926 ResultTy = getTypeByID(Record[1]);
2927 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2928 return error(
"Invalid type");
2931 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2935 if (NumRecords >= TypeList.size())
2936 return error(
"Invalid TYPE table");
2937 if (TypeList[NumRecords])
2939 "Invalid TYPE table: Only named structs can be forward referenced");
2940 assert(ResultTy &&
"Didn't read a type?");
2941 TypeList[NumRecords] = ResultTy;
2942 if (!ContainedIDs.
empty())
2943 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2948Error BitcodeReader::parseOperandBundleTags() {
2952 if (!BundleTags.empty())
2953 return error(
"Invalid multiple blocks");
2955 SmallVector<uint64_t, 64>
Record;
2961 BitstreamEntry
Entry = MaybeEntry.
get();
2963 switch (
Entry.Kind) {
2966 return error(
"Malformed block");
2980 return error(
"Invalid operand bundle record");
2983 BundleTags.emplace_back();
2985 return error(
"Invalid operand bundle record");
2990Error BitcodeReader::parseSyncScopeNames() {
2995 return error(
"Invalid multiple synchronization scope names blocks");
2997 SmallVector<uint64_t, 64>
Record;
3002 BitstreamEntry
Entry = MaybeEntry.
get();
3004 switch (
Entry.Kind) {
3007 return error(
"Malformed block");
3010 return error(
"Invalid empty synchronization scope names block");
3024 return error(
"Invalid sync scope record");
3026 SmallString<16> SSN;
3028 return error(
"Invalid sync scope record");
3036Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
3037 unsigned NameIndex, Triple &TT) {
3040 return error(
"Invalid record");
3041 unsigned ValueID =
Record[0];
3042 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3043 return error(
"Invalid record");
3044 Value *
V = ValueList[ValueID];
3047 if (NameStr.contains(0))
3048 return error(
"Invalid value name");
3049 V->setName(NameStr);
3051 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
3064 return std::move(JumpFailed);
3070 return error(
"Expected value symbol table subblock");
3074void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
3076 ArrayRef<uint64_t> Record) {
3081 uint64_t FuncBitOffset = FuncWordOffset * 32;
3082 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3086 if (FuncBitOffset > LastFunctionBlockBit)
3087 LastFunctionBlockBit = FuncBitOffset;
3091Error BitcodeReader::parseGlobalValueSymbolTable() {
3092 unsigned FuncBitcodeOffsetDelta =
3098 SmallVector<uint64_t, 64>
Record;
3103 BitstreamEntry
Entry = MaybeEntry.
get();
3105 switch (
Entry.Kind) {
3108 return error(
"Malformed block");
3119 switch (MaybeRecord.
get()) {
3121 unsigned ValueID =
Record[0];
3122 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3123 return error(
"Invalid value reference in symbol table");
3124 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3141 if (!MaybeCurrentBit)
3143 CurrentBit = MaybeCurrentBit.
get();
3146 if (
Error Err = parseGlobalValueSymbolTable())
3167 unsigned FuncBitcodeOffsetDelta =
3173 SmallVector<uint64_t, 64>
Record;
3184 BitstreamEntry
Entry = MaybeEntry.
get();
3186 switch (
Entry.Kind) {
3189 return error(
"Malformed block");
3205 switch (MaybeRecord.
get()) {
3209 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3217 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3225 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3230 return error(
"Invalid bbentry record");
3233 return error(
"Invalid bbentry record");
3255Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3256 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3257 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3258 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3260 GlobalInitWorklist.swap(GlobalInits);
3261 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3262 FunctionOperandWorklist.swap(FunctionOperands);
3264 while (!GlobalInitWorklist.empty()) {
3265 unsigned ValID = GlobalInitWorklist.back().second;
3266 if (ValID >= ValueList.
size()) {
3268 GlobalInits.push_back(GlobalInitWorklist.back());
3270 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3273 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3275 GlobalInitWorklist.pop_back();
3278 while (!IndirectSymbolInitWorklist.empty()) {
3279 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3280 if (ValID >= ValueList.
size()) {
3281 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3283 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3287 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3290 return error(
"Alias and aliasee types don't match");
3295 return error(
"Expected an alias or an ifunc");
3298 IndirectSymbolInitWorklist.pop_back();
3301 while (!FunctionOperandWorklist.empty()) {
3302 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3303 if (
Info.PersonalityFn) {
3304 unsigned ValID =
Info.PersonalityFn - 1;
3305 if (ValID < ValueList.
size()) {
3306 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3309 Info.F->setPersonalityFn(MaybeC.
get());
3310 Info.PersonalityFn = 0;
3314 unsigned ValID =
Info.Prefix - 1;
3315 if (ValID < ValueList.
size()) {
3316 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3319 Info.F->setPrefixData(MaybeC.
get());
3323 if (
Info.Prologue) {
3324 unsigned ValID =
Info.Prologue - 1;
3325 if (ValID < ValueList.
size()) {
3326 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3329 Info.F->setPrologueData(MaybeC.
get());
3333 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3334 FunctionOperands.push_back(Info);
3335 FunctionOperandWorklist.pop_back();
3344 BitcodeReader::decodeSignRotatedValue);
3346 return APInt(TypeBits, Words);
3349Error BitcodeReader::parseConstants() {
3357 unsigned Int32TyID = getVirtualTypeID(CurTy);
3358 unsigned CurTyID = Int32TyID;
3359 Type *CurElemTy =
nullptr;
3360 unsigned NextCstNo = ValueList.
size();
3368 switch (Entry.Kind) {
3371 return error(
"Malformed block");
3373 if (NextCstNo != ValueList.
size())
3374 return error(
"Invalid constant reference");
3385 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
3388 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3398 return error(
"Invalid settype record");
3399 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3400 return error(
"Invalid settype record");
3401 if (TypeList[Record[0]] == VoidType)
3402 return error(
"Invalid constant type");
3404 CurTy = TypeList[CurTyID];
3405 CurElemTy = getPtrElementTypeByID(CurTyID);
3409 return error(
"Invalid type for a constant null value");
3412 return error(
"Invalid type for a constant null value");
3417 return error(
"Invalid integer const record");
3422 return error(
"Invalid wide integer const record");
3425 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3426 V = ConstantInt::get(CurTy, VInt);
3431 return error(
"Invalid byte const record");
3432 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]),
3437 return error(
"Invalid wide byte const record");
3440 APInt VByte =
readWideAPInt(Record, ScalarTy->getBitWidth());
3441 V = ConstantByte::get(CurTy, VByte);
3446 return error(
"Invalid float const record");
3449 if (ScalarTy->isHalfTy())
3450 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3451 APInt(16, (uint16_t)Record[0])));
3452 else if (ScalarTy->isBFloatTy())
3453 V = ConstantFP::get(
3454 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3455 else if (ScalarTy->isFloatTy())
3456 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3457 APInt(32, (uint32_t)Record[0])));
3458 else if (ScalarTy->isDoubleTy())
3459 V = ConstantFP::get(
3460 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3461 else if (ScalarTy->isX86_FP80Ty()) {
3464 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3465 Rearrange[1] =
Record[0] >> 48;
3466 V = ConstantFP::get(
3467 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3468 }
else if (ScalarTy->isFP128Ty())
3469 V = ConstantFP::get(CurTy,
3470 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3471 else if (ScalarTy->isPPC_FP128Ty())
3472 V = ConstantFP::get(
3473 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3481 return error(
"Invalid aggregate record");
3483 SmallVector<unsigned, 16> Elts;
3487 V = BitcodeConstant::create(
3488 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3490 V = BitcodeConstant::create(
Alloc, CurTy,
3491 BitcodeConstant::ConstantArrayOpcode, Elts);
3493 V = BitcodeConstant::create(
3494 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3503 return error(
"Invalid string record");
3513 return error(
"Invalid data record");
3517 return error(
"Invalid type for value");
3520 SmallString<128> RawData;
3523 const char *Src =
reinterpret_cast<const char *
>(&Val);
3525 Src +=
sizeof(
uint64_t) - EltBytes;
3526 RawData.
append(Src, Src + EltBytes);
3531 : ConstantDataArray::getRaw(RawData.str(),
Record.
size(), EltTy);
3536 return error(
"Invalid unary op constexpr record");
3541 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3547 return error(
"Invalid binary op constexpr record");
3553 if (
Record.size() >= 4) {
3554 if (
Opc == Instruction::Add ||
3555 Opc == Instruction::Sub ||
3556 Opc == Instruction::Mul ||
3557 Opc == Instruction::Shl) {
3562 }
else if (
Opc == Instruction::SDiv ||
3563 Opc == Instruction::UDiv ||
3564 Opc == Instruction::LShr ||
3565 Opc == Instruction::AShr) {
3570 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3571 {(unsigned)Record[1], (
unsigned)
Record[2]});
3577 return error(
"Invalid cast constexpr record");
3582 unsigned OpTyID =
Record[1];
3583 Type *OpTy = getTypeByID(OpTyID);
3585 return error(
"Invalid cast constexpr record");
3586 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3598 return error(
"Constant GEP record must have at least two elements");
3600 Type *PointeeType =
nullptr;
3604 PointeeType = getTypeByID(Record[OpNum++]);
3607 std::optional<ConstantRange>
InRange;
3611 unsigned InRangeIndex =
Op >> 1;
3617 Expected<ConstantRange> MaybeInRange =
3618 readBitWidthAndConstantRange(Record, OpNum);
3627 SmallVector<unsigned, 16> Elts;
3628 unsigned BaseTypeID =
Record[OpNum];
3629 while (OpNum !=
Record.size()) {
3630 unsigned ElTyID =
Record[OpNum++];
3631 Type *ElTy = getTypeByID(ElTyID);
3633 return error(
"Invalid getelementptr constexpr record");
3637 if (Elts.
size() < 1)
3638 return error(
"Invalid gep with no operands");
3642 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3643 BaseType = getTypeByID(BaseTypeID);
3648 return error(
"GEP base operand must be pointer or vector of pointer");
3651 PointeeType = getPtrElementTypeByID(BaseTypeID);
3653 return error(
"Missing element type for old-style constant GEP");
3656 V = BitcodeConstant::create(
3658 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3664 return error(
"Invalid select constexpr record");
3666 V = BitcodeConstant::create(
3667 Alloc, CurTy, Instruction::Select,
3668 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3674 return error(
"Invalid extractelement constexpr record");
3675 unsigned OpTyID =
Record[0];
3679 return error(
"Invalid extractelement constexpr record");
3681 if (
Record.size() == 4) {
3682 unsigned IdxTyID =
Record[2];
3683 Type *IdxTy = getTypeByID(IdxTyID);
3685 return error(
"Invalid extractelement constexpr record");
3691 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3692 {(unsigned)Record[1], IdxRecord});
3698 if (
Record.size() < 3 || !OpTy)
3699 return error(
"Invalid insertelement constexpr record");
3701 if (
Record.size() == 4) {
3702 unsigned IdxTyID =
Record[2];
3703 Type *IdxTy = getTypeByID(IdxTyID);
3705 return error(
"Invalid insertelement constexpr record");
3711 V = BitcodeConstant::create(
3712 Alloc, CurTy, Instruction::InsertElement,
3713 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3718 if (
Record.size() < 3 || !OpTy)
3719 return error(
"Invalid shufflevector constexpr record");
3720 V = BitcodeConstant::create(
3721 Alloc, CurTy, Instruction::ShuffleVector,
3722 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3729 if (
Record.size() < 4 || !RTy || !OpTy)
3730 return error(
"Invalid shufflevector constexpr record");
3731 V = BitcodeConstant::create(
3732 Alloc, CurTy, Instruction::ShuffleVector,
3733 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3738 return error(
"Invalid cmp constexpt record");
3739 unsigned OpTyID =
Record[0];
3740 Type *OpTy = getTypeByID(OpTyID);
3742 return error(
"Invalid cmp constexpr record");
3743 V = BitcodeConstant::create(
3746 : Instruction::ICmp),
3747 (uint8_t)Record[3]},
3748 {(unsigned)Record[1], (
unsigned)
Record[2]});
3755 return error(
"Invalid inlineasm record");
3756 std::string AsmStr, ConstrStr;
3757 bool HasSideEffects =
Record[0] & 1;
3758 bool IsAlignStack =
Record[0] >> 1;
3759 unsigned AsmStrSize =
Record[1];
3760 if (2+AsmStrSize >=
Record.size())
3761 return error(
"Invalid inlineasm record");
3762 unsigned ConstStrSize =
Record[2+AsmStrSize];
3763 if (3+AsmStrSize+ConstStrSize >
Record.size())
3764 return error(
"Invalid inlineasm record");
3766 for (
unsigned i = 0; i != AsmStrSize; ++i)
3767 AsmStr += (
char)
Record[2+i];
3768 for (
unsigned i = 0; i != ConstStrSize; ++i)
3769 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3772 return error(
"Missing element type for old-style inlineasm");
3774 HasSideEffects, IsAlignStack);
3781 return error(
"Invalid inlineasm record");
3782 std::string AsmStr, ConstrStr;
3783 bool HasSideEffects =
Record[0] & 1;
3784 bool IsAlignStack = (
Record[0] >> 1) & 1;
3785 unsigned AsmDialect =
Record[0] >> 2;
3786 unsigned AsmStrSize =
Record[1];
3787 if (2+AsmStrSize >=
Record.size())
3788 return error(
"Invalid inlineasm record");
3789 unsigned ConstStrSize =
Record[2+AsmStrSize];
3790 if (3+AsmStrSize+ConstStrSize >
Record.size())
3791 return error(
"Invalid inlineasm record");
3793 for (
unsigned i = 0; i != AsmStrSize; ++i)
3794 AsmStr += (
char)
Record[2+i];
3795 for (
unsigned i = 0; i != ConstStrSize; ++i)
3796 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3799 return error(
"Missing element type for old-style inlineasm");
3801 HasSideEffects, IsAlignStack,
3808 return error(
"Invalid inlineasm record");
3810 std::string AsmStr, ConstrStr;
3811 bool HasSideEffects =
Record[OpNum] & 1;
3812 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3813 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3814 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3816 unsigned AsmStrSize =
Record[OpNum];
3818 if (OpNum + AsmStrSize >=
Record.size())
3819 return error(
"Invalid inlineasm record");
3820 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3821 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3822 return error(
"Invalid inlineasm record");
3824 for (
unsigned i = 0; i != AsmStrSize; ++i)
3825 AsmStr += (
char)
Record[OpNum + i];
3827 for (
unsigned i = 0; i != ConstStrSize; ++i)
3828 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3831 return error(
"Missing element type for old-style inlineasm");
3833 HasSideEffects, IsAlignStack,
3840 return error(
"Invalid inlineasm record");
3845 return error(
"Invalid inlineasm record");
3846 std::string AsmStr, ConstrStr;
3847 bool HasSideEffects =
Record[OpNum] & 1;
3848 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3849 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3850 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3852 unsigned AsmStrSize =
Record[OpNum];
3854 if (OpNum + AsmStrSize >=
Record.size())
3855 return error(
"Invalid inlineasm record");
3856 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3857 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3858 return error(
"Invalid inlineasm record");
3860 for (
unsigned i = 0; i != AsmStrSize; ++i)
3861 AsmStr += (
char)
Record[OpNum + i];
3863 for (
unsigned i = 0; i != ConstStrSize; ++i)
3864 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3866 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3872 return error(
"Invalid blockaddress record");
3873 unsigned FnTyID =
Record[0];
3874 Type *FnTy = getTypeByID(FnTyID);
3876 return error(
"Invalid blockaddress record");
3877 V = BitcodeConstant::create(
3879 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3885 return error(
"Invalid dso_local record");
3886 unsigned GVTyID =
Record[0];
3887 Type *GVTy = getTypeByID(GVTyID);
3889 return error(
"Invalid dso_local record");
3890 V = BitcodeConstant::create(
3891 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3896 return error(
"Invalid no_cfi record");
3897 unsigned GVTyID =
Record[0];
3898 Type *GVTy = getTypeByID(GVTyID);
3900 return error(
"Invalid no_cfi record");
3901 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3907 return error(
"Invalid ptrauth record");
3909 V = BitcodeConstant::create(
Alloc, CurTy,
3910 BitcodeConstant::ConstantPtrAuthOpcode,
3911 {(unsigned)Record[0], (
unsigned)
Record[1],
3912 (unsigned)Record[2], (
unsigned)
Record[3]});
3917 return error(
"Invalid ptrauth record");
3919 V = BitcodeConstant::create(
3920 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3921 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3922 (
unsigned)
Record[3], (unsigned)Record[4]});
3927 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3934Error BitcodeReader::parseUseLists() {
3939 SmallVector<uint64_t, 64>
Record;
3945 BitstreamEntry
Entry = MaybeEntry.
get();
3947 switch (
Entry.Kind) {
3950 return error(
"Malformed block");
3964 switch (MaybeRecord.
get()) {
3972 if (RecordLength < 3)
3974 return error(
"Invalid uselist record");
3975 unsigned ID =
Record.pop_back_val();
3979 assert(ID < FunctionBBs.size() &&
"Basic block not found");
3980 V = FunctionBBs[
ID];
3984 if (!
V->hasUseList())
3987 unsigned NumUses = 0;
3988 SmallDenseMap<const Use *, unsigned, 16> Order;
3989 for (
const Use &U :
V->materialized_uses()) {
3990 if (++NumUses >
Record.size())
3992 Order[&
U] =
Record[NumUses - 1];
3999 V->sortUseList([&](
const Use &L,
const Use &R) {
4010Error BitcodeReader::rememberAndSkipMetadata() {
4013 DeferredMetadataInfo.push_back(CurBit);
4021Error BitcodeReader::materializeMetadata() {
4022 for (
uint64_t BitPos : DeferredMetadataInfo) {
4026 if (
Error Err = MDLoader->parseModuleMetadata())
4035 NamedMDNode *LinkerOpts =
4037 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
4044 DeferredMetadataInfo.clear();
4048void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
4052Error BitcodeReader::rememberAndSkipFunctionBody() {
4054 if (FunctionsWithBodies.empty())
4055 return error(
"Insufficient function protos");
4057 Function *Fn = FunctionsWithBodies.back();
4058 FunctionsWithBodies.pop_back();
4063 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4064 "Mismatch between VST and scanned function offsets");
4065 DeferredFunctionInfo[Fn] = CurBit;
4073Error BitcodeReader::globalCleanup() {
4075 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4077 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4078 return error(
"Malformed global initializer set");
4083 MDLoader->upgradeDebugIntrinsics(
F);
4087 !SkipDebugIntrinsicUpgrade))
4088 UpgradedIntrinsics[&
F] = NewFn;
4094 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4095 for (GlobalVariable &GV : TheModule->globals())
4097 UpgradedVariables.emplace_back(&GV, Upgraded);
4098 for (
auto &Pair : UpgradedVariables) {
4099 Pair.first->eraseFromParent();
4100 TheModule->insertGlobalVariable(Pair.second);
4103 for (
size_t ValueID = 0; ValueID < GUIDList.size(); ValueID++) {
4104 const auto GUID = GUIDList[ValueID];
4108 const auto *
Value = ValueList[ValueID];
4109 TheModule->insertGUID(
Value, GUID);
4114 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4115 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4123Error BitcodeReader::rememberAndSkipFunctionBodies() {
4128 return error(
"Could not find function in stream");
4130 if (!SeenFirstFunctionBody)
4131 return error(
"Trying to materialize functions before seeing function blocks");
4135 assert(SeenValueSymbolTable);
4138 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4141 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4143 switch (
Entry.Kind) {
4145 return error(
"Expect SubBlock");
4149 return error(
"Expect function block");
4151 if (
Error Err = rememberAndSkipFunctionBody())
4160Error BitcodeReaderBase::readBlockInfo() {
4161 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4163 if (!MaybeNewBlockInfo)
4165 std::optional<BitstreamBlockInfo> NewBlockInfo =
4166 std::move(MaybeNewBlockInfo.
get());
4168 return error(
"Malformed block");
4169 BlockInfo = std::move(*NewBlockInfo);
4173Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4177 std::tie(Name, Record) = readNameFromStrtab(Record);
4180 return error(
"Invalid comdat record");
4182 std::string OldFormatName;
4185 return error(
"Invalid comdat record");
4186 unsigned ComdatNameSize =
Record[1];
4187 if (ComdatNameSize >
Record.size() - 2)
4188 return error(
"Comdat name size too large");
4189 OldFormatName.reserve(ComdatNameSize);
4190 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4191 OldFormatName += (
char)
Record[2 + i];
4192 Name = OldFormatName;
4194 Comdat *
C = TheModule->getOrInsertComdat(Name);
4195 C->setSelectionKind(SK);
4196 ComdatList.push_back(
C);
4210 Meta.NoAddress =
true;
4212 Meta.NoHWAddress =
true;
4216 Meta.IsDynInit =
true;
4220Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4228 std::tie(Name, Record) = readNameFromStrtab(Record);
4231 return error(
"Invalid global variable record");
4232 unsigned TyID =
Record[0];
4233 Type *Ty = getTypeByID(TyID);
4235 return error(
"Invalid global variable record");
4237 bool explicitType =
Record[1] & 2;
4243 return error(
"Invalid type for value");
4245 TyID = getContainedTypeID(TyID);
4246 Ty = getTypeByID(TyID);
4248 return error(
"Missing element type for old-style global");
4254 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4258 if (Record[5] - 1 >= SectionTable.size())
4259 return error(
"Invalid ID");
4268 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4276 bool ExternallyInitialized =
false;
4278 ExternallyInitialized =
Record[9];
4280 GlobalVariable *NewGV =
4290 if (
Record.size() > 10) {
4302 if (
unsigned InitID = Record[2])
4303 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4305 if (
Record.size() > 11) {
4306 if (
unsigned ComdatID = Record[11]) {
4307 if (ComdatID > ComdatList.size())
4308 return error(
"Invalid global variable comdat ID");
4309 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4312 ImplicitComdatObjects.
insert(NewGV);
4315 if (
Record.size() > 12) {
4320 if (
Record.size() > 13) {
4329 if (
Record.size() > 16 && Record[16]) {
4330 llvm::GlobalValue::SanitizerMetadata
Meta =
4335 if (
Record.size() > 17 && Record[17]) {
4339 return error(
"Invalid global variable code model");
4345void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4346 if (ValueTypeCallback) {
4347 (*ValueTypeCallback)(
4348 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4349 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4353Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4359 std::tie(Name, Record) = readNameFromStrtab(Record);
4362 return error(
"Invalid function record");
4363 unsigned FTyID =
Record[0];
4364 Type *FTy = getTypeByID(FTyID);
4366 return error(
"Invalid function record");
4368 FTyID = getContainedTypeID(FTyID, 0);
4369 FTy = getTypeByID(FTyID);
4371 return error(
"Missing element type for old-style function");
4375 return error(
"Invalid type for value");
4376 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4377 if (CC & ~CallingConv::MaxID)
4378 return error(
"Invalid calling convention ID");
4380 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4386 AddrSpace, Name, TheModule);
4389 "Incorrect fully specified type provided for function");
4390 FunctionTypeIDs[
Func] = FTyID;
4392 Func->setCallingConv(CC);
4393 bool isProto =
Record[2];
4397 callValueTypeCallback(Func, FTyID);
4402 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4403 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4404 Attribute::InAlloca}) {
4405 if (!
Func->hasParamAttribute(i, Kind))
4408 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4411 Func->removeParamAttr(i, Kind);
4413 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4414 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4416 return error(
"Missing param element type for attribute upgrade");
4420 case Attribute::ByVal:
4421 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4423 case Attribute::StructRet:
4424 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4426 case Attribute::InAlloca:
4427 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4433 Func->addParamAttr(i, NewAttr);
4437 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4438 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4439 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4440 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4442 return error(
"Missing param element type for x86_intrcc upgrade");
4444 Func->addParamAttr(0, NewAttr);
4448 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4451 Func->setAlignment(*Alignment);
4453 if (Record[6] - 1 >= SectionTable.size())
4454 return error(
"Invalid ID");
4455 Func->setSection(SectionTable[Record[6] - 1]);
4459 if (!
Func->hasLocalLinkage())
4461 if (
Record.size() > 8 && Record[8]) {
4462 if (Record[8] - 1 >= GCTable.size())
4463 return error(
"Invalid ID");
4464 Func->setGC(GCTable[Record[8] - 1]);
4469 Func->setUnnamedAddr(UnnamedAddr);
4471 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4473 OperandInfo.Prologue =
Record[10];
4475 if (
Record.size() > 11) {
4477 if (!
Func->hasLocalLinkage()) {
4484 if (
Record.size() > 12) {
4485 if (
unsigned ComdatID = Record[12]) {
4486 if (ComdatID > ComdatList.size())
4487 return error(
"Invalid function comdat ID");
4488 Func->setComdat(ComdatList[ComdatID - 1]);
4491 ImplicitComdatObjects.
insert(Func);
4495 OperandInfo.Prefix =
Record[13];
4498 OperandInfo.PersonalityFn =
Record[14];
4500 if (
Record.size() > 15) {
4510 Record[17] + Record[18] <= Strtab.
size()) {
4511 Func->setPartition(StringRef(Strtab.
data() + Record[17], Record[18]));
4514 if (
Record.size() > 19) {
4515 MaybeAlign PrefAlignment;
4516 if (
Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4518 Func->setPreferredAlignment(PrefAlignment);
4521 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4523 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4524 FunctionOperands.push_back(OperandInfo);
4529 Func->setIsMaterializable(
true);
4530 FunctionsWithBodies.push_back(Func);
4531 DeferredFunctionInfo[
Func] = 0;
4536Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4537 unsigned BitCode, ArrayRef<uint64_t> Record) {
4547 std::tie(Name, Record) = readNameFromStrtab(Record);
4550 if (
Record.size() < (3 + (
unsigned)NewRecord))
4551 return error(
"Invalid global indirect symbol record");
4556 return error(
"Invalid global indirect symbol record");
4562 return error(
"Invalid type for value");
4563 AddrSpace = PTy->getAddressSpace();
4565 Ty = getTypeByID(
TypeID);
4567 return error(
"Missing element type for old-style indirect symbol");
4569 AddrSpace =
Record[OpNum++];
4572 auto Val =
Record[OpNum++];
4581 nullptr, TheModule);
4585 if (OpNum !=
Record.size()) {
4586 auto VisInd = OpNum++;
4592 if (OpNum !=
Record.size()) {
4593 auto S =
Record[OpNum++];
4600 if (OpNum !=
Record.size())
4602 if (OpNum !=
Record.size())
4605 if (OpNum !=
Record.size())
4610 if (OpNum + 1 <
Record.size()) {
4612 if (Record[OpNum] + Record[OpNum + 1] > Strtab.
size())
4613 return error(
"Malformed partition, too large.");
4615 StringRef(Strtab.
data() + Record[OpNum], Record[OpNum + 1]));
4619 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4624 bool ShouldLazyLoadMetadata,
4625 ParserCallbacks Callbacks) {
4626 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4633 SmallVector<uint64_t, 64>
Record;
4637 bool ResolvedDataLayout =
false;
4642 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4645 Module::GlobalAsmProperties Props;
4647 auto ResolveDataLayout = [&]() ->
Error {
4648 if (ResolvedDataLayout)
4652 ResolvedDataLayout =
true;
4656 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4660 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4661 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4662 TentativeDataLayoutStr = *LayoutOverride;
4670 TheModule->setDataLayout(MaybeDL.
get());
4676 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4679 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4681 switch (
Entry.Kind) {
4683 return error(
"Malformed block");
4685 if (
Error Err = ResolveDataLayout())
4687 return globalCleanup();
4696 if (
Error Err = readBlockInfo())
4700 if (
Error Err = parseAttributeBlock())
4704 if (
Error Err = parseAttributeGroupBlock())
4708 if (
Error Err = parseTypeTable())
4712 if (!SeenValueSymbolTable) {
4718 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4719 if (
Error Err = parseValueSymbolTable())
4721 SeenValueSymbolTable =
true;
4731 if (
Error Err = parseConstants())
4733 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4737 if (ShouldLazyLoadMetadata) {
4738 if (
Error Err = rememberAndSkipMetadata())
4742 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4743 if (
Error Err = MDLoader->parseModuleMetadata())
4747 if (
Error Err = MDLoader->parseMetadataKinds())
4751 if (
Error Err = ResolveDataLayout())
4756 if (!SeenFirstFunctionBody) {
4757 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4758 if (
Error Err = globalCleanup())
4760 SeenFirstFunctionBody =
true;
4763 if (VSTOffset > 0) {
4767 if (!SeenValueSymbolTable) {
4768 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4770 SeenValueSymbolTable =
true;
4792 if (
Error Err = rememberAndSkipFunctionBody())
4799 if (SeenValueSymbolTable) {
4803 return globalCleanup();
4807 if (
Error Err = parseUseLists())
4811 if (
Error Err = parseOperandBundleTags())
4815 if (
Error Err = parseSyncScopeNames())
4827 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
4830 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4833 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4836 UseRelativeIDs = *VersionOrErr >= 1;
4840 if (ResolvedDataLayout)
4841 return error(
"target triple too late in module");
4844 return error(
"Invalid triple record");
4845 TheModule->setTargetTriple(Triple(std::move(S)));
4849 if (ResolvedDataLayout)
4850 return error(
"datalayout too late in module");
4852 return error(
"Invalid data layout record");
4858 return error(
"Invalid module asm record");
4859 size_t SepPos = Str.find(
'\0');
4860 if (SepPos == std::string::npos)
4861 return error(
"Invalid module asm record");
4862 if (!Props.
set(StringRef(Str.data(), SepPos), Str.substr(SepPos + 1)))
4863 return error(
"Unknown module asm property");
4869 return error(
"Invalid asm record");
4870 TheModule->appendModuleInlineAsm(Module::GlobalAsmFragment(S, Props));
4878 return error(
"Invalid deplib record");
4885 return error(
"Invalid section name record");
4886 SectionTable.push_back(S);
4892 return error(
"Invalid gcname record");
4893 GCTable.push_back(S);
4897 if (
Error Err = parseComdatRecord(Record))
4906 if (
Error Err = parseGlobalVarRecord(Record))
4910 if (
Error Err = ResolveDataLayout())
4912 if (
Error Err = parseFunctionRecord(Record))
4918 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4924 return error(
"Invalid vstoffset record");
4928 VSTOffset =
Record[0] - 1;
4933 GUIDList.reserve(GUIDList.size() +
Record.size() / 2);
4934 for (
size_t i = 0; i <
Record.size(); i += 2)
4935 GUIDList.push_back(Record[i] << 32 | Record[i + 1]);
4941 return error(
"Invalid source filename record");
4942 TheModule->setSourceFileName(
ValueName);
4948 this->ValueTypeCallback = std::nullopt;
4952Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4954 ParserCallbacks Callbacks) {
4956 MetadataLoaderCallbacks MDCallbacks;
4957 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(ID); };
4959 return getContainedTypeID(
I, J);
4962 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4964 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4967Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4969 return error(
"Load/Store operand is not a pointer type");
4970 if (!PointerType::isLoadableOrStorableType(ValType))
4971 return error(
"Cannot load/store from pointer");
4975Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4976 ArrayRef<unsigned> ArgTyIDs) {
4978 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4979 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4980 Attribute::InAlloca}) {
4981 if (!
Attrs.hasParamAttr(i, Kind) ||
4982 Attrs.getParamAttr(i, Kind).getValueAsType())
4985 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4987 return error(
"Missing element type for typed attribute upgrade");
4991 case Attribute::ByVal:
4992 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4994 case Attribute::StructRet:
4995 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4997 case Attribute::InAlloca:
4998 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
5011 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
5015 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
5016 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5018 return error(
"Missing element type for inline asm upgrade");
5021 Attribute::get(
Context, Attribute::ElementType, ElemTy));
5029 case Intrinsic::preserve_array_access_index:
5030 case Intrinsic::preserve_struct_access_index:
5031 case Intrinsic::aarch64_ldaxr:
5032 case Intrinsic::aarch64_ldxr:
5033 case Intrinsic::aarch64_stlxr:
5034 case Intrinsic::aarch64_stxr:
5035 case Intrinsic::arm_ldaex:
5036 case Intrinsic::arm_ldrex:
5037 case Intrinsic::arm_stlex:
5038 case Intrinsic::arm_strex: {
5041 case Intrinsic::aarch64_stlxr:
5042 case Intrinsic::aarch64_stxr:
5043 case Intrinsic::arm_stlex:
5044 case Intrinsic::arm_strex:
5051 if (!
Attrs.getParamElementType(ArgNo)) {
5052 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5054 return error(
"Missing element type for elementtype upgrade");
5074 if (MDLoader->hasFwdRefs())
5075 return error(
"Invalid function metadata: incoming forward references");
5077 InstructionList.
clear();
5078 unsigned ModuleValueListSize = ValueList.
size();
5079 unsigned ModuleMDLoaderSize = MDLoader->size();
5083 unsigned FTyID = FunctionTypeIDs[
F];
5084 for (Argument &
I :
F->args()) {
5085 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
5086 assert(
I.getType() == getTypeByID(ArgTyID) &&
5087 "Incorrect fully specified type for Function Argument");
5091 unsigned NextValueNo = ValueList.
size();
5093 unsigned CurBBNo = 0;
5098 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
5102 auto getLastInstruction = [&]() -> Instruction * {
5103 if (CurBB && !CurBB->
empty())
5104 return &CurBB->
back();
5105 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5106 !FunctionBBs[CurBBNo - 1]->
empty())
5107 return &FunctionBBs[CurBBNo - 1]->back();
5111 std::vector<OperandBundleDef> OperandBundles;
5114 SmallVector<uint64_t, 64>
Record;
5117 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
5120 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
5122 switch (
Entry.Kind) {
5124 return error(
"Malformed block");
5126 goto OutOfRecordLoop;
5135 if (
Error Err = parseConstants())
5137 NextValueNo = ValueList.
size();
5140 if (
Error Err = parseValueSymbolTable())
5144 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5148 assert(DeferredMetadataInfo.empty() &&
5149 "Must read all module-level metadata before function-level");
5150 if (
Error Err = MDLoader->parseFunctionMetadata())
5154 if (
Error Err = parseUseLists())
5168 unsigned ResTypeID = InvalidTypeID;
5169 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
5172 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5174 return error(
"Invalid value");
5176 if (
Record.empty() || Record[0] == 0)
5177 return error(
"Invalid declareblocks record");
5179 FunctionBBs.resize(Record[0]);
5182 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5183 if (BBFRI == BasicBlockFwdRefs.
end()) {
5184 for (BasicBlock *&BB : FunctionBBs)
5187 auto &BBRefs = BBFRI->second;
5189 if (BBRefs.size() > FunctionBBs.size())
5190 return error(
"Invalid ID");
5191 assert(!BBRefs.empty() &&
"Unexpected empty array");
5192 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5193 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5195 if (
I < RE && BBRefs[
I]) {
5196 BBRefs[
I]->insertInto(
F);
5197 FunctionBBs[
I] = BBRefs[
I];
5203 BasicBlockFwdRefs.
erase(BBFRI);
5206 CurBB = FunctionBBs[0];
5213 return error(
"Invalid blockaddr users record");
5229 BackwardRefFunctions.push_back(
F);
5231 return error(
"Invalid blockaddr users record");
5238 I = getLastInstruction();
5241 return error(
"Invalid debug_loc_again record");
5242 I->setDebugLoc(LastLoc);
5247 I = getLastInstruction();
5249 return error(
"Invalid debug loc record");
5257 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5260 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5262 return error(
"Invalid debug loc record");
5266 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5268 return error(
"Invalid debug loc record");
5271 if (
Record.size() >= 8 && Record[7])
5272 IRLayers = MDLoader->getMetadataFwdRefOrLoad(Record[7] - 1);
5274 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5275 isImplicitCode, AtomGroup, AtomRank, IRLayers);
5276 I->setDebugLoc(LastLoc);
5284 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5286 return error(
"Invalid unary operator record");
5290 return error(
"Invalid unary operator record");
5294 if (OpNum <
Record.size()) {
5298 I->setFastMathFlags(FMF);
5307 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5311 return error(
"Invalid binary operator record");
5315 return error(
"Invalid binary operator record");
5319 if (OpNum <
Record.size()) {
5320 if (
Opc == Instruction::Add ||
5321 Opc == Instruction::Sub ||
5322 Opc == Instruction::Mul ||
5323 Opc == Instruction::Shl) {
5328 }
else if (
Opc == Instruction::SDiv ||
5329 Opc == Instruction::UDiv ||
5330 Opc == Instruction::LShr ||
5331 Opc == Instruction::AShr) {
5334 }
else if (
Opc == Instruction::Or) {
5340 I->setFastMathFlags(FMF);
5349 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5350 OpNum + 1 >
Record.size())
5351 return error(
"Invalid cast record");
5353 ResTypeID =
Record[OpNum++];
5354 Type *ResTy = getTypeByID(ResTypeID);
5357 if (
Opc == -1 || !ResTy)
5358 return error(
"Invalid cast record");
5363 assert(CurBB &&
"No current BB?");
5369 return error(
"Invalid cast");
5373 if (OpNum <
Record.size()) {
5374 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5377 }
else if (
Opc == Instruction::Trunc) {
5382 }
else if (
Opc == Instruction::AddrSpaceCast) {
5392 I->setFastMathFlags(FMF);
5411 Ty = getTypeByID(TyID);
5415 TyID = InvalidTypeID;
5420 unsigned BasePtrTypeID;
5421 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5423 return error(
"Invalid gep record");
5426 TyID = getContainedTypeID(BasePtrTypeID);
5427 if (
BasePtr->getType()->isVectorTy())
5428 TyID = getContainedTypeID(TyID);
5429 Ty = getTypeByID(TyID);
5432 SmallVector<Value*, 16> GEPIdx;
5433 while (OpNum !=
Record.size()) {
5436 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5437 return error(
"Invalid gep record");
5448 unsigned SubType = 0;
5449 if (GTI.isStruct()) {
5451 Idx->getType()->isVectorTy()
5453 :
cast<ConstantInt>(Idx);
5456 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5463 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5464 if (
I->getType()->isVectorTy())
5465 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5468 GEP->setNoWrapFlags(NW);
5477 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5478 return error(
"Invalid extractvalue record");
5481 unsigned RecSize =
Record.size();
5482 if (OpNum == RecSize)
5483 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5485 SmallVector<unsigned, 4> EXTRACTVALIdx;
5486 ResTypeID = AggTypeID;
5487 for (; OpNum != RecSize; ++OpNum) {
5492 if (!IsStruct && !IsArray)
5493 return error(
"EXTRACTVAL: Invalid type");
5494 if ((
unsigned)Index != Index)
5495 return error(
"Invalid value");
5497 return error(
"EXTRACTVAL: Invalid struct index");
5499 return error(
"EXTRACTVAL: Invalid array index");
5500 EXTRACTVALIdx.
push_back((
unsigned)Index);
5504 ResTypeID = getContainedTypeID(ResTypeID, Index);
5507 ResTypeID = getContainedTypeID(ResTypeID);
5521 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5522 return error(
"Invalid insertvalue record");
5525 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5526 return error(
"Invalid insertvalue record");
5528 unsigned RecSize =
Record.size();
5529 if (OpNum == RecSize)
5530 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5532 SmallVector<unsigned, 4> INSERTVALIdx;
5534 for (; OpNum != RecSize; ++OpNum) {
5539 if (!IsStruct && !IsArray)
5540 return error(
"INSERTVAL: Invalid type");
5541 if ((
unsigned)Index != Index)
5542 return error(
"Invalid value");
5544 return error(
"INSERTVAL: Invalid struct index");
5546 return error(
"INSERTVAL: Invalid array index");
5548 INSERTVALIdx.
push_back((
unsigned)Index);
5556 return error(
"Inserted value type doesn't match aggregate type");
5559 ResTypeID = AggTypeID;
5571 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5573 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5575 popValue(Record, OpNum, NextValueNo, CondType,
5576 getVirtualTypeID(CondType),
Cond, CurBB))
5577 return error(
"Invalid select record");
5590 unsigned ValTypeID, CondTypeID;
5591 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5593 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5595 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5596 return error(
"Invalid vector select record");
5599 if (VectorType* vector_type =
5602 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5603 return error(
"Invalid type for value");
5607 return error(
"Invalid type for value");
5611 ResTypeID = ValTypeID;
5616 I->setFastMathFlags(FMF);
5624 unsigned VecTypeID, IdxTypeID;
5625 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5626 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5627 return error(
"Invalid extractelement record");
5629 return error(
"Invalid type for value");
5631 ResTypeID = getContainedTypeID(VecTypeID);
5638 Value *Vec, *Elt, *Idx;
5639 unsigned VecTypeID, IdxTypeID;
5640 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5641 return error(
"Invalid insertelement record");
5643 return error(
"Invalid type for value");
5644 if (popValue(Record, OpNum, NextValueNo,
5646 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5647 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5648 return error(
"Invalid insert element record");
5650 ResTypeID = VecTypeID;
5658 unsigned BaseTypeID, ValTypeID, OffsetTypeID;
5659 if (getValueTypePair(Record, OpNum, NextValueNo,
Base, BaseTypeID,
5661 getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB) ||
5662 getValueTypePair(Record, OpNum, NextValueNo,
Offset, OffsetTypeID,
5664 return error(
"Invalid bitinsert record");
5665 if (
const char *Reason =
5667 return error(Reason);
5669 ResTypeID = BaseTypeID;
5677 return error(
"Record is empty for bitextract");
5681 return error(
"Invalid bitextract result type");
5683 unsigned SrcTypeID, OffsetTypeID;
5684 if (getValueTypePair(Record, OpNum, NextValueNo, Src, SrcTypeID, CurBB) ||
5685 getValueTypePair(Record, OpNum, NextValueNo,
Offset, OffsetTypeID,
5687 return error(
"Invalid bitextract record");
5688 if (
const char *Reason =
5690 return error(Reason);
5700 unsigned Vec1TypeID;
5701 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5703 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5705 return error(
"Invalid shufflevector record");
5707 unsigned MaskTypeID;
5708 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5709 return error(
"Invalid shufflevector record");
5711 return error(
"Invalid type for value");
5713 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5715 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5730 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5731 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5733 return error(
"Invalid comparison record");
5735 if (OpNum >=
Record.size())
5737 "Invalid record: operand number exceeded available operands");
5742 if (IsFP &&
Record.size() > OpNum+1)
5747 return error(
"Invalid fcmp predicate");
5748 I =
new FCmpInst(PredVal,
LHS,
RHS);
5751 return error(
"Invalid icmp predicate");
5752 I =
new ICmpInst(PredVal,
LHS,
RHS);
5753 if (
Record.size() > OpNum + 1 &&
5758 if (OpNum + 1 !=
Record.size())
5759 return error(
"Invalid comparison record");
5761 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5763 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5766 I->setFastMathFlags(FMF);
5783 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5784 return error(
"Invalid ret record");
5785 if (OpNum !=
Record.size())
5786 return error(
"Invalid ret record");
5794 return error(
"Invalid br record");
5795 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5797 return error(
"Invalid br record");
5799 if (
Record.size() == 1) {
5804 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5807 getVirtualTypeID(CondType), CurBB);
5808 if (!FalseDest || !
Cond)
5809 return error(
"Invalid br record");
5817 return error(
"Invalid cleanupret record");
5820 Value *CleanupPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5821 getVirtualTypeID(TokenTy), CurBB);
5823 return error(
"Invalid cleanupret record");
5825 if (
Record.size() == 2) {
5826 UnwindDest = getBasicBlock(Record[Idx++]);
5828 return error(
"Invalid cleanupret record");
5837 return error(
"Invalid catchret record");
5840 Value *CatchPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5841 getVirtualTypeID(TokenTy), CurBB);
5843 return error(
"Invalid catchret record");
5844 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5846 return error(
"Invalid catchret record");
5855 return error(
"Invalid catchswitch record");
5860 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5861 getVirtualTypeID(TokenTy), CurBB);
5863 return error(
"Invalid catchswitch record");
5865 unsigned NumHandlers =
Record[Idx++];
5868 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5869 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5871 return error(
"Invalid catchswitch record");
5876 if (Idx + 1 ==
Record.size()) {
5877 UnwindDest = getBasicBlock(Record[Idx++]);
5879 return error(
"Invalid catchswitch record");
5882 if (
Record.size() != Idx)
5883 return error(
"Invalid catchswitch record");
5887 for (BasicBlock *Handler : Handlers)
5888 CatchSwitch->addHandler(Handler);
5890 ResTypeID = getVirtualTypeID(
I->getType());
5898 return error(
"Invalid catchpad/cleanuppad record");
5903 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5904 getVirtualTypeID(TokenTy), CurBB);
5906 return error(
"Invalid catchpad/cleanuppad record");
5908 unsigned NumArgOperands =
Record[Idx++];
5910 SmallVector<Value *, 2>
Args;
5911 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5914 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5915 return error(
"Invalid catchpad/cleanuppad record");
5916 Args.push_back(Val);
5919 if (
Record.size() != Idx)
5920 return error(
"Invalid catchpad/cleanuppad record");
5926 ResTypeID = getVirtualTypeID(
I->getType());
5932 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5938 unsigned OpTyID =
Record[1];
5939 Type *OpTy = getTypeByID(OpTyID);
5945 return error(
"Invalid switch record");
5947 unsigned NumCases =
Record[4];
5952 unsigned CurIdx = 5;
5953 for (
unsigned i = 0; i != NumCases; ++i) {
5955 unsigned NumItems =
Record[CurIdx++];
5956 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5957 bool isSingleNumber =
Record[CurIdx++];
5960 unsigned ActiveWords = 1;
5961 if (ValueBitWidth > 64)
5962 ActiveWords =
Record[CurIdx++];
5965 CurIdx += ActiveWords;
5967 if (!isSingleNumber) {
5969 if (ValueBitWidth > 64)
5970 ActiveWords =
Record[CurIdx++];
5973 CurIdx += ActiveWords;
5984 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5985 for (ConstantInt *Cst : CaseVals)
5986 SI->addCase(Cst, DestBB);
5995 return error(
"Invalid switch record");
5996 unsigned OpTyID =
Record[0];
5997 Type *OpTy = getTypeByID(OpTyID);
6001 return error(
"Invalid switch record");
6002 unsigned NumCases = (
Record.size()-3)/2;
6005 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
6007 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
6008 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
6009 if (!CaseVal || !DestBB) {
6011 return error(
"Invalid switch record");
6013 SI->addCase(CaseVal, DestBB);
6020 return error(
"Invalid indirectbr record");
6021 unsigned OpTyID =
Record[0];
6022 Type *OpTy = getTypeByID(OpTyID);
6025 return error(
"Invalid indirectbr record");
6026 unsigned NumDests =
Record.size()-2;
6029 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
6030 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
6034 return error(
"Invalid indirectbr record");
6044 return error(
"Invalid invoke record");
6047 unsigned CCInfo =
Record[OpNum++];
6048 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
6049 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
6051 unsigned FTyID = InvalidTypeID;
6052 FunctionType *FTy =
nullptr;
6053 if ((CCInfo >> 13) & 1) {
6057 return error(
"Explicit invoke type is not a function type");
6061 unsigned CalleeTypeID;
6062 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6064 return error(
"Invalid invoke record");
6068 return error(
"Callee is not a pointer");
6070 FTyID = getContainedTypeID(CalleeTypeID);
6073 return error(
"Callee is not of pointer to function type");
6075 if (
Record.size() < FTy->getNumParams() + OpNum)
6076 return error(
"Insufficient operands to call");
6078 SmallVector<Value*, 16>
Ops;
6079 SmallVector<unsigned, 16> ArgTyIDs;
6080 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6081 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6082 Ops.push_back(
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6086 return error(
"Invalid invoke record");
6089 if (!FTy->isVarArg()) {
6090 if (
Record.size() != OpNum)
6091 return error(
"Invalid invoke record");
6094 while (OpNum !=
Record.size()) {
6097 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6098 return error(
"Invalid invoke record");
6105 if (!OperandBundles.empty())
6110 ResTypeID = getContainedTypeID(FTyID);
6111 OperandBundles.clear();
6114 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
6125 Value *Val =
nullptr;
6127 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
6128 return error(
"Invalid resume record");
6137 unsigned CCInfo =
Record[OpNum++];
6139 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
6140 unsigned NumIndirectDests =
Record[OpNum++];
6141 SmallVector<BasicBlock *, 16> IndirectDests;
6142 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
6143 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
6145 unsigned FTyID = InvalidTypeID;
6146 FunctionType *FTy =
nullptr;
6151 return error(
"Explicit call type is not a function type");
6155 unsigned CalleeTypeID;
6156 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6158 return error(
"Invalid callbr record");
6162 return error(
"Callee is not a pointer type");
6164 FTyID = getContainedTypeID(CalleeTypeID);
6167 return error(
"Callee is not of pointer to function type");
6169 if (
Record.size() < FTy->getNumParams() + OpNum)
6170 return error(
"Insufficient operands to call");
6172 SmallVector<Value*, 16>
Args;
6173 SmallVector<unsigned, 16> ArgTyIDs;
6175 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6177 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6178 if (FTy->getParamType(i)->isLabelTy())
6179 Arg = getBasicBlock(Record[OpNum]);
6181 Arg =
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6184 return error(
"Invalid callbr record");
6185 Args.push_back(Arg);
6190 if (!FTy->isVarArg()) {
6191 if (OpNum !=
Record.size())
6192 return error(
"Invalid callbr record");
6194 while (OpNum !=
Record.size()) {
6197 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6198 return error(
"Invalid callbr record");
6205 if (!OperandBundles.empty())
6210 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6213 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6218 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6219 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6220 unsigned LabelNo = ArgNo - FirstBlockArg;
6222 if (!BA || BA->getFunction() !=
F ||
6223 LabelNo > IndirectDests.
size() ||
6224 BA->getBasicBlock() != IndirectDests[LabelNo])
6225 return error(
"callbr argument does not match indirect dest");
6230 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6234 for (
Value *Arg : Args)
6237 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6240 std::string Constraints =
IA->getConstraintString().str();
6243 for (
const auto &CI : ConstraintInfo) {
6245 if (ArgNo >= FirstBlockArg)
6246 Constraints.insert(Pos,
"!");
6251 Pos = Constraints.find(
',', Pos);
6252 if (Pos == std::string::npos)
6258 IA->hasSideEffects(),
IA->isAlignStack(),
6259 IA->getDialect(),
IA->canThrow());
6265 ResTypeID = getContainedTypeID(FTyID);
6266 OperandBundles.clear();
6283 return error(
"Invalid phi record");
6285 unsigned TyID =
Record[0];
6286 Type *Ty = getTypeByID(TyID);
6288 return error(
"Invalid phi record");
6293 size_t NumArgs = (
Record.size() - 1) / 2;
6297 return error(
"Invalid phi record");
6301 SmallDenseMap<BasicBlock *, Value *>
Args;
6302 for (
unsigned i = 0; i != NumArgs; i++) {
6303 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6306 return error(
"Invalid phi BB");
6313 auto It =
Args.find(BB);
6315 if (It !=
Args.end()) {
6329 if (!PhiConstExprBB)
6331 EdgeBB = PhiConstExprBB;
6339 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6341 V =
getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6345 return error(
"Invalid phi record");
6348 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6349 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6350 PhiConstExprBB =
nullptr;
6353 Args.insert({BB,
V});
6359 if (
Record.size() % 2 == 0) {
6363 I->setFastMathFlags(FMF);
6375 return error(
"Invalid landingpad record");
6379 return error(
"Invalid landingpad record");
6381 ResTypeID =
Record[Idx++];
6382 Type *Ty = getTypeByID(ResTypeID);
6384 return error(
"Invalid landingpad record");
6386 Value *PersFn =
nullptr;
6387 unsigned PersFnTypeID;
6388 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6390 return error(
"Invalid landingpad record");
6392 if (!
F->hasPersonalityFn())
6395 return error(
"Personality function mismatch");
6398 bool IsCleanup = !!
Record[Idx++];
6399 unsigned NumClauses =
Record[Idx++];
6402 for (
unsigned J = 0; J != NumClauses; ++J) {
6408 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6411 return error(
"Invalid landingpad record");
6416 "Catch clause has a invalid type!");
6419 "Filter clause has invalid type!");
6430 return error(
"Invalid alloca record");
6431 using APV = AllocaPackedValues;
6435 unsigned TyID =
Record[0];
6436 Type *Ty = getTypeByID(TyID);
6438 TyID = getContainedTypeID(TyID);
6439 Ty = getTypeByID(TyID);
6441 return error(
"Missing element type for old-style alloca");
6443 unsigned OpTyID =
Record[1];
6444 Type *OpTy = getTypeByID(OpTyID);
6445 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6450 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6454 return error(
"Invalid alloca record");
6456 const DataLayout &
DL = TheModule->getDataLayout();
6457 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6460 return error(
"alloca of unsized type");
6462 Align =
DL.getPrefTypeAlign(Ty);
6464 if (!
Size->getType()->isIntegerTy())
6465 return error(
"alloca element count must have integer type");
6467 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6471 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6479 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6480 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6481 return error(
"Invalid load record");
6484 return error(
"Load operand is not a pointer type");
6487 if (OpNum + 3 ==
Record.size()) {
6488 ResTypeID =
Record[OpNum++];
6489 Ty = getTypeByID(ResTypeID);
6491 ResTypeID = getContainedTypeID(OpTypeID);
6492 Ty = getTypeByID(ResTypeID);
6496 return error(
"Missing load type");
6498 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6502 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6505 return error(
"load of unsized type");
6507 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6508 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6517 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6518 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size() &&
6519 OpNum + 6 !=
Record.size()))
6520 return error(
"Invalid load atomic record");
6523 return error(
"Load operand is not a pointer type");
6526 if (
Record.size() >= OpNum + 5) {
6527 ResTypeID =
Record[OpNum++];
6528 Ty = getTypeByID(ResTypeID);
6530 ResTypeID = getContainedTypeID(OpTypeID);
6531 Ty = getTypeByID(ResTypeID);
6535 return error(
"Missing atomic load type");
6537 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6541 if (Ordering == AtomicOrdering::NotAtomic ||
6542 Ordering == AtomicOrdering::Release ||
6543 Ordering == AtomicOrdering::AcquireRelease)
6544 return error(
"Invalid load atomic record");
6545 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6546 return error(
"Invalid load atomic record");
6547 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6548 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6551 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6554 return error(
"Alignment missing from atomic load");
6557 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6567 unsigned PtrTypeID, ValTypeID;
6568 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6569 return error(
"Invalid store record");
6572 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6573 return error(
"Invalid store record");
6575 ValTypeID = getContainedTypeID(PtrTypeID);
6576 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6577 ValTypeID, Val, CurBB))
6578 return error(
"Invalid store record");
6581 if (OpNum + 2 !=
Record.size())
6582 return error(
"Invalid store record");
6587 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6590 return error(
"store of unsized type");
6592 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6593 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6603 unsigned PtrTypeID, ValTypeID;
6604 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6606 return error(
"Invalid store atomic record");
6608 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6609 return error(
"Invalid store atomic record");
6611 ValTypeID = getContainedTypeID(PtrTypeID);
6612 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6613 ValTypeID, Val, CurBB))
6614 return error(
"Invalid store atomic record");
6617 if (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size())
6618 return error(
"Invalid store atomic record");
6623 if (Ordering == AtomicOrdering::NotAtomic ||
6624 Ordering == AtomicOrdering::Acquire ||
6625 Ordering == AtomicOrdering::AcquireRelease)
6626 return error(
"Invalid store atomic record");
6627 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6628 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6629 return error(
"Invalid store atomic record");
6632 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6635 return error(
"Alignment missing from atomic store");
6637 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6641 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6650 const size_t NumRecords =
Record.size();
6652 Value *Ptr =
nullptr;
6654 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6655 return error(
"Invalid cmpxchg record");
6658 return error(
"Cmpxchg operand is not a pointer type");
6661 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6662 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6663 CmpTypeID, Cmp, CurBB))
6664 return error(
"Invalid cmpxchg record");
6667 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6669 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6670 return error(
"Invalid cmpxchg record");
6674 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6675 SuccessOrdering == AtomicOrdering::Unordered)
6676 return error(
"Invalid cmpxchg record");
6678 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6680 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6688 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6689 FailureOrdering == AtomicOrdering::Unordered)
6690 return error(
"Invalid cmpxchg record");
6693 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6695 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6696 FailureOrdering, SSID);
6699 if (NumRecords < 8) {
6703 I->insertInto(CurBB, CurBB->
end());
6705 ResTypeID = CmpTypeID;
6708 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6709 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6718 const size_t NumRecords =
Record.size();
6720 Value *Ptr =
nullptr;
6722 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6723 return error(
"Invalid cmpxchg record");
6726 return error(
"Cmpxchg operand is not a pointer type");
6730 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6731 return error(
"Invalid cmpxchg record");
6733 Value *Val =
nullptr;
6734 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6736 return error(
"Invalid cmpxchg record");
6738 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6739 return error(
"Invalid cmpxchg record");
6741 const bool IsVol =
Record[OpNum];
6746 return error(
"Invalid cmpxchg success ordering");
6748 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6750 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6756 return error(
"Invalid cmpxchg failure ordering");
6758 const bool IsWeak =
Record[OpNum + 4];
6762 if (NumRecords == (OpNum + 6)) {
6763 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6768 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6770 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6771 FailureOrdering, SSID);
6775 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6776 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6785 const size_t NumRecords =
Record.size();
6788 Value *Ptr =
nullptr;
6790 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6791 return error(
"Invalid atomicrmw record");
6794 return error(
"Invalid atomicrmw record");
6796 Value *Val =
nullptr;
6797 unsigned ValTypeID = InvalidTypeID;
6799 ValTypeID = getContainedTypeID(PtrTypeID);
6800 if (popValue(Record, OpNum, NextValueNo,
6801 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6802 return error(
"Invalid atomicrmw record");
6804 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6805 return error(
"Invalid atomicrmw record");
6808 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6809 return error(
"Invalid atomicrmw record");
6811 bool IsElementwise =
false;
6816 return error(
"Invalid atomicrmw record");
6818 const bool IsVol =
Record[OpNum + 1];
6821 if (Ordering == AtomicOrdering::NotAtomic ||
6822 Ordering == AtomicOrdering::Unordered)
6823 return error(
"Invalid atomicrmw record");
6825 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6829 if (NumRecords == (OpNum + 5)) {
6830 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6836 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6838 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID,
6840 ResTypeID = ValTypeID;
6848 return error(
"Invalid fence record");
6850 if (Ordering == AtomicOrdering::NotAtomic ||
6851 Ordering == AtomicOrdering::Unordered ||
6852 Ordering == AtomicOrdering::Monotonic)
6853 return error(
"Invalid fence record");
6855 I =
new FenceInst(
Context, Ordering, SSID);
6862 SeenDebugRecord =
true;
6865 return error(
"Invalid dbg record: missing instruction");
6868 Inst->
getParent()->insertDbgRecordBefore(
6879 SeenDebugRecord =
true;
6882 return error(
"Invalid dbg record: missing instruction");
6899 DILocalVariable *Var =
6901 DIExpression *Expr =
6914 unsigned SlotBefore =
Slot;
6915 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6916 return error(
"Invalid dbg record: invalid value");
6918 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6921 RawLocation = getFnMetadataByID(Record[Slot++]);
6924 DbgVariableRecord *DVR =
nullptr;
6928 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6929 DbgVariableRecord::LocationType::Value);
6932 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6933 DbgVariableRecord::LocationType::Declare);
6936 DVR =
new DbgVariableRecord(
6937 RawLocation, Var, Expr, DIL,
6938 DbgVariableRecord::LocationType::DeclareValue);
6942 DIExpression *AddrExpr =
6944 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6945 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
6958 return error(
"Invalid call record");
6962 unsigned CCInfo =
Record[OpNum++];
6968 return error(
"Fast math flags indicator set for call with no FMF");
6971 unsigned FTyID = InvalidTypeID;
6972 FunctionType *FTy =
nullptr;
6977 return error(
"Explicit call type is not a function type");
6981 unsigned CalleeTypeID;
6982 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6984 return error(
"Invalid call record");
6988 return error(
"Callee is not a pointer type");
6990 FTyID = getContainedTypeID(CalleeTypeID);
6993 return error(
"Callee is not of pointer to function type");
6995 if (
Record.size() < FTy->getNumParams() + OpNum)
6996 return error(
"Insufficient operands to call");
6998 SmallVector<Value*, 16>
Args;
6999 SmallVector<unsigned, 16> ArgTyIDs;
7001 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
7002 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
7003 if (FTy->getParamType(i)->isLabelTy())
7004 Args.push_back(getBasicBlock(Record[OpNum]));
7007 FTy->getParamType(i), ArgTyID, CurBB));
7010 return error(
"Invalid call record");
7014 if (!FTy->isVarArg()) {
7015 if (OpNum !=
Record.size())
7016 return error(
"Invalid call record");
7018 while (OpNum !=
Record.size()) {
7021 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7022 return error(
"Invalid call record");
7029 if (!OperandBundles.empty())
7033 ResTypeID = getContainedTypeID(FTyID);
7034 OperandBundles.clear();
7048 SeenDebugIntrinsic =
true;
7051 if (
auto *ListAsValue =
7064 return error(
"Fast-math-flags specified for call without "
7065 "floating-point scalar or vector return type");
7066 I->setFastMathFlags(FMF);
7072 return error(
"Invalid va_arg record");
7073 unsigned OpTyID =
Record[0];
7074 Type *OpTy = getTypeByID(OpTyID);
7077 Type *ResTy = getTypeByID(ResTypeID);
7078 if (!OpTy || !
Op || !ResTy)
7079 return error(
"Invalid va_arg record");
7080 I =
new VAArgInst(
Op, ResTy);
7090 if (
Record.empty() || Record[0] >= BundleTags.size())
7091 return error(
"Invalid operand bundle record");
7093 std::vector<Value *> Inputs;
7096 while (OpNum !=
Record.size()) {
7098 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
7099 return error(
"Invalid operand bundle record");
7100 Inputs.push_back(
Op);
7103 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
7111 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7112 return error(
"Invalid freeze record");
7113 if (OpNum !=
Record.size())
7114 return error(
"Invalid freeze record");
7116 I =
new FreezeInst(
Op);
7117 ResTypeID = OpTypeID;
7127 return error(
"Invalid instruction with no BB");
7129 if (!OperandBundles.empty()) {
7131 return error(
"Operand bundles found with no consumer");
7133 I->insertInto(CurBB, CurBB->
end());
7136 if (
I->isTerminator()) {
7138 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
7142 if (!
I->getType()->isVoidTy()) {
7143 assert(
I->getType() == getTypeByID(ResTypeID) &&
7144 "Incorrect result type ID");
7152 if (!OperandBundles.empty())
7153 return error(
"Operand bundles found with no consumer");
7157 if (!
A->getParent()) {
7159 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
7165 return error(
"Never resolved value found in function");
7170 if (MDLoader->hasFwdRefs())
7171 return error(
"Invalid function metadata: outgoing forward refs");
7176 for (
const auto &Pair : ConstExprEdgeBBs) {
7187 ValueList.
shrinkTo(ModuleValueListSize);
7188 MDLoader->shrinkTo(ModuleMDLoaderSize);
7189 std::vector<BasicBlock*>().swap(FunctionBBs);
7194Error BitcodeReader::findFunctionInStream(
7196 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7197 while (DeferredFunctionInfoIterator->second == 0) {
7202 assert(VSTOffset == 0 || !
F->hasName());
7205 if (
Error Err = rememberAndSkipFunctionBodies())
7211SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7214 if (Val >= SSIDs.
size())
7223Error BitcodeReader::materialize(GlobalValue *GV) {
7226 if (!
F || !
F->isMaterializable())
7229 auto DFII = DeferredFunctionInfo.
find(
F);
7230 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7233 if (DFII->second == 0)
7234 if (
Error Err = findFunctionInStream(
F, DFII))
7238 if (
Error Err = materializeMetadata())
7245 if (
Error Err = parseFunctionBody(
F))
7247 F->setIsMaterializable(
false);
7251 if (SeenDebugIntrinsic && SeenDebugRecord)
7252 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7258 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7259 F->setSubprogram(SP);
7262 if (!MDLoader->isStrippingTBAA()) {
7264 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7267 MDLoader->setStripTBAA(
true);
7274 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7275 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7281 unsigned ExpectedNumOperands = 0;
7283 ExpectedNumOperands = 2;
7285 ExpectedNumOperands =
SI->getNumSuccessors();
7287 ExpectedNumOperands = 1;
7291 ExpectedNumOperands = 2;
7298 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7299 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7305 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7306 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7308 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7309 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7310 CI->getArgOperand(ArgNo)->getType(),
7311 CI->getParamAttributes(ArgNo)));
7314 if (
Function *OldFn = CI->getCalledFunction()) {
7315 auto It = UpgradedIntrinsics.
find(OldFn);
7316 if (It != UpgradedIntrinsics.
end())
7320 BC && BC->getSrcTy() == BC->getDestTy() &&
7326 CI && CI->isMustTailCall() && CI->getNextNode() == BC) {
7327 BC->replaceAllUsesWith(CI);
7328 BC->eraseFromParent();
7338 return materializeForwardReferencedFunctions();
7341Error BitcodeReader::materializeModule() {
7342 if (
Error Err = materializeMetadata())
7346 WillMaterializeAllForwardRefs =
true;
7351 if (
Error Err = materialize(&
F))
7357 if (LastFunctionBlockBit || NextUnreadBit)
7359 ? LastFunctionBlockBit
7365 if (!BasicBlockFwdRefs.
empty())
7366 return error(
"Never resolved function from blockaddress");
7372 for (
auto &[OldFn, NewFn] : UpgradedIntrinsics) {
7373 for (User *U : OldFn->users()) {
7377 if (OldFn != NewFn) {
7378 if (!OldFn->use_empty())
7379 OldFn->replaceAllUsesWith(NewFn);
7380 OldFn->eraseFromParent();
7383 UpgradedIntrinsics.clear();
7398std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7399 return IdentifiedStructTypes;
7402ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7403 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7404 StringRef ModulePath, std::function<
bool(StringRef)> IsPrevailing,
7405 std::function<
void(ValueInfo)> OnValueInfo)
7406 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7407 ModulePath(ModulePath), IsPrevailing(IsPrevailing),
7408 OnValueInfo(OnValueInfo) {}
7410void ModuleSummaryIndexBitcodeReader::addThisModule() {
7415ModuleSummaryIndexBitcodeReader::getThisModule() {
7419template <
bool AllowNullValueInfo>
7420std::pair<ValueInfo, GlobalValue::GUID>
7421ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7422 auto VGI = ValueIdToValueInfoMap[ValueId];
7429 assert(AllowNullValueInfo || std::get<0>(VGI));
7433void ModuleSummaryIndexBitcodeReader::setValueGUID(
7435 StringRef SourceFileName) {
7437 if (ValueID < DefinedGUIDs.size())
7438 ValueGUID = DefinedGUIDs[ValueID];
7445 auto OriginalNameID = ValueGUID;
7449 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7457 ValueIdToValueInfoMap[ValueID] = std::make_pair(VI, OriginalNameID);
7465Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7467 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7474 if (!MaybeCurrentBit)
7481 SmallVector<uint64_t, 64>
Record;
7490 BitstreamEntry
Entry = MaybeEntry.
get();
7492 switch (
Entry.Kind) {
7495 return error(
"Malformed block");
7511 switch (MaybeRecord.
get()) {
7516 return error(
"Invalid vst_code_entry record");
7517 unsigned ValueID =
Record[0];
7519 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7520 assert(VLI != ValueIdToLinkageMap.
end() &&
7521 "No linkage found for VST entry?");
7530 return error(
"Invalid vst_code_fnentry record");
7531 unsigned ValueID =
Record[0];
7533 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7534 assert(VLI != ValueIdToLinkageMap.
end() &&
7535 "No linkage found for VST entry?");
7543 unsigned ValueID =
Record[0];
7547 ValueIdToValueInfoMap[ValueID] =
7558Error ModuleSummaryIndexBitcodeReader::parseModule() {
7562 SmallVector<uint64_t, 64>
Record;
7563 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7564 unsigned ValueId = 0;
7568 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
7571 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7573 switch (
Entry.Kind) {
7575 return error(
"Malformed block");
7587 if (
Error Err = readBlockInfo())
7593 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7594 !SeenGlobalValSummary) &&
7595 "Expected early VST parse via VSTOffset record");
7602 if (!SourceFileName.
empty())
7604 assert(!SeenValueSymbolTable &&
7605 "Already read VST when parsing summary block?");
7610 if (VSTOffset > 0) {
7611 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7613 SeenValueSymbolTable =
true;
7615 SeenGlobalValSummary =
true;
7616 if (
Error Err = parseEntireSummary(
Entry.ID))
7620 if (
Error Err = parseModuleStringTable())
7628 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7631 switch (MaybeBitCode.
get()) {
7635 if (
Error Err = parseVersionRecord(Record).takeError())
7643 return error(
"Invalid source filename record");
7650 return error(
"Invalid hash length " + Twine(
Record.size()));
7651 auto &Hash = getThisModule()->second;
7653 for (
auto &Val : Record) {
7654 assert(!(Val >> 32) &&
"Unexpected high bits set");
7662 return error(
"Invalid vstoffset record");
7666 VSTOffset =
Record[0] - 1;
7671 DefinedGUIDs.reserve(DefinedGUIDs.size() +
Record.size() / 2);
7672 for (
size_t i = 0; i <
Record.size(); i += 2)
7673 DefinedGUIDs.push_back(Record[i] << 32 | Record[i + 1]);
7683 ArrayRef<uint64_t> GVRecord;
7684 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7685 if (GVRecord.
size() <= 3)
7686 return error(
"Invalid global record");
7690 ValueIdToLinkageMap[ValueId++] =
Linkage;
7694 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7705ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7709 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7714ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7715 bool IsOldProfileFormat,
7716 bool HasProfile,
bool HasRelBF) {
7720 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7725 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7727 bool HasTailCall =
false;
7729 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7730 if (IsOldProfileFormat) {
7734 }
else if (HasProfile)
7735 std::tie(Hotness, HasTailCall) =
7769 static_cast<size_t>(
Record[Slot + 1])};
7792 while (Slot <
Record.size())
7796std::vector<FunctionSummary::ParamAccess>
7797ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7798 auto ReadRange = [&]() {
7800 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7802 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7809 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7810 while (!
Record.empty()) {
7811 PendingParamAccesses.emplace_back();
7812 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7814 ParamAccess.
Use = ReadRange();
7819 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7820 Call.Offsets = ReadRange();
7823 return PendingParamAccesses;
7826void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7827 ArrayRef<uint64_t> Record,
size_t &Slot,
7830 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7834void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7835 ArrayRef<uint64_t> Record) {
7843 while (Slot <
Record.size())
7844 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7847SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7848 ArrayRef<uint64_t> Record,
unsigned &
I) {
7849 SmallVector<unsigned> StackIdList;
7853 if (RadixArray.empty()) {
7854 unsigned NumStackEntries =
Record[
I++];
7856 StackIdList.
reserve(NumStackEntries);
7857 for (
unsigned J = 0; J < NumStackEntries; J++) {
7858 assert(Record[
I] < StackIds.size());
7859 StackIdList.
push_back(getStackIdIndex(Record[
I++]));
7862 unsigned RadixIndex =
Record[
I++];
7868 assert(RadixIndex < RadixArray.size());
7869 unsigned NumStackIds = RadixArray[RadixIndex++];
7870 StackIdList.
reserve(NumStackIds);
7871 while (NumStackIds--) {
7872 assert(RadixIndex < RadixArray.size());
7873 unsigned Elem = RadixArray[RadixIndex];
7874 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7875 RadixIndex = RadixIndex - Elem;
7876 assert(RadixIndex < RadixArray.size());
7877 Elem = RadixArray[RadixIndex];
7879 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7882 StackIdList.
push_back(getStackIdIndex(Elem));
7892 unsigned FirstWORef = Refs.
size() - WOCnt;
7893 unsigned RefNo = FirstWORef - ROCnt;
7894 for (; RefNo < FirstWORef; ++RefNo)
7895 Refs[RefNo].setReadOnly();
7896 for (; RefNo < Refs.
size(); ++RefNo)
7897 Refs[RefNo].setWriteOnly();
7902Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7905 SmallVector<uint64_t, 64>
Record;
7912 BitstreamEntry
Entry = MaybeEntry.
get();
7915 return error(
"Invalid Summary Block: record for version expected");
7920 return error(
"Invalid Summary Block: version expected");
7923 const bool IsOldProfileFormat =
Version == 1;
7926 const bool MemProfAfterFunctionSummary =
Version >= 13;
7928 return error(
"Invalid summary version " + Twine(
Version) +
" in module '" +
7929 ModulePath +
"'. Version should be in the range [1-" +
7935 GlobalValueSummary *LastSeenSummary =
nullptr;
7945 FunctionSummary *CurrentPrevailingFS =
nullptr;
7950 std::vector<GlobalValue::GUID> PendingTypeTests;
7951 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7952 PendingTypeCheckedLoadVCalls;
7953 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7954 PendingTypeCheckedLoadConstVCalls;
7955 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7957 std::vector<CallsiteInfo> PendingCallsites;
7958 std::vector<AllocInfo> PendingAllocs;
7959 std::vector<uint64_t> PendingContextIds;
7965 BitstreamEntry
Entry = MaybeEntry.
get();
7967 switch (
Entry.Kind) {
7970 return error(
"Malformed block");
7986 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7989 unsigned BitCode = MaybeBitCode.
get();
8006 ValueIdToValueInfoMap[ValueID] =
8024 unsigned ValueID =
Record[0];
8026 unsigned InstCount =
Record[2];
8028 unsigned NumRefs =
Record[3];
8029 unsigned NumRORefs = 0, NumWORefs = 0;
8030 int RefListStartIndex = 4;
8034 RefListStartIndex = 5;
8037 RefListStartIndex = 6;
8040 RefListStartIndex = 7;
8051 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8053 "Record size inconsistent with number of references");
8055 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8060 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8061 IsOldProfileFormat, HasProfile, HasRelBF);
8063 auto [
VI,
GUID] = getValueInfoFromValueId(ValueID);
8070 IsPrevailing(
VI.name());
8076 assert(!MemProfAfterFunctionSummary ||
8077 (PendingCallsites.empty() && PendingAllocs.empty()));
8078 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
8079 PendingCallsites.clear();
8080 PendingAllocs.clear();
8083 auto FS = std::make_unique<FunctionSummary>(
8085 std::move(Calls), std::move(PendingTypeTests),
8086 std::move(PendingTypeTestAssumeVCalls),
8087 std::move(PendingTypeCheckedLoadVCalls),
8088 std::move(PendingTypeTestAssumeConstVCalls),
8089 std::move(PendingTypeCheckedLoadConstVCalls),
8090 std::move(PendingParamAccesses), std::move(PendingCallsites),
8091 std::move(PendingAllocs));
8092 FS->setModulePath(getThisModule()->first());
8093 FS->setOriginalName(GUID);
8096 if (MemProfAfterFunctionSummary) {
8097 if (IsPrevailingSym)
8098 CurrentPrevailingFS =
FS.get();
8100 CurrentPrevailingFS =
nullptr;
8109 unsigned ValueID =
Record[0];
8111 unsigned AliaseeID =
Record[2];
8113 auto AS = std::make_unique<AliasSummary>(Flags);
8119 AS->setModulePath(getThisModule()->first());
8121 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
8123 if (!AliaseeInModule)
8124 return error(
"Alias expects aliasee summary to be parsed");
8125 AS->setAliasee(AliaseeVI, AliaseeInModule);
8127 auto GUID = getValueInfoFromValueId(ValueID);
8128 AS->setOriginalName(std::get<1>(GUID));
8134 unsigned ValueID =
Record[0];
8136 unsigned RefArrayStart = 2;
8137 GlobalVarSummary::GVarFlags GVF(
false,
8147 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8149 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8150 FS->setModulePath(getThisModule()->first());
8151 auto GUID = getValueInfoFromValueId(ValueID);
8152 FS->setOriginalName(std::get<1>(GUID));
8160 unsigned ValueID =
Record[0];
8163 unsigned NumRefs =
Record[3];
8164 unsigned RefListStartIndex = 4;
8165 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
8168 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8170 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
8171 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
8176 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8177 VS->setModulePath(getThisModule()->first());
8178 VS->setVTableFuncs(VTableFuncs);
8179 auto GUID = getValueInfoFromValueId(ValueID);
8180 VS->setOriginalName(std::get<1>(GUID));
8192 unsigned ValueID =
Record[0];
8195 unsigned InstCount =
Record[3];
8197 unsigned NumRefs =
Record[4];
8198 unsigned NumRORefs = 0, NumWORefs = 0;
8199 int RefListStartIndex = 5;
8203 RefListStartIndex = 6;
8204 size_t NumRefsIndex = 5;
8206 unsigned NumRORefsOffset = 1;
8207 RefListStartIndex = 7;
8210 RefListStartIndex = 8;
8212 RefListStartIndex = 9;
8214 NumRORefsOffset = 2;
8217 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
8219 NumRefs =
Record[NumRefsIndex];
8223 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8225 "Record size inconsistent with number of references");
8227 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8230 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8231 IsOldProfileFormat, HasProfile,
false);
8232 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8234 auto FS = std::make_unique<FunctionSummary>(
8236 std::move(Edges), std::move(PendingTypeTests),
8237 std::move(PendingTypeTestAssumeVCalls),
8238 std::move(PendingTypeCheckedLoadVCalls),
8239 std::move(PendingTypeTestAssumeConstVCalls),
8240 std::move(PendingTypeCheckedLoadConstVCalls),
8241 std::move(PendingParamAccesses), std::move(PendingCallsites),
8242 std::move(PendingAllocs));
8243 LastSeenSummary =
FS.get();
8244 if (MemProfAfterFunctionSummary)
8245 CurrentPrevailingFS =
FS.get();
8246 LastSeenGUID =
VI.getGUID();
8247 FS->setModulePath(ModuleIdMap[ModuleId]);
8255 unsigned ValueID =
Record[0];
8258 unsigned AliaseeValueId =
Record[3];
8260 auto AS = std::make_unique<AliasSummary>(Flags);
8261 LastSeenSummary = AS.get();
8262 AS->setModulePath(ModuleIdMap[ModuleId]);
8264 auto AliaseeVI = std::get<0>(
8265 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8267 auto AliaseeInModule =
8269 AS->setAliasee(AliaseeVI, AliaseeInModule);
8271 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8272 LastSeenGUID =
VI.getGUID();
8278 unsigned ValueID =
Record[0];
8281 unsigned RefArrayStart = 3;
8282 GlobalVarSummary::GVarFlags GVF(
false,
8292 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8294 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8295 LastSeenSummary =
FS.get();
8296 FS->setModulePath(ModuleIdMap[ModuleId]);
8297 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8298 LastSeenGUID =
VI.getGUID();
8305 if (!LastSeenSummary)
8306 return error(
"Name attachment that does not follow a combined record");
8310 LastSeenSummary =
nullptr;
8315 assert(PendingTypeTests.empty());
8320 assert(PendingTypeTestAssumeVCalls.empty());
8321 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8322 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8326 assert(PendingTypeCheckedLoadVCalls.empty());
8327 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8328 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8332 PendingTypeTestAssumeConstVCalls.push_back(
8337 PendingTypeCheckedLoadConstVCalls.push_back(
8344 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8345 StringRef
Name(Strtab.
data() + Record[
I],
8346 static_cast<size_t>(Record[
I + 1]));
8349 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, GUID);
8352 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8354 StringRef
Name(Strtab.
data() + Record[
I + 1],
8355 static_cast<size_t>(Record[
I + 2]));
8356 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8365 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8366 StringRef
Name(Strtab.
data() + Record[
I],
8367 static_cast<size_t>(Record[
I + 1]));
8370 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, GUID);
8373 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8375 StringRef
Name(Strtab.
data() + Record[
I + 1],
8376 static_cast<size_t>(Record[
I + 2]));
8377 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8388 parseTypeIdCompatibleVtableSummaryRecord(Record);
8396 PendingParamAccesses = parseParamAccesses(Record);
8403 assert(StackIds.empty());
8405 StackIds = ArrayRef<uint64_t>(Record);
8411 StackIds.reserve(
Record.size() / 2);
8412 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8413 StackIds.push_back(*R << 32 | *(R + 1));
8415 assert(StackIdToIndex.empty());
8417 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8422 RadixArray = ArrayRef<uint64_t>(Record);
8429 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8431 unsigned ValueID =
Record[0];
8432 SmallVector<unsigned> StackIdList;
8434 assert(R < StackIds.size());
8435 StackIdList.
push_back(getStackIdIndex(R));
8437 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8438 if (MemProfAfterFunctionSummary)
8440 CallsiteInfo({
VI, std::move(StackIdList)}));
8442 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8449 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8450 auto RecordIter =
Record.begin();
8451 unsigned ValueID = *RecordIter++;
8452 unsigned NumStackIds = *RecordIter++;
8453 unsigned NumVersions = *RecordIter++;
8454 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8455 SmallVector<unsigned> StackIdList;
8456 for (
unsigned J = 0; J < NumStackIds; J++) {
8457 assert(*RecordIter < StackIds.size());
8458 StackIdList.
push_back(getStackIdIndex(*RecordIter++));
8460 SmallVector<unsigned> Versions;
8461 for (
unsigned J = 0; J < NumVersions; J++)
8463 ValueInfo
VI = std::get<0>(
8464 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8465 if (MemProfAfterFunctionSummary)
8467 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8469 PendingCallsites.push_back(
8470 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8477 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8482 PendingContextIds.reserve(
Record.size() / 2);
8483 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8484 PendingContextIds.push_back(*R << 32 | *(R + 1));
8491 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8492 PendingContextIds.clear();
8496 std::vector<MIBInfo> MIBs;
8497 unsigned NumMIBs = 0;
8500 unsigned MIBsRead = 0;
8501 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8505 auto StackIdList = parseAllocInfoContext(Record,
I);
8506 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8512 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8514 assert(!PendingContextIds.empty() &&
8515 "Missing context ids for alloc sizes");
8516 unsigned ContextIdIndex = 0;
8522 while (MIBsRead++ < NumMIBs) {
8524 unsigned NumContextSizeInfoEntries =
Record[
I++];
8526 std::vector<ContextTotalSize> ContextSizes;
8527 ContextSizes.reserve(NumContextSizeInfoEntries);
8528 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8529 assert(ContextIdIndex < PendingContextIds.size());
8531 if (PendingContextIds[ContextIdIndex] == 0) {
8540 ContextSizes.push_back(
8541 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8543 AllContextSizes.push_back(std::move(ContextSizes));
8545 PendingContextIds.clear();
8547 AllocInfo AI(std::move(MIBs));
8548 if (!AllContextSizes.empty()) {
8549 assert(AI.MIBs.size() == AllContextSizes.size());
8550 AI.ContextSizeInfos = std::move(AllContextSizes);
8553 if (MemProfAfterFunctionSummary)
8554 CurrentPrevailingFS->
addAlloc(std::move(AI));
8556 PendingAllocs.push_back(std::move(AI));
8564 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8566 std::vector<MIBInfo> MIBs;
8567 unsigned NumMIBs =
Record[
I++];
8568 unsigned NumVersions =
Record[
I++];
8569 unsigned MIBsRead = 0;
8570 while (MIBsRead++ < NumMIBs) {
8573 SmallVector<unsigned> StackIdList;
8575 StackIdList = parseAllocInfoContext(Record,
I);
8576 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8579 SmallVector<uint8_t> Versions;
8580 for (
unsigned J = 0; J < NumVersions; J++)
8583 AllocInfo AI(std::move(Versions), std::move(MIBs));
8584 if (MemProfAfterFunctionSummary)
8585 CurrentPrevailingFS->
addAlloc(std::move(AI));
8587 PendingAllocs.push_back(std::move(AI));
8597Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8601 SmallVector<uint64_t, 64>
Record;
8603 SmallString<128> ModulePath;
8610 BitstreamEntry
Entry = MaybeEntry.
get();
8612 switch (
Entry.Kind) {
8615 return error(
"Malformed block");
8627 switch (MaybeRecord.
get()) {
8635 return error(
"Invalid code_entry record");
8637 LastSeenModule = TheIndex.
addModule(ModulePath);
8638 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8646 return error(
"Invalid hash length " + Twine(
Record.size()));
8647 if (!LastSeenModule)
8648 return error(
"Invalid hash that does not follow a module path");
8650 for (
auto &Val : Record) {
8651 assert(!(Val >> 32) &&
"Unexpected high bits set");
8652 LastSeenModule->
second[Pos++] = Val;
8655 LastSeenModule =
nullptr;
8668class BitcodeErrorCategoryType :
public std::error_category {
8669 const char *
name()
const noexcept
override {
8670 return "llvm.bitcode";
8673 std::string message(
int IE)
const override {
8676 case BitcodeError::CorruptedBitcode:
8677 return "Corrupted bitcode";
8686 static BitcodeErrorCategoryType ErrorCategory;
8687 return ErrorCategory;
8691 unsigned Block,
unsigned RecordID) {
8693 return std::move(Err);
8702 switch (Entry.Kind) {
8707 return error(
"Malformed block");
8711 return std::move(Err);
8721 if (MaybeRecord.
get() == RecordID)
8732Expected<std::vector<BitcodeModule>>
8736 return FOrErr.takeError();
8737 return std::move(FOrErr->Mods);
8762 switch (Entry.Kind) {
8765 return error(
"Malformed block");
8768 uint64_t IdentificationBit = -1ull;
8772 return std::move(Err);
8778 Entry = MaybeEntry.
get();
8783 return error(
"Malformed block");
8789 return std::move(Err);
8808 if (!
I.Strtab.empty())
8815 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8816 F.StrtabForSymtab = *Strtab;
8832 if (
F.Symtab.empty())
8833 F.Symtab = *SymtabOrErr;
8838 return std::move(Err);
8843 return std::move(E);
8858BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8859 bool ShouldLazyLoadMetadata,
bool IsImporting,
8863 std::string ProducerIdentification;
8864 if (IdentificationBit != -1ull) {
8866 return std::move(JumpFailed);
8869 return std::move(
E);
8873 return std::move(JumpFailed);
8874 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8877 std::unique_ptr<Module>
M =
8878 std::make_unique<Module>(ModuleIdentifier,
Context);
8879 M->setMaterializer(R);
8882 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8883 IsImporting, Callbacks))
8884 return std::move(Err);
8886 if (MaterializeAll) {
8888 if (
Error Err =
M->materializeAll())
8889 return std::move(Err);
8892 if (
Error Err =
R->materializeForwardReferencedFunctions())
8893 return std::move(Err);
8896 return std::move(M);
8899Expected<std::unique_ptr<Module>>
8902 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8912 std::function<
bool(
StringRef)> IsPrevailing,
8913 std::function<
void(
ValueInfo)> OnValueInfo) {
8918 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8919 ModulePath, IsPrevailing, OnValueInfo);
8920 return R.parseModule();
8927 return std::move(JumpFailed);
8929 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8930 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8931 ModuleIdentifier, 0);
8933 if (
Error Err = R.parseModule())
8934 return std::move(Err);
8936 return std::move(Index);
8942 return std::move(Err);
8948 return std::move(
E);
8950 switch (Entry.Kind) {
8953 return error(
"Malformed block");
8956 return std::make_pair(
false,
false);
8968 switch (MaybeBitCode.
get()) {
8974 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
8976 bool EnableSplitLTOUnit = Flags & 0x8;
8977 bool UnifiedLTO = Flags & 0x200;
8978 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8989 return std::move(JumpFailed);
8992 return std::move(Err);
8997 return std::move(E);
8999 switch (Entry.Kind) {
9001 return error(
"Malformed block");
9012 return Flags.takeError();
9022 return std::move(Err);
9029 return StreamFailed.takeError();
9039 if (MsOrErr->size() != 1)
9040 return error(
"Expected a single module");
9042 return (*MsOrErr)[0];
9045Expected<std::unique_ptr<Module>>
9047 bool ShouldLazyLoadMetadata,
bool IsImporting,
9053 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
9058 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
9059 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
9061 IsImporting, Callbacks);
9063 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
9069 return getModuleImpl(Context,
true,
false,
false, Callbacks);
9081 return BM->parseModule(Context, Callbacks);
9114 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
9123 return BM->getSummary();
9131 return BM->getLTOInfo();
9136 bool IgnoreEmptyThinLTOIndexFile) {
9141 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, bool &HasTailCall)
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
static cl::opt< bool > PrintSummaryGUIDs("print-summary-global-ids", cl::init(false), cl::Hidden, cl::desc("Print the global id for each value when reading the module summary"))
static AtomicOrdering getDecodedOrdering(unsigned Val)
static std::pair< CalleeInfo::HotnessType, bool > getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)
static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags)
static std::optional< CodeModel::Model > getDecodedCodeModel(unsigned Val)
static void setSpecialRefs(SmallVectorImpl< ValueInfo > &Refs, unsigned ROCnt, unsigned WOCnt)
static bool getDecodedDSOLocal(unsigned Val)
static bool convertToString(ArrayRef< uint64_t > Record, unsigned Idx, StrTy &Result)
Convert a string from a record into an std::string, return true on failure.
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
static void stripTBAA(Module *M)
static int getDecodedUnaryOpcode(unsigned Val, Type *Ty)
static Expected< std::string > readTriple(BitstreamCursor &Stream)
static void parseWholeProgramDevirtResolutionByArg(ArrayRef< uint64_t > Record, size_t &Slot, WholeProgramDevirtResolution &Wpd)
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags)
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
static Expected< uint64_t > jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
static Expected< bool > hasObjCCategoryInModule(BitstreamCursor &Stream)
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags)
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs, uint64_t AttrIdx)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val, bool &IsElementwise)
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
static bool hasImplicitComdat(size_t Val)
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream)
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
static void inferDSOLocal(GlobalValue *GV)
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V)
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
static cl::opt< bool > ExpandConstantExprs("expand-constant-exprs", cl::Hidden, cl::desc("Expand constant expressions to instructions for testing purposes"))
static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind)
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
static Expected< std::string > readIdentificationBlock(BitstreamCursor &Stream)
Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the "epoch" encoded in the bit...
static Expected< std::pair< bool, bool > > getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID)
static bool isConstExprSupported(const BitcodeConstant *BC)
static int getDecodedCastOpcode(unsigned Val)
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP
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.
static LLVM_ABI const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static BitInsertInst * Create(Value *Base, Value *Val, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Represents a module in a bitcode file.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(StringRef)> IsPrevailing=nullptr, std::function< void(ValueInfo)> OnValueInfo=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
void push_back(Value *V, unsigned TypeID)
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
void shrinkTo(unsigned N)
unsigned getTypeID(unsigned ValNo) const
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
ArrayRef< uint8_t > getBitcodeBytes() const
Expected< word_t > Read(unsigned NumBits)
Expected< BitstreamEntry > advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Expected< BitstreamEntry > advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block.
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
uint64_t getCurrentByteNo() const
LLVM_ABI Expected< std::optional< BitstreamBlockInfo > > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
bool canSkipToPos(size_t pos) const
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
@ MIN_BYTE_BITS
Minimum number of bits that can be specified.
@ MAX_BYTE_BITS
Maximum number of bits that can be specified Note that bit width is stored in the Type classes Subcla...
static LLVM_ABI ByteType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing a ByteType.
bool isInlineAsm() const
Check if this call is an inline asm statement.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo createFromIntValue(uint32_t Data)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
bool isIntPredicate() const
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
static Constant * getRaw(StringRef Data, uint64_t NumElements, Type *ElementTy)
getRaw() constructor - Return a constant with vector type with an element count and element type matc...
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH 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 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 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)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
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.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
Convenience struct for specifying and reasoning about fast-math flags.
void setFast(bool B=true)
void setAllowContract(bool B=true)
void setAllowReciprocal(bool B=true)
void setNoSignedZeros(bool B=true)
void setNoNaNs(bool B=true)
void setAllowReassoc(bool B=true)
Flag setters.
void setApproxFunc(bool B=true)
void setNoInfs(bool B=true)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
void addCallsite(CallsiteInfo &&Callsite)
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
void addAlloc(AllocInfo &&Alloc)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
BasicBlockListType::iterator iterator
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
bool hasDefaultVisibility() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
bool hasExternalWeakLinkage() const
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
LLVM_ABI void setPartition(StringRef Part)
void setAttributes(AttributeSet A)
Set attribute list for this global.
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
std::vector< ConstraintInfo > ConstraintInfoVector
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
const char * getOpcodeName() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
@ MIN_INT_BITS
Minimum number of bits that can be specified.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
LLVM_ABI StringRef getString() const
ValueT lookup(const KeyT &Key) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static MemoryEffectsBase readOnly()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase createFromIntValue(uint32_t Data)
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
StringRef saveString(StringRef String)
LLVM_ABI void setFlags(uint64_t Flags)
CfiFunctionIndex & cfiFunctionDecls()
void addBlockCount(uint64_t C)
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
CfiFunctionIndex & cfiFunctionDefs()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
void append(StringRef RHS)
Append from a StringRef.
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
LLVM_ABI void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Triple - Helper class for working with autoconf configuration names.
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
bool isSized() const
Return true if it makes sense to take the size of this type.
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.
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.
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
@ BasicBlock
Various leaf nodes.
static const int NoAliasScopeDeclScopeArg
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_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_ATOMICRMW_OLD
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
@ FUNC_CODE_INST_STOREATOMIC_OLD
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_INST_LANDINGPAD_OLD
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ 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_BITINSERT
@ FUNC_CODE_INST_CMPXCHG_OLD
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
constexpr bool IsBigEndianHost
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
StringMapEntry< Value * > ValueName
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI const std::error_category & BitcodeErrorCategory()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI void UpgradeInlineAsmString(std::string *AsmStr)
Upgrade comment in call to inline asm that represents an objc retain release marker.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
std::error_code make_error_code(BitcodeError E)
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto uninitialized_copy(R &&Src, IterTy Dst)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
bool isa_and_nonnull(const Y &Val)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
LLVM_ABI void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
auto reverse(ContainerTy &&C)
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI std::string UpgradeDataLayoutString(StringRef DL, StringRef Triple)
Upgrade the datalayout string by adding a section for address space pointers.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ ArgMem
Access to memory via argument pointers.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
LLVM_ABI Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
MaybeAlign decodeMaybeAlign(unsigned Value)
Dual operation of the encode function above.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Basic information extracted from a bitcode module to be used for LTO.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
static constexpr DenormalFPEnv createFromIntValue(uint32_t Data)
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const char * BranchWeights
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
std::optional< DataLayoutCallbackFuncTy > DataLayout
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
bool SkipDebugIntrinsicUpgrade
If true, do not auto-upgrade debug intrinsic calls (llvm.dbg.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
Kind
Specifies which kind of type check we should emit for this byte array.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Struct that holds a reference to a particular GUID in a global value summary.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName