65#define DEBUG_TYPE "bitcode-reader"
67STATISTIC(NumMDStringLoaded,
"Number of MDStrings loaded");
68STATISTIC(NumMDNodeTemporary,
"Number of MDNode::Temporary created");
69STATISTIC(NumMDRecordLoaded,
"Number of Metadata records loaded");
75 cl::desc(
"Import full type definitions for ThinLTO."));
79 cl::desc(
"Force disable the lazy-loading on-demand of metadata when "
80 "loading bitcode for importing."));
84class BitcodeReaderMetadataList {
107 LLVMContext &Context;
111 unsigned RefsUpperBound;
114 BitcodeReaderMetadataList(LLVMContext &
C,
size_t RefsUpperBound)
116 RefsUpperBound(std::
min((size_t)std::numeric_limits<unsigned>::
max(),
119 using const_iterator = SmallVector<TrackingMDRef, 1>::const_iterator;
122 unsigned size()
const {
return MetadataPtrs.size(); }
123 void resize(
unsigned N) { MetadataPtrs.resize(
N); }
124 void push_back(
Metadata *MD) { MetadataPtrs.emplace_back(MD); }
125 void clear() { MetadataPtrs.clear(); }
127 void pop_back() { MetadataPtrs.pop_back(); }
128 bool empty()
const {
return MetadataPtrs.empty(); }
129 const_iterator
begin()
const {
return MetadataPtrs.begin(); }
130 const_iterator
end()
const {
return MetadataPtrs.end(); }
132 Metadata *operator[](
unsigned i)
const {
return MetadataPtrs[i]; }
135 if (
I < MetadataPtrs.size())
136 return MetadataPtrs[
I];
140 void shrinkTo(
unsigned N) {
141 assert(
N <=
size() &&
"Invalid shrinkTo request!");
142 assert(ForwardReference.empty() &&
"Unexpected forward refs");
143 assert(UnresolvedNodes.empty() &&
"Unexpected unresolved node");
144 MetadataPtrs.resize(
N);
149 Metadata *getMetadataFwdRef(
unsigned Idx);
155 Metadata *getMetadataIfResolved(
unsigned Idx);
157 MDNode *getMDNodeFwdRefOrNull(
unsigned Idx);
158 void assignValue(
Metadata *MD,
unsigned Idx);
159 void tryToResolveCycles();
160 bool hasFwdRefs()
const {
return !ForwardReference.empty(); }
161 int getNextFwdRef() {
163 return *ForwardReference.begin();
167 void addTypeRef(MDString &
UUID, DICompositeType &CT);
182void BitcodeReaderMetadataList::assignValue(
Metadata *MD,
unsigned Idx) {
184 if (!MDN->isResolved())
185 UnresolvedNodes.
insert(Idx);
195 TrackingMDRef &OldMD = MetadataPtrs[Idx];
203 PrevMD->replaceAllUsesWith(MD);
207Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(
unsigned Idx) {
209 if (Idx >= RefsUpperBound)
215 if (
Metadata *MD = MetadataPtrs[Idx])
222 ++NumMDNodeTemporary;
224 MetadataPtrs[Idx].reset(MD);
228Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(
unsigned Idx) {
231 if (!
N->isResolved())
236MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(
unsigned Idx) {
240void BitcodeReaderMetadataList::tryToResolveCycles() {
246 for (
const auto &
Ref : OldTypeRefs.FwdDecls)
247 OldTypeRefs.Final.insert(
Ref);
248 OldTypeRefs.FwdDecls.clear();
252 for (
const auto &Array : OldTypeRefs.Arrays)
253 Array.second->replaceAllUsesWith(resolveTypeArray(
Array.first.get()));
254 OldTypeRefs.Arrays.clear();
259 for (
const auto &
Ref : OldTypeRefs.Unknown) {
260 if (DICompositeType *CT = OldTypeRefs.Final.lookup(
Ref.first))
261 Ref.second->replaceAllUsesWith(CT);
263 Ref.second->replaceAllUsesWith(
Ref.first);
265 OldTypeRefs.Unknown.clear();
267 if (UnresolvedNodes.
empty())
272 for (
unsigned I : UnresolvedNodes) {
273 auto &MD = MetadataPtrs[
I];
278 assert(!
N->isTemporary() &&
"Unexpected forward reference");
283 UnresolvedNodes.clear();
286void BitcodeReaderMetadataList::addTypeRef(MDString &
UUID,
287 DICompositeType &CT) {
290 OldTypeRefs.FwdDecls.insert(std::make_pair(&
UUID, &CT));
292 OldTypeRefs.Final.insert(std::make_pair(&
UUID, &CT));
300 if (
auto *CT = OldTypeRefs.Final.lookup(
UUID))
303 auto &
Ref = OldTypeRefs.Unknown[
UUID];
309Metadata *BitcodeReaderMetadataList::upgradeTypeArray(
Metadata *MaybeTuple) {
311 if (!Tuple || Tuple->isDistinct())
315 if (!Tuple->isTemporary())
316 return resolveTypeArray(Tuple);
320 OldTypeRefs.Arrays.emplace_back(
321 std::piecewise_construct, std::forward_as_tuple(Tuple),
323 return OldTypeRefs.Arrays.back().second.get();
326Metadata *BitcodeReaderMetadataList::resolveTypeArray(
Metadata *MaybeTuple) {
328 if (!Tuple || Tuple->isDistinct())
333 Ops.reserve(Tuple->getNumOperands());
334 for (
Metadata *MD : Tuple->operands())
335 Ops.push_back(upgradeTypeRef(MD));
342class PlaceholderQueue {
345 std::deque<DistinctMDOperandPlaceholder> PHs;
348 ~PlaceholderQueue() {
350 "PlaceholderQueue hasn't been flushed before being destroyed");
352 bool empty()
const {
return PHs.empty(); }
353 DistinctMDOperandPlaceholder &getPlaceholderOp(
unsigned ID);
354 void flush(BitcodeReaderMetadataList &MetadataList);
358 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
359 DenseSet<unsigned> &Temporaries) {
360 for (
auto &PH : PHs) {
361 auto ID = PH.getID();
362 auto *MD = MetadataList.lookup(ID);
368 if (
N &&
N->isTemporary())
376DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(
unsigned ID) {
377 PHs.emplace_back(ID);
381void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
382 while (!PHs.empty()) {
383 auto *MD = MetadataList.lookup(PHs.front().getID());
384 assert(MD &&
"Flushing placeholder on unassigned MD");
387 assert(MDN->isResolved() &&
388 "Flushing Placeholder while cycles aren't resolved");
390 PHs.front().replaceUseWith(MD);
401 BitcodeReaderMetadataList MetadataList;
414 std::vector<StringRef> MDStringRef;
418 MDString *lazyLoadOneMDString(
unsigned Idx);
421 std::vector<uint64_t> GlobalMetadataBitPosIndex;
426 uint64_t GlobalDeclAttachmentPos = 0;
431 unsigned NumGlobalDeclAttachSkipped = 0;
432 unsigned NumGlobalDeclAttachParsed = 0;
445 void lazyLoadOneMetadata(
unsigned Idx, PlaceholderQueue &Placeholders);
449 std::vector<std::pair<DICompileUnit *, unsigned>> CUSubprograms;
463 bool StripTBAA =
false;
464 bool HasSeenOldLoopTags =
false;
465 bool NeedUpgradeToDIGlobalVariableExpression =
false;
466 bool NeedDeclareExpressionUpgrade =
false;
470 GlobalVariableExpression;
476 bool IsImporting =
false;
479 PlaceholderQueue &Placeholders,
StringRef Blob,
480 unsigned &NextMetadataNo);
487 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
490 void upgradeCUSubprograms() {
491 for (
auto CU_SP : CUSubprograms)
494 for (
auto &
Op : SPs->operands())
496 SP->replaceUnit(CU_SP.first);
497 CUSubprograms.clear();
501 void upgradeCUVariables() {
502 if (!NeedUpgradeToDIGlobalVariableExpression)
506 if (
NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu"))
507 for (
unsigned I = 0, E = CUNodes->getNumOperands();
I != E; ++
I) {
510 for (
unsigned I = 0;
I < GVs->getNumOperands();
I++)
523 for (
auto &GV : TheModule.globals()) {
525 GV.getMetadata(LLVMContext::MD_dbg, MDs);
526 GV.eraseMetadata(LLVMContext::MD_dbg);
534 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
536 GV.addMetadata(LLVMContext::MD_dbg, *MD);
543 if (
auto *SP = ParentSubprogram[S]) {
551 if (!Visited.
insert(S).second)
555 return ParentSubprogram[InitialScope] =
561 using SPToEntitiesMap =
567 template <
typename NodeT>
568 void upgradeOneCULocalsList(SPToEntitiesMap &SPToEntities,
DICompileUnit *
CU,
569 unsigned ListIndex) {
575 return !isa_and_nonnull<DILocalScope>(getScope(cast<NodeT>(MD)));
585 else if (
auto *SP = findEnclosingSubprogram(LS))
586 SPToEntities[SP].push_back(MD);
594 void upgradeCULocals() {
595 NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu");
599 SPToEntitiesMap SPToEntities;
606 upgradeOneCULocalsList<DIGlobalVariableExpression>(SPToEntities,
CU, 6);
608 upgradeOneCULocalsList<DIImportedEntity>(SPToEntities,
CU, 7);
610 upgradeOneCULocalsList<DICompositeType>(SPToEntities,
CU, 4);
614 for (
auto &[SP, Nodes] : SPToEntities)
615 SP->retainNodes(Nodes.begin(), Nodes.end());
616 SPToEntities.clear();
619 ParentSubprogram.clear();
624 void upgradeDeclareExpressions(
Function &
F) {
625 if (!NeedDeclareExpressionUpgrade)
628 auto UpdateDeclareIfNeeded = [&](
auto *Declare) {
629 auto *DIExpr = Declare->getExpression();
630 if (!DIExpr || !DIExpr->startsWithDeref() ||
634 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
641 if (DVR.isDbgDeclare())
642 UpdateDeclareIfNeeded(&DVR);
645 UpdateDeclareIfNeeded(DDI);
650 Error upgradeDIExpression(uint64_t FromVersion,
653 auto N = Expr.
size();
654 switch (FromVersion) {
656 return error(
"Invalid record");
658 if (
N >= 3 && Expr[
N - 3] == dwarf::DW_OP_bit_piece)
663 if (
N && Expr[0] == dwarf::DW_OP_deref) {
664 auto End = Expr.
end();
665 if (Expr.
size() >= 3 &&
667 End = std::prev(End, 3);
668 std::move(std::next(Expr.
begin()), End, Expr.
begin());
669 *std::prev(End) = dwarf::DW_OP_deref;
671 NeedDeclareExpressionUpgrade =
true;
677 while (!SubExpr.empty()) {
682 switch (SubExpr.front()) {
686 case dwarf::DW_OP_constu:
687 case dwarf::DW_OP_minus:
688 case dwarf::DW_OP_plus:
698 HistoricSize = std::min(SubExpr.size(), HistoricSize);
701 switch (SubExpr.front()) {
702 case dwarf::DW_OP_plus:
703 Buffer.
push_back(dwarf::DW_OP_plus_uconst);
704 Buffer.
append(Args.begin(), Args.end());
706 case dwarf::DW_OP_minus:
708 Buffer.
append(Args.begin(), Args.end());
713 Buffer.
append(Args.begin(), Args.end());
718 SubExpr = SubExpr.slice(HistoricSize);
736 enum class DebugInfoUpgradeMode {
745 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
746 if (Mode == DebugInfoUpgradeMode::None)
748 upgradeCUSubprograms();
749 upgradeCUVariables();
750 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
755 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
756 DebugInfoUpgradeMode DIUpgradeMode) {
757 resolveForwardRefsAndPlaceholders(Placeholders);
758 upgradeDebugInfo(DIUpgradeMode);
761 << NewDistinctSPs.size() <<
" subprogram(s).\n");
762 NewDistinctSPs.clear();
765 void callMDTypeCallback(
Metadata **Val,
unsigned TypeID);
771 : MetadataList(TheModule.
getContext(), Stream.SizeInBytes()),
772 ValueList(ValueList), Stream(Stream), Context(TheModule.
getContext()),
773 TheModule(TheModule), Callbacks(
std::
move(Callbacks)),
774 IsImporting(IsImporting) {}
778 bool hasFwdRefs()
const {
return MetadataList.hasFwdRefs(); }
781 if (ID < MDStringRef.size())
782 return lazyLoadOneMDString(ID);
783 if (
auto *MD = MetadataList.lookup(ID))
787 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
788 PlaceholderQueue Placeholders;
789 lazyLoadOneMetadata(ID, Placeholders);
791 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
792 return MetadataList.lookup(ID);
794 return MetadataList.getMetadataFwdRef(ID);
798 return FunctionsWithSPs.lookup(
F);
811 unsigned size()
const {
return MetadataList.size(); }
817MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
818 IndexCursor = Stream;
820 GlobalDeclAttachmentPos = 0;
823 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
831 switch (Entry.Kind) {
834 return error(
"Malformed block");
841 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
843 if (
Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
848 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
849 return std::move(Err);
853 IndexCursor.readRecord(Entry.ID,
Record, &Blob))
856 return MaybeRecord.takeError();
857 unsigned NumStrings =
Record[0];
858 MDStringRef.reserve(NumStrings);
859 auto IndexNextMDString = [&](
StringRef Str) {
860 MDStringRef.push_back(Str);
862 if (
auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
863 return std::move(Err);
869 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
870 return std::move(Err);
872 if (Expected<unsigned> MaybeRecord =
873 IndexCursor.readRecord(
Entry.ID, Record))
876 return MaybeRecord.takeError();
878 return error(
"Invalid record");
880 auto BeginPos = IndexCursor.GetCurrentBitNo();
881 if (
Error Err = IndexCursor.JumpToBit(BeginPos +
Offset))
882 return std::move(Err);
883 Expected<BitstreamEntry> MaybeEntry =
884 IndexCursor.advanceSkippingSubblocks(
890 "Corrupted bitcode: Expected `Record` when trying to find the "
893 if (Expected<unsigned> MaybeCode =
894 IndexCursor.readRecord(
Entry.ID, Record))
896 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
897 "find the Metadata index");
899 return MaybeCode.takeError();
901 auto CurrentValue = BeginPos;
902 GlobalMetadataBitPosIndex.reserve(
Record.size());
903 for (
auto &Elt : Record) {
905 GlobalMetadataBitPosIndex.push_back(CurrentValue);
912 return error(
"Corrupted Metadata block");
915 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
916 return std::move(Err);
920 if (Expected<unsigned> MaybeCode =
921 IndexCursor.readRecord(
Entry.ID, Record)) {
922 Code = MaybeCode.get();
925 return MaybeCode.takeError();
929 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
930 Code = MaybeCode.get();
932 return MaybeCode.takeError();
937 if (Expected<unsigned> MaybeNextBitCode =
938 IndexCursor.readRecord(Code, Record))
941 return MaybeNextBitCode.takeError();
945 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
946 for (
unsigned i = 0; i !=
Size; ++i) {
951 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
952 assert(MD &&
"Invalid metadata: expect fwd ref to MDNode");
958 if (!GlobalDeclAttachmentPos)
959 GlobalDeclAttachmentPos = SavedPos;
961 NumGlobalDeclAttachSkipped++;
1005 MDStringRef.clear();
1006 GlobalMetadataBitPosIndex.clear();
1020Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1022 if (!GlobalDeclAttachmentPos)
1026 BitstreamCursor TempCursor = Stream;
1027 SmallVector<uint64_t, 64>
Record;
1031 return std::move(Err);
1033 BitstreamEntry
Entry;
1038 return std::move(
E);
1040 switch (
Entry.Kind) {
1043 return error(
"Malformed block");
1046 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1058 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1062 NumGlobalDeclAttachParsed++;
1067 return std::move(Err);
1069 if (Expected<unsigned> MaybeRecord =
1073 return MaybeRecord.takeError();
1074 if (
Record.size() % 2 == 0)
1075 return error(
"Invalid record");
1076 unsigned ValueID =
Record[0];
1077 if (ValueID >= ValueList.size())
1078 return error(
"Invalid record");
1084 if (
Error Err = parseGlobalObjectAttachment(
1085 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1086 return std::move(Err);
1088 return std::move(Err);
1093void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(
Metadata **Val,
1095 if (Callbacks.MDType) {
1096 (*Callbacks.MDType)(Val,
TypeID, Callbacks.GetTypeByID,
1097 Callbacks.GetContainedTypeID);
1105 if (!ModuleLevel && MetadataList.hasFwdRefs())
1106 return error(
"Invalid metadata: fwd refs into function blocks");
1110 auto EntryPos = Stream.GetCurrentBitNo();
1116 PlaceholderQueue Placeholders;
1117 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1118 : DebugInfoUpgradeMode::Partial;
1122 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1124 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1126 return SuccessOrErr.takeError();
1127 if (SuccessOrErr.get()) {
1130 MetadataList.resize(MDStringRef.size() +
1131 GlobalMetadataBitPosIndex.size());
1136 SuccessOrErr = loadGlobalDeclAttachments();
1138 return SuccessOrErr.takeError();
1139 assert(SuccessOrErr.get());
1144 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1147 Stream.ReadBlockEnd();
1148 if (
Error Err = IndexCursor.JumpToBit(EntryPos))
1150 if (
Error Err = Stream.SkipBlock()) {
1161 unsigned NextMetadataNo = MetadataList.size();
1166 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1169 switch (Entry.Kind) {
1172 return error(
"Malformed block");
1175 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1185 ++NumMDRecordLoaded;
1187 Stream.readRecord(Entry.ID,
Record, &Blob)) {
1188 if (
Error Err = parseOneMetadata(
Record, MaybeCode.
get(), Placeholders,
1189 Blob, NextMetadataNo))
1196MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
1197 ++NumMDStringLoaded;
1198 if (
Metadata *MD = MetadataList.lookup(ID))
1201 MetadataList.assignValue(MDS, ID);
1205void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1206 unsigned ID, PlaceholderQueue &Placeholders) {
1207 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1208 assert(ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
1210 if (
auto *MD = MetadataList.lookup(ID)) {
1214 if (!
N || !
N->isTemporary())
1219 if (
Error Err = IndexCursor.JumpToBit(
1220 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1224 if (
Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1228 ++NumMDRecordLoaded;
1230 IndexCursor.readRecord(Entry.ID,
Record, &Blob)) {
1232 parseOneMetadata(
Record, MaybeCode.
get(), Placeholders, Blob, ID))
1242void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1243 PlaceholderQueue &Placeholders) {
1244 DenseSet<unsigned> Temporaries;
1247 Placeholders.getTemporaries(MetadataList, Temporaries);
1250 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
1255 for (
auto ID : Temporaries)
1256 lazyLoadOneMetadata(ID, Placeholders);
1257 Temporaries.clear();
1261 while (MetadataList.hasFwdRefs())
1262 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1267 MetadataList.tryToResolveCycles();
1271 Placeholders.flush(MetadataList);
1275 Type *Ty,
unsigned TyID) {
1287 if (Idx < ValueList.
size() && ValueList[Idx] &&
1288 ValueList[Idx]->getType() == Ty)
1294Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1295 SmallVectorImpl<uint64_t> &Record,
unsigned Code,
1296 PlaceholderQueue &Placeholders, StringRef Blob,
unsigned &NextMetadataNo) {
1298 bool IsDistinct =
false;
1299 auto getMD = [&](
unsigned ID) ->
Metadata * {
1300 if (ID < MDStringRef.size())
1301 return lazyLoadOneMDString(ID);
1303 if (
auto *MD = MetadataList.lookup(ID))
1307 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1311 MetadataList.getMetadataFwdRef(NextMetadataNo);
1312 lazyLoadOneMetadata(ID, Placeholders);
1313 return MetadataList.lookup(ID);
1316 return MetadataList.getMetadataFwdRef(ID);
1318 if (
auto *MD = MetadataList.getMetadataIfResolved(ID))
1320 return &Placeholders.getPlaceholderOp(ID);
1322 auto getMDOrNull = [&](
unsigned ID) ->
Metadata * {
1324 return getMD(ID - 1);
1327 auto getMDString = [&](
unsigned ID) -> MDString * {
1330 auto MDS = getMDOrNull(ID);
1335 auto getDITypeRefOrNull = [&](
unsigned ID) {
1336 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1339 auto getMetadataOrConstant = [&](
bool IsMetadata,
1342 return getMDOrNull(Entry);
1344 ConstantInt::get(Type::getInt64Ty(
Context), Entry));
1347#define GET_OR_DISTINCT(CLASS, ARGS) \
1348 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1357 if (
Error E = Stream.ReadCode().moveInto(Code))
1360 ++NumMDRecordLoaded;
1361 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1363 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1365 return MaybeNextBitCode.takeError();
1369 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1370 for (
unsigned i = 0; i !=
Size; ++i) {
1371 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1373 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1382 if (
Record.size() % 2 == 1)
1383 return error(
"Invalid record");
1387 auto dropRecord = [&] {
1391 if (
Record.size() != 2) {
1396 unsigned TyID =
Record[0];
1397 Type *Ty = Callbacks.GetTypeByID(TyID);
1403 Value *
V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1406 return error(
"Invalid value reference from old fn metadata");
1414 if (
Record.size() % 2 == 1)
1415 return error(
"Invalid record");
1419 for (
unsigned i = 0; i !=
Size; i += 2) {
1420 unsigned TyID =
Record[i];
1421 Type *Ty = Callbacks.GetTypeByID(TyID);
1423 return error(
"Invalid record");
1429 return error(
"Invalid value reference from old metadata");
1432 "Expected non-function-local metadata");
1433 callMDTypeCallback(&MD, TyID);
1444 return error(
"Invalid record");
1446 unsigned TyID =
Record[0];
1447 Type *Ty = Callbacks.GetTypeByID(TyID);
1449 return error(
"Invalid record");
1453 return error(
"Invalid value reference from metadata");
1456 callMDTypeCallback(&MD, TyID);
1457 MetadataList.assignValue(MD, NextMetadataNo);
1467 for (
unsigned ID : Record)
1478 return error(
"Invalid record");
1482 unsigned Column =
Record[2];
1484 Metadata *InlinedAt = getMDOrNull(Record[4]);
1488 MetadataList.assignValue(
1490 ImplicitCode, AtomGroup, AtomRank)),
1497 return error(
"Invalid record");
1504 return error(
"Invalid record");
1506 auto *Header = getMDString(Record[3]);
1508 for (
unsigned I = 4,
E =
Record.size();
I !=
E; ++
I)
1510 MetadataList.assignValue(
1526 switch (Record[0] >> 1) {
1537 DISubrange, (
Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1538 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1541 return error(
"Invalid record: Unsupported version of DISubrange");
1544 MetadataList.assignValue(Val, NextMetadataNo);
1545 IsDistinct =
Record[0] & 1;
1552 (
Context, getMDOrNull(Record[1]),
1553 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1554 getMDOrNull(Record[4])));
1556 MetadataList.assignValue(Val, NextMetadataNo);
1557 IsDistinct =
Record[0] & 1;
1563 return error(
"Invalid record");
1565 IsDistinct =
Record[0] & 1;
1566 bool IsUnsigned =
Record[0] & 2;
1567 bool IsBigInt =
Record[0] & 4;
1572 const size_t NumWords =
Record.size() - 3;
1577 MetadataList.assignValue(
1586 return error(
"Invalid record");
1588 IsDistinct =
Record[0] & 1;
1589 bool SizeIsMetadata =
Record[0] & 2;
1593 uint32_t NumExtraInhabitants = (
Record.size() > 7) ?
Record[7] : 0;
1594 uint32_t DataSizeInBits = (
Record.size() > 8) ?
Record[8] : 0;
1595 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1597 unsigned LineNo = 0;
1600 File = getMDOrNull(Record[9]);
1602 Scope = getMDOrNull(Record[11]);
1604 MetadataList.assignValue(
1606 (
Context, Record[1], getMDString(Record[2]), File,
1607 LineNo, Scope, SizeInBits, Record[4], Record[5],
1608 NumExtraInhabitants, DataSizeInBits, Flags)),
1615 return error(
"Invalid record");
1617 IsDistinct =
Record[0] & 1;
1618 bool SizeIsMetadata =
Record[0] & 2;
1621 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1625 auto ReadWideInt = [&]() {
1627 unsigned NumWords =
Encoded >> 32;
1634 APInt Numerator = ReadWideInt();
1635 APInt Denominator = ReadWideInt();
1638 unsigned LineNo = 0;
1646 return error(
"Invalid record");
1648 MetadataList.assignValue(
1650 (
Context, Record[1], getMDString(Record[2]), File,
1651 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1652 Record[7], Record[8], Numerator, Denominator)),
1659 return error(
"Invalid record");
1661 IsDistinct =
Record[0] & 1;
1662 bool SizeIsMetadata =
Record[0] & 2;
1663 bool SizeIs8 =
Record.size() == 8;
1666 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1667 unsigned Offset = SizeIs8 ? 5 : 6;
1669 getMetadataOrConstant(SizeIsMetadata, Record[
Offset]);
1671 MetadataList.assignValue(
1673 (
Context, Record[1], getMDString(Record[2]),
1674 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1675 StringLocationExp, SizeInBits, Record[
Offset + 1],
1683 return error(
"Invalid record");
1687 std::optional<unsigned> DWARFAddressSpace;
1688 if (
Record.size() > 12 && Record[12])
1689 DWARFAddressSpace =
Record[12] - 1;
1692 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1697 if (
Record.size() > 14) {
1699 Annotations = getMDOrNull(Record[13]);
1701 PtrAuthData.emplace(Record[14]);
1704 IsDistinct =
Record[0] & 1;
1705 bool SizeIsMetadata =
Record[0] & 2;
1708 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1709 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1711 MetadataList.assignValue(
1713 (
Context, Record[1], getMDString(Record[2]),
1714 getMDOrNull(Record[3]), Record[4],
1715 getDITypeRefOrNull(Record[5]),
1716 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1717 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1718 getDITypeRefOrNull(Record[11]), Annotations)),
1725 return error(
"Invalid record");
1727 IsDistinct =
Record[0] & 1;
1728 bool SizeIsMetadata =
Record[0] & 2;
1731 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1733 MetadataList.assignValue(
1735 (
Context, getMDString(Record[1]),
1736 getMDOrNull(Record[2]), Record[3],
1737 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1738 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1739 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1740 getMDOrNull(Record[12]))),
1747 return error(
"Invalid record");
1751 IsDistinct =
Record[0] & 0x1;
1752 bool IsNotUsedInTypeRef =
Record[0] & 2;
1753 bool SizeIsMetadata =
Record[0] & 4;
1755 MDString *
Name = getMDString(Record[2]);
1760 if (Record[8] > (
uint64_t)std::numeric_limits<uint32_t>::max())
1761 return error(
"Alignment value is too large");
1762 uint32_t AlignInBits =
Record[8];
1764 uint32_t NumExtraInhabitants = (
Record.size() > 22) ?
Record[22] : 0;
1767 unsigned RuntimeLang =
Record[12];
1768 std::optional<uint32_t> EnumKind;
1771 Metadata *TemplateParams =
nullptr;
1796 (
Tag == dwarf::DW_TAG_enumeration_type ||
1797 Tag == dwarf::DW_TAG_class_type ||
1798 Tag == dwarf::DW_TAG_structure_type ||
1799 Tag == dwarf::DW_TAG_union_type)) {
1805 StringRef NameStr =
Name->getString();
1807 TemplateParams = getMDOrNull(Record[14]);
1809 BaseType = getDITypeRefOrNull(Record[6]);
1811 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1813 Elements = getMDOrNull(Record[11]);
1814 VTableHolder = getDITypeRefOrNull(Record[13]);
1815 TemplateParams = getMDOrNull(Record[14]);
1819 DataLocation = getMDOrNull(Record[17]);
1820 if (
Record.size() > 19) {
1821 Associated = getMDOrNull(Record[18]);
1822 Allocated = getMDOrNull(Record[19]);
1824 if (
Record.size() > 20) {
1825 Rank = getMDOrNull(Record[20]);
1827 if (
Record.size() > 21) {
1828 Annotations = getMDOrNull(Record[21]);
1830 if (
Record.size() > 23) {
1831 Specification = getMDOrNull(Record[23]);
1834 BitStride = getMDOrNull(Record[25]);
1840 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1842 DICompositeType *CT =
nullptr;
1846 SizeInBits, AlignInBits, OffsetInBits, Specification,
1847 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1848 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1849 Allocated, Rank, Annotations, BitStride);
1856 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1857 VTableHolder, TemplateParams, Identifier, Discriminator,
1858 DataLocation, Associated, Allocated, Rank, Annotations,
1859 Specification, NumExtraInhabitants, BitStride));
1860 if (!IsNotUsedInTypeRef && Identifier)
1863 MetadataList.assignValue(CT, NextMetadataNo);
1869 return error(
"Invalid record");
1870 bool IsOldTypeArray =
Record[0] < 2;
1873 IsDistinct =
Record[0] & 0x1;
1877 Types = MetadataList.upgradeTypeArray(Types);
1879 MetadataList.assignValue(
1888 return error(
"Invalid record");
1892 MetadataList.assignValue(
1895 (
Context,
Record.size() >= 8 ? getMDOrNull(Record[1]) :
nullptr,
1896 getMDOrNull(Record[0 +
Offset]), getMDString(Record[1 +
Offset]),
1897 getMDString(Record[2 +
Offset]), getMDString(Record[3 +
Offset]),
1898 getMDString(Record[4 +
Offset]),
1899 Record.size() <= 7 ? 0 : Record[7],
1900 Record.size() <= 8 ?
false : Record[8])),
1908 return error(
"Invalid record");
1911 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1917 if (
Record.size() > 4 && Record[3] && Record[4])
1919 getMDString(Record[4]));
1920 MetadataList.assignValue(
1922 (
Context, getMDString(Record[1]),
1923 getMDString(Record[2]), Checksum,
1924 Record.size() > 5 ? getMDString(Record[5]) :
nullptr)),
1931 return error(
"Invalid record");
1937 const auto LangVersionMask = (
uint64_t(1) << 63);
1938 const bool HasVersionedLanguage =
Record[1] & LangVersionMask;
1945 if (
Record.size() > 23 &&
1947 return error(
"Invalid DICompileUnit dialect value");
1948 const uint16_t Dialect =
1949 Record.size() > 23 ?
static_cast<uint16_t
>(
Record[23]) : uint16_t(0);
1951 auto *CU = DICompileUnit::getDistinct(
1953 HasVersionedLanguage
1954 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
1955 LanguageVersion, Dialect)
1956 : DISourceLanguageName(Record[1], Dialect),
1957 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
1958 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
1959 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1960 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1961 Record.size() <= 15 ?
nullptr : getMDOrNull(Record[15]),
1962 Record.size() <= 14 ? 0 : Record[14],
1963 Record.size() <= 16 ?
true : Record[16],
1964 Record.size() <= 17 ?
false : Record[17],
1965 Record.size() <= 18 ? 0 : Record[18],
1966 Record.size() <= 19 ?
false : Record[19],
1971 Record.size() <= 20 ?
nullptr : getMDString(Record[20]),
1972 Record.size() <= 21 ?
nullptr : getMDString(Record[21]));
1974 MetadataList.assignValue(CU, NextMetadataNo);
1979 CUSubprograms.push_back({CU,
Record[11]});
1984 return error(
"Invalid record");
1986 bool HasSPFlags =
Record[0] & 4;
1999 const unsigned DIFlagMainSubprogram = 1 << 21;
2000 bool HasOldMainSubprogramFlag =
Flags & DIFlagMainSubprogram;
2001 if (HasOldMainSubprogramFlag)
2005 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
2007 if (HasOldMainSubprogramFlag && HasSPFlags)
2008 SPFlags |= DISubprogram::SPFlagMainSubprogram;
2009 else if (!HasSPFlags)
2011 Record[7], Record[8],
2012 Record[14], Record[11],
2013 HasOldMainSubprogramFlag);
2016 IsDistinct = (
Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2022 bool HasUnit =
Record[0] & 2;
2023 if (!HasSPFlags && HasUnit &&
Record.size() < 19)
2024 return error(
"Invalid record");
2025 if (HasSPFlags && !HasUnit)
2026 return error(
"Invalid record");
2029 bool HasThisAdj =
true;
2030 bool HasThrownTypes =
true;
2031 bool HasAnnotations =
false;
2032 bool HasTargetFuncName =
false;
2033 unsigned OffsetA = 0;
2034 unsigned OffsetB = 0;
2037 bool UsesKeyInstructions =
false;
2041 if (
Record.size() >= 19) {
2045 HasThisAdj =
Record.size() >= 20;
2046 HasThrownTypes =
Record.size() >= 21;
2048 HasAnnotations =
Record.size() >= 19;
2049 HasTargetFuncName =
Record.size() >= 20;
2050 UsesKeyInstructions =
Record.size() >= 21 ?
Record[20] : 0;
2053 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2057 getDITypeRefOrNull(Record[1]),
2058 getMDString(Record[2]),
2059 getMDString(Record[3]),
2060 getMDOrNull(Record[4]),
2062 getMDOrNull(Record[6]),
2063 Record[7 + OffsetA],
2064 getDITypeRefOrNull(Record[8 + OffsetA]),
2065 Record[10 + OffsetA],
2066 HasThisAdj ? Record[16 + OffsetB] : 0,
2069 HasUnit ? CUorFn :
nullptr,
2070 getMDOrNull(Record[13 + OffsetB]),
2071 getMDOrNull(Record[14 + OffsetB]),
2072 getMDOrNull(Record[15 + OffsetB]),
2073 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2075 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2077 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2079 UsesKeyInstructions));
2080 MetadataList.assignValue(SP, NextMetadataNo);
2084 NewDistinctSPs.push_back(SP);
2090 if (
F->isMaterializable())
2093 FunctionsWithSPs[
F] =
SP;
2094 else if (!
F->empty())
2095 F->setSubprogram(SP);
2102 return error(
"Invalid record");
2105 MetadataList.assignValue(
2107 (
Context, getMDOrNull(Record[1]),
2108 getMDOrNull(Record[2]), Record[3], Record[4])),
2115 return error(
"Invalid record");
2118 MetadataList.assignValue(
2120 (
Context, getMDOrNull(Record[1]),
2121 getMDOrNull(Record[2]), Record[3])),
2127 IsDistinct =
Record[0] & 1;
2128 MetadataList.assignValue(
2130 (
Context, getMDOrNull(Record[1]),
2131 getMDOrNull(Record[2]), getMDString(Record[3]),
2132 getMDOrNull(Record[4]), Record[5])),
2141 Name = getMDString(Record[2]);
2142 else if (
Record.size() == 5)
2143 Name = getMDString(Record[3]);
2145 return error(
"Invalid record");
2147 IsDistinct =
Record[0] & 1;
2148 bool ExportSymbols =
Record[0] & 2;
2149 MetadataList.assignValue(
2151 (
Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2158 return error(
"Invalid record");
2161 MetadataList.assignValue(
2163 (
Context, Record[1], Record[2], getMDString(Record[3]),
2164 getMDString(Record[4]))),
2171 return error(
"Invalid record");
2174 MetadataList.assignValue(
2176 (
Context, Record[1], Record[2], getMDOrNull(Record[3]),
2177 getMDOrNull(Record[4]))),
2184 return error(
"Invalid record");
2187 MetadataList.assignValue(
2189 (
Context, getMDString(Record[1]),
2190 getDITypeRefOrNull(Record[2]),
2191 (
Record.size() == 4) ? getMDOrNull(Record[3])
2192 : getMDOrNull(
false))),
2199 return error(
"Invalid record");
2203 MetadataList.assignValue(
2205 DITemplateValueParameter,
2206 (
Context, Record[1], getMDString(Record[2]),
2207 getDITypeRefOrNull(Record[3]),
2208 (
Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(
false),
2209 (
Record.size() == 6) ? getMDOrNull(Record[5])
2210 : getMDOrNull(Record[4]))),
2217 return error(
"Invalid record");
2219 IsDistinct =
Record[0] & 1;
2225 Annotations = getMDOrNull(Record[12]);
2227 MetadataList.assignValue(
2229 (
Context, getMDOrNull(Record[1]),
2230 getMDString(Record[2]), getMDString(Record[3]),
2231 getMDOrNull(Record[4]), Record[5],
2232 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2233 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2234 Record[11], Annotations)),
2241 MetadataList.assignValue(
2244 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2245 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2246 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2247 getMDOrNull(Record[10]),
nullptr, Record[11],
nullptr)),
2254 NeedUpgradeToDIGlobalVariableExpression =
true;
2255 Metadata *Expr = getMDOrNull(Record[9]);
2256 uint32_t AlignInBits = 0;
2257 if (
Record.size() > 11) {
2258 if (Record[11] > (
uint64_t)std::numeric_limits<uint32_t>::max())
2259 return error(
"Alignment value is too large");
2260 AlignInBits =
Record[11];
2262 GlobalVariable *Attach =
nullptr;
2268 Expr = DIExpression::get(
Context,
2269 {dwarf::DW_OP_constu, CI->getZExtValue(),
2270 dwarf::DW_OP_stack_value});
2277 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2278 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2279 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2280 getMDOrNull(Record[10]),
nullptr, AlignInBits,
nullptr));
2282 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[DGV];
2283 if (Attach || Expr) {
2285 DGVE = DIGlobalVariableExpression::getDistinct(
2293 MetadataList.assignValue(MDNode, NextMetadataNo);
2296 return error(
"Invalid record");
2302 return error(
"Invalid DIAssignID record.");
2304 IsDistinct =
Record[0] & 1;
2306 return error(
"Invalid DIAssignID record. Must be distinct");
2315 return error(
"Invalid record");
2317 IsDistinct =
Record[0] & 1;
2318 bool HasAlignment =
Record[0] & 2;
2322 bool HasTag = !HasAlignment &&
Record.size() > 8;
2324 uint32_t AlignInBits = 0;
2327 if (Record[8] > (
uint64_t)std::numeric_limits<uint32_t>::max())
2328 return error(
"Alignment value is too large");
2331 Annotations = getMDOrNull(Record[9]);
2334 MetadataList.assignValue(
2336 (
Context, getMDOrNull(Record[1 + HasTag]),
2337 getMDString(Record[2 + HasTag]),
2338 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2339 getDITypeRefOrNull(Record[5 + HasTag]),
2340 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2347 return error(
"Invalid record");
2349 IsDistinct =
Record[0] & 1;
2352 bool IsArtificial =
Record[0] & 2;
2353 std::optional<unsigned> CoroSuspendIdx;
2356 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2357 if (RawSuspendIdx > (
uint64_t)std::numeric_limits<unsigned>::max())
2358 return error(
"CoroSuspendIdx value is too large");
2359 CoroSuspendIdx = RawSuspendIdx;
2363 MetadataList.assignValue(
2365 (
Context, getMDOrNull(Record[1]),
2366 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2367 Column, IsArtificial, CoroSuspendIdx)),
2374 return error(
"Invalid record");
2376 IsDistinct =
Record[0] & 1;
2381 if (
Error Err = upgradeDIExpression(
Version, Elts, Buffer))
2391 return error(
"Invalid record");
2394 Metadata *Expr = getMDOrNull(Record[2]);
2396 Expr = DIExpression::get(
Context, {});
2397 MetadataList.assignValue(
2399 (
Context, getMDOrNull(Record[1]), Expr)),
2406 return error(
"Invalid record");
2409 MetadataList.assignValue(
2411 (
Context, getMDString(Record[1]),
2412 getMDOrNull(Record[2]), Record[3],
2413 getMDString(Record[5]),
2414 getMDString(Record[4]), Record[6],
2415 getDITypeRefOrNull(Record[7]))),
2422 return error(
"Invalid record");
2425 MetadataList.assignValue(
2427 getMDOrNull(Record[2]), Record[3],
2428 getDITypeRefOrNull(Record[4]),
2429 getMDOrNull(Record[5]))),
2436 return error(
"Invalid DIImportedEntity record");
2439 bool HasFile = (
Record.size() >= 7);
2440 bool HasElements = (
Record.size() >= 8);
2441 MetadataList.assignValue(
2443 (
Context, Record[1], getMDOrNull(Record[2]),
2444 getDITypeRefOrNull(Record[3]),
2445 HasFile ? getMDOrNull(Record[6]) :
nullptr,
2446 HasFile ? Record[4] : 0, getMDString(Record[5]),
2447 HasElements ? getMDOrNull(Record[7]) :
nullptr)),
2457 ++NumMDStringLoaded;
2459 MetadataList.assignValue(MD, NextMetadataNo);
2464 auto CreateNextMDString = [&](StringRef Str) {
2468 ++NumMDStringLoaded;
2472 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2477 if (
Record.size() % 2 == 0)
2478 return error(
"Invalid record");
2479 unsigned ValueID =
Record[0];
2480 if (ValueID >= ValueList.size())
2481 return error(
"Invalid record");
2483 if (
Error Err = parseGlobalObjectAttachment(
2484 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2491 if (
Error Err = parseMetadataKindRecord(Record))
2502 "Invalid record: DIArgList should not contain forward refs");
2504 return error(
"Invalid record");
2514#undef GET_OR_DISTINCT
2517Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2518 ArrayRef<uint64_t> Record, StringRef Blob,
2519 function_ref<
void(StringRef)> CallBack) {
2524 return error(
"Invalid record: metadata strings layout");
2526 unsigned NumStrings =
Record[0];
2527 unsigned StringsOffset =
Record[1];
2529 return error(
"Invalid record: metadata strings with no strings");
2530 if (StringsOffset > Blob.
size())
2531 return error(
"Invalid record: metadata strings corrupt offset");
2533 StringRef Lengths = Blob.
slice(0, StringsOffset);
2534 SimpleBitstreamCursor
R(Lengths);
2536 StringRef Strings = Blob.
drop_front(StringsOffset);
2538 if (
R.AtEndOfStream())
2539 return error(
"Invalid record: metadata strings bad length");
2545 return error(
"Invalid record: metadata strings truncated chars");
2549 }
while (--NumStrings);
2554Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2555 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2557 for (
unsigned I = 0,
E =
Record.size();
I !=
E;
I += 2) {
2558 auto K = MDKindMap.find(Record[
I]);
2559 if (K == MDKindMap.end())
2560 return error(
"Invalid ID");
2564 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
2577 PlaceholderQueue Placeholders;
2581 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2584 switch (Entry.Kind) {
2587 return error(
"Malformed block");
2590 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2599 ++NumMDRecordLoaded;
2603 switch (MaybeRecord.
get()) {
2607 unsigned RecordLength =
Record.size();
2609 return error(
"Invalid record");
2610 if (RecordLength % 2 == 0) {
2612 if (
Error Err = parseGlobalObjectAttachment(
F,
Record))
2619 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
2620 unsigned Kind =
Record[i];
2621 auto I = MDKindMap.find(Kind);
2622 if (
I == MDKindMap.end())
2623 return error(
"Invalid ID");
2624 if (
I->second == LLVMContext::MD_tbaa && StripTBAA)
2627 auto Idx =
Record[i + 1];
2628 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2629 !MetadataList.lookup(Idx)) {
2632 lazyLoadOneMetadata(Idx, Placeholders);
2634 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2644 return error(
"Invalid metadata attachment");
2646 if (HasSeenOldLoopTags &&
I->second == LLVMContext::MD_loop)
2649 if (
I->second == LLVMContext::MD_tbaa) {
2662Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2665 return error(
"Invalid record");
2667 unsigned Kind =
Record[0];
2670 unsigned NewKind = TheModule.getMDKindID(Name.str());
2671 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2672 return error(
"Conflicting METADATA_KIND records");
2686 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2689 switch (Entry.Kind) {
2692 return error(
"Malformed block");
2702 ++NumMDRecordLoaded;
2706 switch (MaybeCode.
get()) {
2719 Pimpl = std::move(RHS.Pimpl);
2723 : Pimpl(
std::
move(RHS.Pimpl)) {}
2731 Stream, TheModule, ValueList,
std::
move(Callbacks), IsImporting)) {}
2733Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2734 return Pimpl->parseMetadata(ModuleLevel);
2742 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2746 return Pimpl->lookupSubprogramForFunction(
F);
2751 return Pimpl->parseMetadataAttachment(
F, InstructionList);
2755 return Pimpl->parseMetadataKinds();
2759 return Pimpl->setStripTBAA(StripTBAA);
2768 return Pimpl->upgradeDebugIntrinsics(
F);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
#define LLVM_LIKELY(EXPR)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define GET_OR_DISTINCT(CLASS, ARGS)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallString class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
std::pair< llvm::MachO::Target, std::string > UUID
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
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.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
@ AF_DontPopBlockAtEnd
If this flag is used, the advance() method does not automatically pop the block scope when the end of...
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
MDString * getRawIdentifier() const
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
DISPFlags
Debug info subprogram flags.
bool isForwardDecl() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Implements a dense probed hash-table based set.
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.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
A Module instance is used to store all the information related to an LLVM module.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
iterator_range< op_iterator > operands()
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Implements a dense probed hash-table based set with some number of buckets stored inline.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
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.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
Get the string size.
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
LLVM Value Representation.
std::pair< iterator, bool > insert(const ValueT &V)
An efficient, type-erasing, non-owning reference to a callable.
constexpr char LanguageVersion[]
Key for Kernel::Metadata::mLanguageVersion.
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< CodeNode * > Code
LLVM_ABI Instruction & back() const
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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.
std::error_code make_error_code(BitcodeError E)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
LLVM_ABI MDNode * upgradeInstructionLoopAttachment(MDNode &N)
Upgrade the loop attachment metadata node.
auto cast_or_null(const Y &Val)
bool isa_and_nonnull(const Y &Val)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
static const DIScope * getScope(const NodeT *N)
auto dyn_cast_or_null(const Y &Val)
bool mayBeOldLoopAttachmentTag(StringRef Name)
Check whether a string looks like an old loop attachment tag.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
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...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
@ Ref
The access may reference the value stored in memory.
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
void consumeError(Error Err)
Consume a Error without doing anything.
Implement std::hash so that hash_code can be used in STL containers.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...