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);
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++;
1004 MDStringRef.clear();
1005 GlobalMetadataBitPosIndex.clear();
1019Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1021 if (!GlobalDeclAttachmentPos)
1025 BitstreamCursor TempCursor = Stream;
1026 SmallVector<uint64_t, 64>
Record;
1030 return std::move(Err);
1032 BitstreamEntry
Entry;
1037 return std::move(
E);
1039 switch (
Entry.Kind) {
1042 return error(
"Malformed block");
1045 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1057 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1061 NumGlobalDeclAttachParsed++;
1066 return std::move(Err);
1068 if (Expected<unsigned> MaybeRecord =
1072 return MaybeRecord.takeError();
1073 if (
Record.size() % 2 == 0)
1074 return error(
"Invalid record");
1075 unsigned ValueID =
Record[0];
1076 if (ValueID >= ValueList.size())
1077 return error(
"Invalid record");
1083 if (
Error Err = parseGlobalObjectAttachment(
1084 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1085 return std::move(Err);
1087 return std::move(Err);
1092void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(
Metadata **Val,
1094 if (Callbacks.MDType) {
1095 (*Callbacks.MDType)(Val,
TypeID, Callbacks.GetTypeByID,
1096 Callbacks.GetContainedTypeID);
1104 if (!ModuleLevel && MetadataList.hasFwdRefs())
1105 return error(
"Invalid metadata: fwd refs into function blocks");
1109 auto EntryPos = Stream.GetCurrentBitNo();
1115 PlaceholderQueue Placeholders;
1116 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1117 : DebugInfoUpgradeMode::Partial;
1121 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1123 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1125 return SuccessOrErr.takeError();
1126 if (SuccessOrErr.get()) {
1129 MetadataList.resize(MDStringRef.size() +
1130 GlobalMetadataBitPosIndex.size());
1135 SuccessOrErr = loadGlobalDeclAttachments();
1137 return SuccessOrErr.takeError();
1138 assert(SuccessOrErr.get());
1143 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1146 Stream.ReadBlockEnd();
1147 if (
Error Err = IndexCursor.JumpToBit(EntryPos))
1149 if (
Error Err = Stream.SkipBlock()) {
1160 unsigned NextMetadataNo = MetadataList.size();
1165 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1168 switch (Entry.Kind) {
1171 return error(
"Malformed block");
1174 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1184 ++NumMDRecordLoaded;
1186 Stream.readRecord(Entry.ID,
Record, &Blob)) {
1187 if (
Error Err = parseOneMetadata(
Record, MaybeCode.
get(), Placeholders,
1188 Blob, NextMetadataNo))
1195MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
1196 ++NumMDStringLoaded;
1200 MetadataList.assignValue(MDS,
ID);
1204void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1205 unsigned ID, PlaceholderQueue &Placeholders) {
1206 assert(
ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1207 assert(
ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
1209 if (
auto *MD = MetadataList.lookup(
ID)) {
1213 if (!
N || !
N->isTemporary())
1218 if (
Error Err = IndexCursor.JumpToBit(
1219 GlobalMetadataBitPosIndex[
ID - MDStringRef.size()]))
1223 if (
Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1227 ++NumMDRecordLoaded;
1229 IndexCursor.readRecord(Entry.ID,
Record, &Blob)) {
1231 parseOneMetadata(
Record, MaybeCode.
get(), Placeholders, Blob,
ID))
1241void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1242 PlaceholderQueue &Placeholders) {
1243 DenseSet<unsigned> Temporaries;
1246 Placeholders.getTemporaries(MetadataList, Temporaries);
1249 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
1254 for (
auto ID : Temporaries)
1255 lazyLoadOneMetadata(
ID, Placeholders);
1256 Temporaries.clear();
1260 while (MetadataList.hasFwdRefs())
1261 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1266 MetadataList.tryToResolveCycles();
1270 Placeholders.flush(MetadataList);
1274 Type *Ty,
unsigned TyID) {
1286 if (Idx < ValueList.
size() && ValueList[Idx] &&
1287 ValueList[Idx]->getType() == Ty)
1293Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1294 SmallVectorImpl<uint64_t> &Record,
unsigned Code,
1295 PlaceholderQueue &Placeholders, StringRef Blob,
unsigned &NextMetadataNo) {
1297 bool IsDistinct =
false;
1298 auto getMD = [&](
unsigned ID) ->
Metadata * {
1299 if (
ID < MDStringRef.size())
1300 return lazyLoadOneMDString(
ID);
1302 if (
auto *MD = MetadataList.lookup(
ID))
1306 if (
ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1310 MetadataList.getMetadataFwdRef(NextMetadataNo);
1311 lazyLoadOneMetadata(
ID, Placeholders);
1312 return MetadataList.lookup(
ID);
1315 return MetadataList.getMetadataFwdRef(
ID);
1317 if (
auto *MD = MetadataList.getMetadataIfResolved(
ID))
1319 return &Placeholders.getPlaceholderOp(
ID);
1321 auto getMDOrNull = [&](
unsigned ID) ->
Metadata * {
1323 return getMD(
ID - 1);
1326 auto getMDString = [&](
unsigned ID) -> MDString * {
1329 auto MDS = getMDOrNull(
ID);
1334 auto getDITypeRefOrNull = [&](
unsigned ID) {
1335 return MetadataList.upgradeTypeRef(getMDOrNull(
ID));
1338 auto getMetadataOrConstant = [&](
bool IsMetadata,
1341 return getMDOrNull(Entry);
1343 ConstantInt::get(Type::getInt64Ty(
Context), Entry));
1346#define GET_OR_DISTINCT(CLASS, ARGS) \
1347 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1356 if (
Error E = Stream.ReadCode().moveInto(Code))
1359 ++NumMDRecordLoaded;
1360 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1362 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1364 return MaybeNextBitCode.takeError();
1368 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1369 for (
unsigned i = 0; i !=
Size; ++i) {
1370 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1372 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1381 if (
Record.size() % 2 == 1)
1382 return error(
"Invalid record");
1386 auto dropRecord = [&] {
1390 if (
Record.size() != 2) {
1395 unsigned TyID =
Record[0];
1396 Type *Ty = Callbacks.GetTypeByID(TyID);
1402 Value *
V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1405 return error(
"Invalid value reference from old fn metadata");
1413 if (
Record.size() % 2 == 1)
1414 return error(
"Invalid record");
1418 for (
unsigned i = 0; i !=
Size; i += 2) {
1419 unsigned TyID =
Record[i];
1420 Type *Ty = Callbacks.GetTypeByID(TyID);
1422 return error(
"Invalid record");
1428 return error(
"Invalid value reference from old metadata");
1431 "Expected non-function-local metadata");
1432 callMDTypeCallback(&MD, TyID);
1443 return error(
"Invalid record");
1445 unsigned TyID =
Record[0];
1446 Type *Ty = Callbacks.GetTypeByID(TyID);
1448 return error(
"Invalid record");
1452 return error(
"Invalid value reference from metadata");
1455 callMDTypeCallback(&MD, TyID);
1456 MetadataList.assignValue(MD, NextMetadataNo);
1466 for (
unsigned ID : Record)
1477 return error(
"Invalid record");
1481 unsigned Column =
Record[2];
1483 Metadata *InlinedAt = getMDOrNull(Record[4]);
1485 uint64_t AtomGroup =
Record.size() == 8 ?
Record[6] : 0;
1487 MetadataList.assignValue(
1489 ImplicitCode, AtomGroup, AtomRank)),
1496 return error(
"Invalid record");
1503 return error(
"Invalid record");
1505 auto *Header = getMDString(Record[3]);
1507 for (
unsigned I = 4,
E =
Record.size();
I !=
E; ++
I)
1509 MetadataList.assignValue(
1525 switch (Record[0] >> 1) {
1536 DISubrange, (
Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1537 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1540 return error(
"Invalid record: Unsupported version of DISubrange");
1543 MetadataList.assignValue(Val, NextMetadataNo);
1544 IsDistinct =
Record[0] & 1;
1551 (
Context, getMDOrNull(Record[1]),
1552 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1553 getMDOrNull(Record[4])));
1555 MetadataList.assignValue(Val, NextMetadataNo);
1556 IsDistinct =
Record[0] & 1;
1562 return error(
"Invalid record");
1564 IsDistinct =
Record[0] & 1;
1565 bool IsUnsigned =
Record[0] & 2;
1566 bool IsBigInt =
Record[0] & 4;
1571 const size_t NumWords =
Record.size() - 3;
1576 MetadataList.assignValue(
1585 return error(
"Invalid record");
1587 IsDistinct =
Record[0] & 1;
1588 bool SizeIsMetadata =
Record[0] & 2;
1592 uint32_t NumExtraInhabitants = (
Record.size() > 7) ?
Record[7] : 0;
1593 uint32_t DataSizeInBits = (
Record.size() > 8) ?
Record[8] : 0;
1594 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1596 unsigned LineNo = 0;
1599 File = getMDOrNull(Record[9]);
1601 Scope = getMDOrNull(Record[11]);
1603 MetadataList.assignValue(
1605 (
Context, Record[1], getMDString(Record[2]), File,
1606 LineNo, Scope, SizeInBits, Record[4], Record[5],
1607 NumExtraInhabitants, DataSizeInBits, Flags)),
1614 return error(
"Invalid record");
1616 IsDistinct =
Record[0] & 1;
1617 bool SizeIsMetadata =
Record[0] & 2;
1620 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1624 auto ReadWideInt = [&]() {
1626 unsigned NumWords =
Encoded >> 32;
1633 APInt Numerator = ReadWideInt();
1634 APInt Denominator = ReadWideInt();
1637 unsigned LineNo = 0;
1645 return error(
"Invalid record");
1647 MetadataList.assignValue(
1649 (
Context, Record[1], getMDString(Record[2]), File,
1650 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1651 Record[7], Record[8], Numerator, Denominator)),
1658 return error(
"Invalid record");
1660 IsDistinct =
Record[0] & 1;
1661 bool SizeIsMetadata =
Record[0] & 2;
1662 bool SizeIs8 =
Record.size() == 8;
1665 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1666 unsigned Offset = SizeIs8 ? 5 : 6;
1668 getMetadataOrConstant(SizeIsMetadata, Record[
Offset]);
1670 MetadataList.assignValue(
1672 (
Context, Record[1], getMDString(Record[2]),
1673 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1674 StringLocationExp, SizeInBits, Record[
Offset + 1],
1682 return error(
"Invalid record");
1686 std::optional<unsigned> DWARFAddressSpace;
1687 if (
Record.size() > 12 && Record[12])
1688 DWARFAddressSpace =
Record[12] - 1;
1691 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1696 if (
Record.size() > 14) {
1698 Annotations = getMDOrNull(Record[13]);
1700 PtrAuthData.emplace(Record[14]);
1703 IsDistinct =
Record[0] & 1;
1704 bool SizeIsMetadata =
Record[0] & 2;
1707 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1708 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1710 MetadataList.assignValue(
1712 (
Context, Record[1], getMDString(Record[2]),
1713 getMDOrNull(Record[3]), Record[4],
1714 getDITypeRefOrNull(Record[5]),
1715 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1716 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1717 getDITypeRefOrNull(Record[11]), Annotations)),
1724 return error(
"Invalid record");
1726 IsDistinct =
Record[0] & 1;
1727 bool SizeIsMetadata =
Record[0] & 2;
1730 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1732 MetadataList.assignValue(
1734 (
Context, getMDString(Record[1]),
1735 getMDOrNull(Record[2]), Record[3],
1736 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1737 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1738 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1739 getMDOrNull(Record[12]))),
1746 return error(
"Invalid record");
1750 IsDistinct =
Record[0] & 0x1;
1751 bool IsNotUsedInTypeRef =
Record[0] & 2;
1752 bool SizeIsMetadata =
Record[0] & 4;
1754 MDString *
Name = getMDString(Record[2]);
1759 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1760 return error(
"Alignment value is too large");
1761 uint32_t AlignInBits =
Record[8];
1763 uint32_t NumExtraInhabitants = (
Record.size() > 22) ?
Record[22] : 0;
1766 unsigned RuntimeLang =
Record[12];
1767 std::optional<uint32_t> EnumKind;
1770 Metadata *TemplateParams =
nullptr;
1795 (
Tag == dwarf::DW_TAG_enumeration_type ||
1796 Tag == dwarf::DW_TAG_class_type ||
1797 Tag == dwarf::DW_TAG_structure_type ||
1798 Tag == dwarf::DW_TAG_union_type)) {
1804 StringRef NameStr =
Name->getString();
1806 TemplateParams = getMDOrNull(Record[14]);
1808 BaseType = getDITypeRefOrNull(Record[6]);
1810 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1812 Elements = getMDOrNull(Record[11]);
1813 VTableHolder = getDITypeRefOrNull(Record[13]);
1814 TemplateParams = getMDOrNull(Record[14]);
1818 DataLocation = getMDOrNull(Record[17]);
1819 if (
Record.size() > 19) {
1820 Associated = getMDOrNull(Record[18]);
1821 Allocated = getMDOrNull(Record[19]);
1823 if (
Record.size() > 20) {
1824 Rank = getMDOrNull(Record[20]);
1826 if (
Record.size() > 21) {
1827 Annotations = getMDOrNull(Record[21]);
1829 if (
Record.size() > 23) {
1830 Specification = getMDOrNull(Record[23]);
1833 BitStride = getMDOrNull(Record[25]);
1839 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1841 DICompositeType *CT =
nullptr;
1845 SizeInBits, AlignInBits, OffsetInBits, Specification,
1846 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1847 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1848 Allocated, Rank, Annotations, BitStride);
1855 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1856 VTableHolder, TemplateParams, Identifier, Discriminator,
1857 DataLocation, Associated, Allocated, Rank, Annotations,
1858 Specification, NumExtraInhabitants, BitStride));
1859 if (!IsNotUsedInTypeRef && Identifier)
1862 MetadataList.assignValue(CT, NextMetadataNo);
1868 return error(
"Invalid record");
1869 bool IsOldTypeArray =
Record[0] < 2;
1872 IsDistinct =
Record[0] & 0x1;
1876 Types = MetadataList.upgradeTypeArray(Types);
1878 MetadataList.assignValue(
1887 return error(
"Invalid record");
1891 MetadataList.assignValue(
1894 (
Context,
Record.size() >= 8 ? getMDOrNull(Record[1]) :
nullptr,
1895 getMDOrNull(Record[0 +
Offset]), getMDString(Record[1 +
Offset]),
1896 getMDString(Record[2 +
Offset]), getMDString(Record[3 +
Offset]),
1897 getMDString(Record[4 +
Offset]),
1898 Record.size() <= 7 ? 0 : Record[7],
1899 Record.size() <= 8 ?
false : Record[8])),
1907 return error(
"Invalid record");
1910 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1916 if (
Record.size() > 4 && Record[3] && Record[4])
1918 getMDString(Record[4]));
1919 MetadataList.assignValue(
1921 (
Context, getMDString(Record[1]),
1922 getMDString(Record[2]), Checksum,
1923 Record.size() > 5 ? getMDString(Record[5]) :
nullptr)),
1930 return error(
"Invalid record");
1936 const auto LangVersionMask = (uint64_t(1) << 63);
1937 const bool HasVersionedLanguage =
Record[1] & LangVersionMask;
1944 if (
Record.size() > 23 &&
1946 return error(
"Invalid DICompileUnit dialect value");
1947 const uint16_t Dialect =
1948 Record.size() > 23 ?
static_cast<uint16_t
>(
Record[23]) : uint16_t(0);
1950 auto *CU = DICompileUnit::getDistinct(
1952 HasVersionedLanguage
1953 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
1954 LanguageVersion, Dialect)
1955 : DISourceLanguageName(Record[1], Dialect),
1956 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
1957 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
1958 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1959 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1960 Record.size() <= 15 ?
nullptr : getMDOrNull(Record[15]),
1961 Record.size() <= 14 ? 0 : Record[14],
1962 Record.size() <= 16 ?
true : Record[16],
1963 Record.size() <= 17 ?
false : Record[17],
1964 Record.size() <= 18 ? 0 : Record[18],
1965 Record.size() <= 19 ?
false : Record[19],
1970 Record.size() <= 20 ?
nullptr : getMDString(Record[20]),
1971 Record.size() <= 21 ?
nullptr : getMDString(Record[21]));
1973 MetadataList.assignValue(CU, NextMetadataNo);
1978 CUSubprograms.push_back({CU,
Record[11]});
1983 return error(
"Invalid record");
1985 bool HasSPFlags =
Record[0] & 4;
1998 const unsigned DIFlagMainSubprogram = 1 << 21;
1999 bool HasOldMainSubprogramFlag =
Flags & DIFlagMainSubprogram;
2000 if (HasOldMainSubprogramFlag)
2004 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
2006 if (HasOldMainSubprogramFlag && HasSPFlags)
2007 SPFlags |= DISubprogram::SPFlagMainSubprogram;
2008 else if (!HasSPFlags)
2010 Record[7], Record[8],
2011 Record[14], Record[11],
2012 HasOldMainSubprogramFlag);
2015 IsDistinct = (
Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2021 bool HasUnit =
Record[0] & 2;
2022 if (!HasSPFlags && HasUnit &&
Record.size() < 19)
2023 return error(
"Invalid record");
2024 if (HasSPFlags && !HasUnit)
2025 return error(
"Invalid record");
2028 bool HasThisAdj =
true;
2029 bool HasThrownTypes =
true;
2030 bool HasAnnotations =
false;
2031 bool HasTargetFuncName =
false;
2032 unsigned OffsetA = 0;
2033 unsigned OffsetB = 0;
2036 bool UsesKeyInstructions =
false;
2040 if (
Record.size() >= 19) {
2044 HasThisAdj =
Record.size() >= 20;
2045 HasThrownTypes =
Record.size() >= 21;
2047 HasAnnotations =
Record.size() >= 19;
2048 HasTargetFuncName =
Record.size() >= 20;
2049 UsesKeyInstructions =
Record.size() >= 21 ?
Record[20] : 0;
2052 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2056 getDITypeRefOrNull(Record[1]),
2057 getMDString(Record[2]),
2058 getMDString(Record[3]),
2059 getMDOrNull(Record[4]),
2061 getMDOrNull(Record[6]),
2062 Record[7 + OffsetA],
2063 getDITypeRefOrNull(Record[8 + OffsetA]),
2064 Record[10 + OffsetA],
2065 HasThisAdj ? Record[16 + OffsetB] : 0,
2068 HasUnit ? CUorFn :
nullptr,
2069 getMDOrNull(Record[13 + OffsetB]),
2070 getMDOrNull(Record[14 + OffsetB]),
2071 getMDOrNull(Record[15 + OffsetB]),
2072 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2074 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2076 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2078 UsesKeyInstructions));
2079 MetadataList.assignValue(SP, NextMetadataNo);
2083 NewDistinctSPs.push_back(SP);
2089 if (
F->isMaterializable())
2092 FunctionsWithSPs[
F] =
SP;
2093 else if (!
F->empty())
2094 F->setSubprogram(SP);
2101 return error(
"Invalid record");
2104 MetadataList.assignValue(
2106 (
Context, getMDOrNull(Record[1]),
2107 getMDOrNull(Record[2]), Record[3], Record[4])),
2114 return error(
"Invalid record");
2117 MetadataList.assignValue(
2119 (
Context, getMDOrNull(Record[1]),
2120 getMDOrNull(Record[2]), Record[3])),
2126 IsDistinct =
Record[0] & 1;
2127 MetadataList.assignValue(
2129 (
Context, getMDOrNull(Record[1]),
2130 getMDOrNull(Record[2]), getMDString(Record[3]),
2131 getMDOrNull(Record[4]), Record[5])),
2140 Name = getMDString(Record[2]);
2141 else if (
Record.size() == 5)
2142 Name = getMDString(Record[3]);
2144 return error(
"Invalid record");
2146 IsDistinct =
Record[0] & 1;
2147 bool ExportSymbols =
Record[0] & 2;
2148 MetadataList.assignValue(
2150 (
Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2157 return error(
"Invalid record");
2160 MetadataList.assignValue(
2162 (
Context, Record[1], Record[2], getMDString(Record[3]),
2163 getMDString(Record[4]))),
2170 return error(
"Invalid record");
2173 MetadataList.assignValue(
2175 (
Context, Record[1], Record[2], getMDOrNull(Record[3]),
2176 getMDOrNull(Record[4]))),
2183 return error(
"Invalid record");
2186 MetadataList.assignValue(
2188 (
Context, getMDString(Record[1]),
2189 getDITypeRefOrNull(Record[2]),
2190 (
Record.size() == 4) ? getMDOrNull(Record[3])
2191 : getMDOrNull(
false))),
2198 return error(
"Invalid record");
2202 MetadataList.assignValue(
2204 DITemplateValueParameter,
2205 (
Context, Record[1], getMDString(Record[2]),
2206 getDITypeRefOrNull(Record[3]),
2207 (
Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(
false),
2208 (
Record.size() == 6) ? getMDOrNull(Record[5])
2209 : getMDOrNull(Record[4]))),
2216 return error(
"Invalid record");
2218 IsDistinct =
Record[0] & 1;
2224 Annotations = getMDOrNull(Record[12]);
2226 MetadataList.assignValue(
2228 (
Context, getMDOrNull(Record[1]),
2229 getMDString(Record[2]), getMDString(Record[3]),
2230 getMDOrNull(Record[4]), Record[5],
2231 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2232 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2233 Record[11], Annotations)),
2240 MetadataList.assignValue(
2243 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2244 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2245 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2246 getMDOrNull(Record[10]),
nullptr, Record[11],
nullptr)),
2253 NeedUpgradeToDIGlobalVariableExpression =
true;
2254 Metadata *Expr = getMDOrNull(Record[9]);
2255 uint32_t AlignInBits = 0;
2256 if (
Record.size() > 11) {
2257 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2258 return error(
"Alignment value is too large");
2259 AlignInBits =
Record[11];
2261 GlobalVariable *Attach =
nullptr;
2267 Expr = DIExpression::get(
Context,
2268 {dwarf::DW_OP_constu, CI->getZExtValue(),
2269 dwarf::DW_OP_stack_value});
2276 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2277 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2278 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2279 getMDOrNull(Record[10]),
nullptr, AlignInBits,
nullptr));
2281 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[DGV];
2282 if (Attach || Expr) {
2284 DGVE = DIGlobalVariableExpression::getDistinct(
2292 MetadataList.assignValue(MDNode, NextMetadataNo);
2295 return error(
"Invalid record");
2301 return error(
"Invalid DIAssignID record.");
2303 IsDistinct =
Record[0] & 1;
2305 return error(
"Invalid DIAssignID record. Must be distinct");
2314 return error(
"Invalid record");
2316 IsDistinct =
Record[0] & 1;
2317 bool HasAlignment =
Record[0] & 2;
2321 bool HasTag = !HasAlignment &&
Record.size() > 8;
2323 uint32_t AlignInBits = 0;
2326 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2327 return error(
"Alignment value is too large");
2330 Annotations = getMDOrNull(Record[9]);
2333 MetadataList.assignValue(
2335 (
Context, getMDOrNull(Record[1 + HasTag]),
2336 getMDString(Record[2 + HasTag]),
2337 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2338 getDITypeRefOrNull(Record[5 + HasTag]),
2339 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2346 return error(
"Invalid record");
2348 IsDistinct =
Record[0] & 1;
2351 bool IsArtificial =
Record[0] & 2;
2352 std::optional<unsigned> CoroSuspendIdx;
2354 uint64_t RawSuspendIdx =
Record[6];
2355 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2356 if (RawSuspendIdx > (uint64_t)std::numeric_limits<unsigned>::max())
2357 return error(
"CoroSuspendIdx value is too large");
2358 CoroSuspendIdx = RawSuspendIdx;
2362 MetadataList.assignValue(
2364 (
Context, getMDOrNull(Record[1]),
2365 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2366 Column, IsArtificial, CoroSuspendIdx)),
2373 return error(
"Invalid record");
2375 IsDistinct =
Record[0] & 1;
2380 if (
Error Err = upgradeDIExpression(
Version, Elts, Buffer))
2390 return error(
"Invalid record");
2393 Metadata *Expr = getMDOrNull(Record[2]);
2395 Expr = DIExpression::get(
Context, {});
2396 MetadataList.assignValue(
2398 (
Context, getMDOrNull(Record[1]), Expr)),
2405 return error(
"Invalid record");
2408 MetadataList.assignValue(
2410 (
Context, getMDString(Record[1]),
2411 getMDOrNull(Record[2]), Record[3],
2412 getMDString(Record[5]),
2413 getMDString(Record[4]), Record[6],
2414 getDITypeRefOrNull(Record[7]))),
2421 return error(
"Invalid DIImportedEntity record");
2424 bool HasFile = (
Record.size() >= 7);
2425 bool HasElements = (
Record.size() >= 8);
2426 MetadataList.assignValue(
2428 (
Context, Record[1], getMDOrNull(Record[2]),
2429 getDITypeRefOrNull(Record[3]),
2430 HasFile ? getMDOrNull(Record[6]) :
nullptr,
2431 HasFile ? Record[4] : 0, getMDString(Record[5]),
2432 HasElements ? getMDOrNull(Record[7]) :
nullptr)),
2442 ++NumMDStringLoaded;
2444 MetadataList.assignValue(MD, NextMetadataNo);
2449 auto CreateNextMDString = [&](StringRef Str) {
2453 ++NumMDStringLoaded;
2457 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2462 if (
Record.size() % 2 == 0)
2463 return error(
"Invalid record");
2464 unsigned ValueID =
Record[0];
2465 if (ValueID >= ValueList.size())
2466 return error(
"Invalid record");
2468 if (
Error Err = parseGlobalObjectAttachment(
2469 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2476 if (
Error Err = parseMetadataKindRecord(Record))
2483 for (uint64_t Elt : Record) {
2487 "Invalid record: DIArgList should not contain forward refs");
2489 return error(
"Invalid record");
2499#undef GET_OR_DISTINCT
2502Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2503 ArrayRef<uint64_t> Record, StringRef Blob,
2504 function_ref<
void(StringRef)> CallBack) {
2509 return error(
"Invalid record: metadata strings layout");
2511 unsigned NumStrings =
Record[0];
2512 unsigned StringsOffset =
Record[1];
2514 return error(
"Invalid record: metadata strings with no strings");
2515 if (StringsOffset > Blob.
size())
2516 return error(
"Invalid record: metadata strings corrupt offset");
2518 StringRef Lengths = Blob.
slice(0, StringsOffset);
2519 SimpleBitstreamCursor
R(Lengths);
2521 StringRef Strings = Blob.
drop_front(StringsOffset);
2523 if (
R.AtEndOfStream())
2524 return error(
"Invalid record: metadata strings bad length");
2530 return error(
"Invalid record: metadata strings truncated chars");
2534 }
while (--NumStrings);
2539Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2540 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2542 for (
unsigned I = 0,
E =
Record.size();
I !=
E;
I += 2) {
2543 auto K = MDKindMap.find(Record[
I]);
2544 if (K == MDKindMap.end())
2545 return error(
"Invalid ID");
2549 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
2562 PlaceholderQueue Placeholders;
2566 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2569 switch (Entry.Kind) {
2572 return error(
"Malformed block");
2575 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2584 ++NumMDRecordLoaded;
2588 switch (MaybeRecord.
get()) {
2592 unsigned RecordLength =
Record.size();
2594 return error(
"Invalid record");
2595 if (RecordLength % 2 == 0) {
2597 if (
Error Err = parseGlobalObjectAttachment(
F,
Record))
2604 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
2605 unsigned Kind =
Record[i];
2606 auto I = MDKindMap.find(Kind);
2607 if (
I == MDKindMap.end())
2608 return error(
"Invalid ID");
2609 if (
I->second == LLVMContext::MD_tbaa && StripTBAA)
2612 auto Idx =
Record[i + 1];
2613 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2614 !MetadataList.lookup(Idx)) {
2617 lazyLoadOneMetadata(Idx, Placeholders);
2619 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2629 return error(
"Invalid metadata attachment");
2631 if (HasSeenOldLoopTags &&
I->second == LLVMContext::MD_loop)
2634 if (
I->second == LLVMContext::MD_tbaa) {
2647Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2650 return error(
"Invalid record");
2652 unsigned Kind =
Record[0];
2655 unsigned NewKind = TheModule.getMDKindID(Name.str());
2656 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2657 return error(
"Conflicting METADATA_KIND records");
2671 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2674 switch (Entry.Kind) {
2677 return error(
"Malformed block");
2687 ++NumMDRecordLoaded;
2691 switch (MaybeCode.
get()) {
2704 Pimpl = std::move(RHS.Pimpl);
2708 : Pimpl(
std::
move(RHS.Pimpl)) {}
2716 Stream, TheModule, ValueList,
std::
move(Callbacks), IsImporting)) {}
2718Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2719 return Pimpl->parseMetadata(ModuleLevel);
2727 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2731 return Pimpl->lookupSubprogramForFunction(
F);
2736 return Pimpl->parseMetadataAttachment(
F, InstructionList);
2740 return Pimpl->parseMetadataKinds();
2744 return Pimpl->setStripTBAA(StripTBAA);
2753 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< 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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
@ 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...