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;
472 bool IsImporting =
false;
475 PlaceholderQueue &Placeholders,
StringRef Blob,
476 unsigned &NextMetadataNo);
483 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
486 void upgradeCUSubprograms() {
487 for (
auto CU_SP : CUSubprograms)
490 for (
auto &
Op : SPs->operands())
492 SP->replaceUnit(CU_SP.first);
493 CUSubprograms.clear();
497 void upgradeCUVariables() {
498 if (!NeedUpgradeToDIGlobalVariableExpression)
502 if (
NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu"))
503 for (
unsigned I = 0, E = CUNodes->getNumOperands();
I != E; ++
I) {
506 for (
unsigned I = 0;
I < GVs->getNumOperands();
I++)
511 GVs->replaceOperandWith(
I, DGVE);
516 for (
auto &GV : TheModule.globals()) {
518 GV.getMetadata(LLVMContext::MD_dbg, MDs);
519 GV.eraseMetadata(LLVMContext::MD_dbg);
524 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
526 GV.addMetadata(LLVMContext::MD_dbg, *MD);
533 if (
auto *SP = ParentSubprogram[S]) {
541 if (!Visited.
insert(S).second)
545 return ParentSubprogram[InitialScope] =
553 void upgradeCULocals() {
554 NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu");
559 auto FilterTuple = [
this](
MDNode *
T,
564 Result.push_back(
Op);
584 if (
CU->getRawImportedEntities())
585 for (
Metadata *
Op :
CU->getImportedEntities()->operands()) {
588 MetadataToRemove.
insert(IE);
591 if (
CU->getRawEnumTypes())
595 MetadataToRemove.
insert(Enum);
598 if (MetadataToRemove.
empty())
602 if (
CU->getRawImportedEntities())
603 CU->replaceImportedEntities(
604 FilterTuple(
CU->getImportedEntities().get(), MetadataToRemove));
607 if (
CU->getRawEnumTypes())
608 CU->replaceEnumTypes(
609 FilterTuple(
CU->getEnumTypes().get(), MetadataToRemove));
613 for (
auto *
I : MetadataToRemove) {
616 if (
auto *SP = findEnclosingSubprogram(Scope))
617 SPToEntities[SP].push_back(
I);
621 for (
auto I = SPToEntities.
begin();
I != SPToEntities.
end(); ++
I) {
623 auto RetainedNodes = SP->getRetainedNodes();
626 SP->replaceRetainedNodes(
MDNode::get(Context, MDs));
630 ParentSubprogram.clear();
635 void upgradeDeclareExpressions(
Function &
F) {
636 if (!NeedDeclareExpressionUpgrade)
639 auto UpdateDeclareIfNeeded = [&](
auto *Declare) {
640 auto *DIExpr = Declare->getExpression();
641 if (!DIExpr || !DIExpr->startsWithDeref() ||
645 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
652 if (DVR.isDbgDeclare())
653 UpdateDeclareIfNeeded(&DVR);
656 UpdateDeclareIfNeeded(DDI);
664 auto N = Expr.
size();
665 switch (FromVersion) {
667 return error(
"Invalid record");
669 if (
N >= 3 && Expr[
N - 3] == dwarf::DW_OP_bit_piece)
674 if (
N && Expr[0] == dwarf::DW_OP_deref) {
675 auto End = Expr.
end();
676 if (Expr.
size() >= 3 &&
678 End = std::prev(End, 3);
679 std::move(std::next(Expr.
begin()), End, Expr.
begin());
680 *std::prev(End) = dwarf::DW_OP_deref;
682 NeedDeclareExpressionUpgrade =
true;
688 while (!SubExpr.empty()) {
693 switch (SubExpr.front()) {
697 case dwarf::DW_OP_constu:
698 case dwarf::DW_OP_minus:
699 case dwarf::DW_OP_plus:
709 HistoricSize = std::min(SubExpr.size(), HistoricSize);
712 switch (SubExpr.front()) {
713 case dwarf::DW_OP_plus:
714 Buffer.
push_back(dwarf::DW_OP_plus_uconst);
715 Buffer.
append(Args.begin(), Args.end());
717 case dwarf::DW_OP_minus:
719 Buffer.
append(Args.begin(), Args.end());
724 Buffer.
append(Args.begin(), Args.end());
729 SubExpr = SubExpr.slice(HistoricSize);
747 enum class DebugInfoUpgradeMode {
756 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
757 if (Mode == DebugInfoUpgradeMode::None)
759 upgradeCUSubprograms();
760 upgradeCUVariables();
761 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
766 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
767 DebugInfoUpgradeMode DIUpgradeMode) {
768 resolveForwardRefsAndPlaceholders(Placeholders);
769 upgradeDebugInfo(DIUpgradeMode);
772 << NewDistinctSPs.size() <<
" subprogram(s).\n");
773 NewDistinctSPs.clear();
776 void callMDTypeCallback(
Metadata **Val,
unsigned TypeID);
782 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
783 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
784 TheModule(TheModule), Callbacks(
std::
move(Callbacks)),
785 IsImporting(IsImporting) {}
789 bool hasFwdRefs()
const {
return MetadataList.hasFwdRefs(); }
792 if (
ID < MDStringRef.size())
793 return lazyLoadOneMDString(
ID);
794 if (
auto *MD = MetadataList.lookup(
ID))
798 if (
ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
799 PlaceholderQueue Placeholders;
800 lazyLoadOneMetadata(
ID, Placeholders);
802 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
803 return MetadataList.lookup(
ID);
805 return MetadataList.getMetadataFwdRef(
ID);
809 return FunctionsWithSPs.lookup(
F);
822 unsigned size()
const {
return MetadataList.size(); }
828MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
829 IndexCursor = Stream;
831 GlobalDeclAttachmentPos = 0;
834 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
842 switch (Entry.Kind) {
845 return error(
"Malformed block");
852 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
854 if (
Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
859 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
860 return std::move(Err);
864 IndexCursor.readRecord(Entry.ID,
Record, &Blob))
867 return MaybeRecord.takeError();
868 unsigned NumStrings =
Record[0];
869 MDStringRef.reserve(NumStrings);
870 auto IndexNextMDString = [&](
StringRef Str) {
871 MDStringRef.push_back(Str);
873 if (
auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
874 return std::move(Err);
880 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
881 return std::move(Err);
883 if (Expected<unsigned> MaybeRecord =
884 IndexCursor.readRecord(
Entry.ID, Record))
887 return MaybeRecord.takeError();
889 return error(
"Invalid record");
891 auto BeginPos = IndexCursor.GetCurrentBitNo();
892 if (
Error Err = IndexCursor.JumpToBit(BeginPos +
Offset))
893 return std::move(Err);
894 Expected<BitstreamEntry> MaybeEntry =
895 IndexCursor.advanceSkippingSubblocks(
901 "Corrupted bitcode: Expected `Record` when trying to find the "
904 if (Expected<unsigned> MaybeCode =
905 IndexCursor.readRecord(
Entry.ID, Record))
907 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
908 "find the Metadata index");
910 return MaybeCode.takeError();
912 auto CurrentValue = BeginPos;
913 GlobalMetadataBitPosIndex.reserve(
Record.size());
914 for (
auto &Elt : Record) {
916 GlobalMetadataBitPosIndex.push_back(CurrentValue);
923 return error(
"Corrupted Metadata block");
926 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
927 return std::move(Err);
931 if (Expected<unsigned> MaybeCode =
932 IndexCursor.readRecord(
Entry.ID, Record)) {
933 Code = MaybeCode.get();
936 return MaybeCode.takeError();
940 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
941 Code = MaybeCode.get();
943 return MaybeCode.takeError();
948 if (Expected<unsigned> MaybeNextBitCode =
949 IndexCursor.readRecord(Code, Record))
952 return MaybeNextBitCode.takeError();
956 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
957 for (
unsigned i = 0; i !=
Size; ++i) {
962 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
963 assert(MD &&
"Invalid metadata: expect fwd ref to MDNode");
969 if (!GlobalDeclAttachmentPos)
970 GlobalDeclAttachmentPos = SavedPos;
972 NumGlobalDeclAttachSkipped++;
1015 MDStringRef.clear();
1016 GlobalMetadataBitPosIndex.clear();
1030Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1032 if (!GlobalDeclAttachmentPos)
1036 BitstreamCursor TempCursor = Stream;
1037 SmallVector<uint64_t, 64>
Record;
1041 return std::move(Err);
1043 BitstreamEntry
Entry;
1048 return std::move(
E);
1050 switch (
Entry.Kind) {
1053 return error(
"Malformed block");
1056 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1068 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1072 NumGlobalDeclAttachParsed++;
1077 return std::move(Err);
1079 if (Expected<unsigned> MaybeRecord =
1083 return MaybeRecord.takeError();
1084 if (
Record.size() % 2 == 0)
1085 return error(
"Invalid record");
1086 unsigned ValueID =
Record[0];
1087 if (ValueID >= ValueList.size())
1088 return error(
"Invalid record");
1094 if (
Error Err = parseGlobalObjectAttachment(
1095 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1096 return std::move(Err);
1098 return std::move(Err);
1103void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(
Metadata **Val,
1105 if (Callbacks.MDType) {
1106 (*Callbacks.MDType)(Val,
TypeID, Callbacks.GetTypeByID,
1107 Callbacks.GetContainedTypeID);
1115 if (!ModuleLevel && MetadataList.hasFwdRefs())
1116 return error(
"Invalid metadata: fwd refs into function blocks");
1120 auto EntryPos = Stream.GetCurrentBitNo();
1126 PlaceholderQueue Placeholders;
1127 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1128 : DebugInfoUpgradeMode::Partial;
1132 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1134 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1136 return SuccessOrErr.takeError();
1137 if (SuccessOrErr.get()) {
1140 MetadataList.resize(MDStringRef.size() +
1141 GlobalMetadataBitPosIndex.size());
1146 SuccessOrErr = loadGlobalDeclAttachments();
1148 return SuccessOrErr.takeError();
1149 assert(SuccessOrErr.get());
1154 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1157 Stream.ReadBlockEnd();
1158 if (
Error Err = IndexCursor.JumpToBit(EntryPos))
1160 if (
Error Err = Stream.SkipBlock()) {
1171 unsigned NextMetadataNo = MetadataList.size();
1176 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1179 switch (Entry.Kind) {
1182 return error(
"Malformed block");
1185 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1195 ++NumMDRecordLoaded;
1197 Stream.readRecord(Entry.ID,
Record, &Blob)) {
1198 if (
Error Err = parseOneMetadata(
Record, MaybeCode.
get(), Placeholders,
1199 Blob, NextMetadataNo))
1206MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
1207 ++NumMDStringLoaded;
1211 MetadataList.assignValue(MDS,
ID);
1215void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1216 unsigned ID, PlaceholderQueue &Placeholders) {
1217 assert(
ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1218 assert(
ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
1220 if (
auto *MD = MetadataList.lookup(
ID)) {
1224 if (!
N || !
N->isTemporary())
1229 if (
Error Err = IndexCursor.JumpToBit(
1230 GlobalMetadataBitPosIndex[
ID - MDStringRef.size()]))
1234 if (
Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1238 ++NumMDRecordLoaded;
1240 IndexCursor.readRecord(Entry.ID,
Record, &Blob)) {
1242 parseOneMetadata(
Record, MaybeCode.
get(), Placeholders, Blob,
ID))
1252void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1253 PlaceholderQueue &Placeholders) {
1254 DenseSet<unsigned> Temporaries;
1257 Placeholders.getTemporaries(MetadataList, Temporaries);
1260 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
1265 for (
auto ID : Temporaries)
1266 lazyLoadOneMetadata(
ID, Placeholders);
1267 Temporaries.clear();
1271 while (MetadataList.hasFwdRefs())
1272 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1277 MetadataList.tryToResolveCycles();
1281 Placeholders.flush(MetadataList);
1285 Type *Ty,
unsigned TyID) {
1297 if (Idx < ValueList.
size() && ValueList[Idx] &&
1298 ValueList[Idx]->getType() == Ty)
1304Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1305 SmallVectorImpl<uint64_t> &Record,
unsigned Code,
1306 PlaceholderQueue &Placeholders, StringRef Blob,
unsigned &NextMetadataNo) {
1308 bool IsDistinct =
false;
1309 auto getMD = [&](
unsigned ID) ->
Metadata * {
1310 if (
ID < MDStringRef.size())
1311 return lazyLoadOneMDString(
ID);
1313 if (
auto *MD = MetadataList.lookup(
ID))
1317 if (
ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1321 MetadataList.getMetadataFwdRef(NextMetadataNo);
1322 lazyLoadOneMetadata(
ID, Placeholders);
1323 return MetadataList.lookup(
ID);
1326 return MetadataList.getMetadataFwdRef(
ID);
1328 if (
auto *MD = MetadataList.getMetadataIfResolved(
ID))
1330 return &Placeholders.getPlaceholderOp(
ID);
1332 auto getMDOrNull = [&](
unsigned ID) ->
Metadata * {
1334 return getMD(
ID - 1);
1337 auto getMDString = [&](
unsigned ID) -> MDString * {
1340 auto MDS = getMDOrNull(
ID);
1345 auto getDITypeRefOrNull = [&](
unsigned ID) {
1346 return MetadataList.upgradeTypeRef(getMDOrNull(
ID));
1349 auto getMetadataOrConstant = [&](
bool IsMetadata,
1352 return getMDOrNull(Entry);
1354 ConstantInt::get(Type::getInt64Ty(
Context), Entry));
1357#define GET_OR_DISTINCT(CLASS, ARGS) \
1358 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1367 if (
Error E = Stream.ReadCode().moveInto(Code))
1370 ++NumMDRecordLoaded;
1371 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1373 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1375 return MaybeNextBitCode.takeError();
1379 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1380 for (
unsigned i = 0; i !=
Size; ++i) {
1381 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1383 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1392 if (
Record.size() % 2 == 1)
1393 return error(
"Invalid record");
1397 auto dropRecord = [&] {
1401 if (
Record.size() != 2) {
1406 unsigned TyID =
Record[0];
1407 Type *Ty = Callbacks.GetTypeByID(TyID);
1413 Value *
V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1416 return error(
"Invalid value reference from old fn metadata");
1424 if (
Record.size() % 2 == 1)
1425 return error(
"Invalid record");
1429 for (
unsigned i = 0; i !=
Size; i += 2) {
1430 unsigned TyID =
Record[i];
1431 Type *Ty = Callbacks.GetTypeByID(TyID);
1433 return error(
"Invalid record");
1439 return error(
"Invalid value reference from old metadata");
1442 "Expected non-function-local metadata");
1443 callMDTypeCallback(&MD, TyID);
1454 return error(
"Invalid record");
1456 unsigned TyID =
Record[0];
1457 Type *Ty = Callbacks.GetTypeByID(TyID);
1459 return error(
"Invalid record");
1463 return error(
"Invalid value reference from metadata");
1466 callMDTypeCallback(&MD, TyID);
1467 MetadataList.assignValue(MD, NextMetadataNo);
1477 for (
unsigned ID : Record)
1488 return error(
"Invalid record");
1492 unsigned Column =
Record[2];
1494 Metadata *InlinedAt = getMDOrNull(Record[4]);
1496 uint64_t AtomGroup =
Record.size() == 8 ?
Record[6] : 0;
1498 MetadataList.assignValue(
1500 ImplicitCode, AtomGroup, AtomRank)),
1507 return error(
"Invalid record");
1514 return error(
"Invalid record");
1516 auto *Header = getMDString(Record[3]);
1518 for (
unsigned I = 4,
E =
Record.size();
I !=
E; ++
I)
1520 MetadataList.assignValue(
1536 switch (Record[0] >> 1) {
1547 DISubrange, (
Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1548 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1551 return error(
"Invalid record: Unsupported version of DISubrange");
1554 MetadataList.assignValue(Val, NextMetadataNo);
1555 IsDistinct =
Record[0] & 1;
1562 (
Context, getMDOrNull(Record[1]),
1563 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1564 getMDOrNull(Record[4])));
1566 MetadataList.assignValue(Val, NextMetadataNo);
1567 IsDistinct =
Record[0] & 1;
1573 return error(
"Invalid record");
1575 IsDistinct =
Record[0] & 1;
1576 bool IsUnsigned =
Record[0] & 2;
1577 bool IsBigInt =
Record[0] & 4;
1582 const size_t NumWords =
Record.size() - 3;
1587 MetadataList.assignValue(
1596 return error(
"Invalid record");
1598 IsDistinct =
Record[0] & 1;
1599 bool SizeIsMetadata =
Record[0] & 2;
1603 uint32_t NumExtraInhabitants = (
Record.size() > 7) ?
Record[7] : 0;
1604 uint32_t DataSizeInBits = (
Record.size() > 8) ?
Record[8] : 0;
1605 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1607 unsigned LineNo = 0;
1610 File = getMDOrNull(Record[9]);
1612 Scope = getMDOrNull(Record[11]);
1614 MetadataList.assignValue(
1616 (
Context, Record[1], getMDString(Record[2]), File,
1617 LineNo, Scope, SizeInBits, Record[4], Record[5],
1618 NumExtraInhabitants, DataSizeInBits, Flags)),
1625 return error(
"Invalid record");
1627 IsDistinct =
Record[0] & 1;
1628 bool SizeIsMetadata =
Record[0] & 2;
1631 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1635 auto ReadWideInt = [&]() {
1637 unsigned NumWords =
Encoded >> 32;
1644 APInt Numerator = ReadWideInt();
1645 APInt Denominator = ReadWideInt();
1648 unsigned LineNo = 0;
1656 return error(
"Invalid record");
1658 MetadataList.assignValue(
1660 (
Context, Record[1], getMDString(Record[2]), File,
1661 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1662 Record[7], Record[8], Numerator, Denominator)),
1669 return error(
"Invalid record");
1671 IsDistinct =
Record[0] & 1;
1672 bool SizeIsMetadata =
Record[0] & 2;
1673 bool SizeIs8 =
Record.size() == 8;
1676 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1677 unsigned Offset = SizeIs8 ? 5 : 6;
1679 getMetadataOrConstant(SizeIsMetadata, Record[
Offset]);
1681 MetadataList.assignValue(
1683 (
Context, Record[1], getMDString(Record[2]),
1684 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1685 StringLocationExp, SizeInBits, Record[
Offset + 1],
1693 return error(
"Invalid record");
1697 std::optional<unsigned> DWARFAddressSpace;
1698 if (
Record.size() > 12 && Record[12])
1699 DWARFAddressSpace =
Record[12] - 1;
1702 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1707 if (
Record.size() > 14) {
1709 Annotations = getMDOrNull(Record[13]);
1711 PtrAuthData.emplace(Record[14]);
1714 IsDistinct =
Record[0] & 1;
1715 bool SizeIsMetadata =
Record[0] & 2;
1718 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1719 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1721 MetadataList.assignValue(
1723 (
Context, Record[1], getMDString(Record[2]),
1724 getMDOrNull(Record[3]), Record[4],
1725 getDITypeRefOrNull(Record[5]),
1726 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1727 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1728 getDITypeRefOrNull(Record[11]), Annotations)),
1735 return error(
"Invalid record");
1737 IsDistinct =
Record[0] & 1;
1738 bool SizeIsMetadata =
Record[0] & 2;
1741 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1743 MetadataList.assignValue(
1745 (
Context, getMDString(Record[1]),
1746 getMDOrNull(Record[2]), Record[3],
1747 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1748 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1749 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1750 getMDOrNull(Record[12]))),
1757 return error(
"Invalid record");
1761 IsDistinct =
Record[0] & 0x1;
1762 bool IsNotUsedInTypeRef =
Record[0] & 2;
1763 bool SizeIsMetadata =
Record[0] & 4;
1765 MDString *
Name = getMDString(Record[2]);
1770 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1771 return error(
"Alignment value is too large");
1772 uint32_t AlignInBits =
Record[8];
1774 uint32_t NumExtraInhabitants = (
Record.size() > 22) ?
Record[22] : 0;
1777 unsigned RuntimeLang =
Record[12];
1778 std::optional<uint32_t> EnumKind;
1781 Metadata *TemplateParams =
nullptr;
1806 (
Tag == dwarf::DW_TAG_enumeration_type ||
1807 Tag == dwarf::DW_TAG_class_type ||
1808 Tag == dwarf::DW_TAG_structure_type ||
1809 Tag == dwarf::DW_TAG_union_type)) {
1815 StringRef NameStr =
Name->getString();
1817 TemplateParams = getMDOrNull(Record[14]);
1819 BaseType = getDITypeRefOrNull(Record[6]);
1821 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1823 Elements = getMDOrNull(Record[11]);
1824 VTableHolder = getDITypeRefOrNull(Record[13]);
1825 TemplateParams = getMDOrNull(Record[14]);
1829 DataLocation = getMDOrNull(Record[17]);
1830 if (
Record.size() > 19) {
1831 Associated = getMDOrNull(Record[18]);
1832 Allocated = getMDOrNull(Record[19]);
1834 if (
Record.size() > 20) {
1835 Rank = getMDOrNull(Record[20]);
1837 if (
Record.size() > 21) {
1838 Annotations = getMDOrNull(Record[21]);
1840 if (
Record.size() > 23) {
1841 Specification = getMDOrNull(Record[23]);
1844 BitStride = getMDOrNull(Record[25]);
1850 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1852 DICompositeType *CT =
nullptr;
1856 SizeInBits, AlignInBits, OffsetInBits, Specification,
1857 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1858 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1859 Allocated, Rank, Annotations, BitStride);
1866 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1867 VTableHolder, TemplateParams, Identifier, Discriminator,
1868 DataLocation, Associated, Allocated, Rank, Annotations,
1869 Specification, NumExtraInhabitants, BitStride));
1870 if (!IsNotUsedInTypeRef && Identifier)
1873 MetadataList.assignValue(CT, NextMetadataNo);
1879 return error(
"Invalid record");
1880 bool IsOldTypeArray =
Record[0] < 2;
1883 IsDistinct =
Record[0] & 0x1;
1887 Types = MetadataList.upgradeTypeArray(Types);
1889 MetadataList.assignValue(
1898 return error(
"Invalid record");
1902 MetadataList.assignValue(
1905 (
Context,
Record.size() >= 8 ? getMDOrNull(Record[1]) :
nullptr,
1906 getMDOrNull(Record[0 +
Offset]), getMDString(Record[1 +
Offset]),
1907 getMDString(Record[2 +
Offset]), getMDString(Record[3 +
Offset]),
1908 getMDString(Record[4 +
Offset]),
1909 Record.size() <= 7 ? 0 : Record[7],
1910 Record.size() <= 8 ?
false : Record[8])),
1918 return error(
"Invalid record");
1921 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1927 if (
Record.size() > 4 && Record[3] && Record[4])
1929 getMDString(Record[4]));
1930 MetadataList.assignValue(
1932 (
Context, getMDString(Record[1]),
1933 getMDString(Record[2]), Checksum,
1934 Record.size() > 5 ? getMDString(Record[5]) :
nullptr)),
1941 return error(
"Invalid record");
1947 const auto LangVersionMask = (uint64_t(1) << 63);
1948 const bool HasVersionedLanguage =
Record[1] & LangVersionMask;
1951 auto *CU = DICompileUnit::getDistinct(
1953 HasVersionedLanguage
1954 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
1956 : DISourceLanguageName(Record[1]),
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],
1967 Record.size() <= 20 ?
nullptr : getMDString(Record[20]),
1968 Record.size() <= 21 ?
nullptr : getMDString(Record[21]));
1970 MetadataList.assignValue(CU, NextMetadataNo);
1975 CUSubprograms.push_back({CU,
Record[11]});
1980 return error(
"Invalid record");
1982 bool HasSPFlags =
Record[0] & 4;
1995 const unsigned DIFlagMainSubprogram = 1 << 21;
1996 bool HasOldMainSubprogramFlag =
Flags & DIFlagMainSubprogram;
1997 if (HasOldMainSubprogramFlag)
2001 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
2003 if (HasOldMainSubprogramFlag && HasSPFlags)
2004 SPFlags |= DISubprogram::SPFlagMainSubprogram;
2005 else if (!HasSPFlags)
2007 Record[7], Record[8],
2008 Record[14], Record[11],
2009 HasOldMainSubprogramFlag);
2012 IsDistinct = (
Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2018 bool HasUnit =
Record[0] & 2;
2019 if (!HasSPFlags && HasUnit &&
Record.size() < 19)
2020 return error(
"Invalid record");
2021 if (HasSPFlags && !HasUnit)
2022 return error(
"Invalid record");
2025 bool HasThisAdj =
true;
2026 bool HasThrownTypes =
true;
2027 bool HasAnnotations =
false;
2028 bool HasTargetFuncName =
false;
2029 unsigned OffsetA = 0;
2030 unsigned OffsetB = 0;
2033 bool UsesKeyInstructions =
false;
2037 if (
Record.size() >= 19) {
2041 HasThisAdj =
Record.size() >= 20;
2042 HasThrownTypes =
Record.size() >= 21;
2044 HasAnnotations =
Record.size() >= 19;
2045 HasTargetFuncName =
Record.size() >= 20;
2046 UsesKeyInstructions =
Record.size() >= 21 ?
Record[20] : 0;
2049 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2053 getDITypeRefOrNull(Record[1]),
2054 getMDString(Record[2]),
2055 getMDString(Record[3]),
2056 getMDOrNull(Record[4]),
2058 getMDOrNull(Record[6]),
2059 Record[7 + OffsetA],
2060 getDITypeRefOrNull(Record[8 + OffsetA]),
2061 Record[10 + OffsetA],
2062 HasThisAdj ? Record[16 + OffsetB] : 0,
2065 HasUnit ? CUorFn :
nullptr,
2066 getMDOrNull(Record[13 + OffsetB]),
2067 getMDOrNull(Record[14 + OffsetB]),
2068 getMDOrNull(Record[15 + OffsetB]),
2069 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2071 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2073 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2075 UsesKeyInstructions));
2076 MetadataList.assignValue(SP, NextMetadataNo);
2080 NewDistinctSPs.push_back(SP);
2086 if (
F->isMaterializable())
2089 FunctionsWithSPs[
F] =
SP;
2090 else if (!
F->empty())
2091 F->setSubprogram(SP);
2098 return error(
"Invalid record");
2101 MetadataList.assignValue(
2103 (
Context, getMDOrNull(Record[1]),
2104 getMDOrNull(Record[2]), Record[3], Record[4])),
2111 return error(
"Invalid record");
2114 MetadataList.assignValue(
2116 (
Context, getMDOrNull(Record[1]),
2117 getMDOrNull(Record[2]), Record[3])),
2123 IsDistinct =
Record[0] & 1;
2124 MetadataList.assignValue(
2126 (
Context, getMDOrNull(Record[1]),
2127 getMDOrNull(Record[2]), getMDString(Record[3]),
2128 getMDOrNull(Record[4]), Record[5])),
2137 Name = getMDString(Record[2]);
2138 else if (
Record.size() == 5)
2139 Name = getMDString(Record[3]);
2141 return error(
"Invalid record");
2143 IsDistinct =
Record[0] & 1;
2144 bool ExportSymbols =
Record[0] & 2;
2145 MetadataList.assignValue(
2147 (
Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2154 return error(
"Invalid record");
2157 MetadataList.assignValue(
2159 (
Context, Record[1], Record[2], getMDString(Record[3]),
2160 getMDString(Record[4]))),
2167 return error(
"Invalid record");
2170 MetadataList.assignValue(
2172 (
Context, Record[1], Record[2], getMDOrNull(Record[3]),
2173 getMDOrNull(Record[4]))),
2180 return error(
"Invalid record");
2183 MetadataList.assignValue(
2185 (
Context, getMDString(Record[1]),
2186 getDITypeRefOrNull(Record[2]),
2187 (
Record.size() == 4) ? getMDOrNull(Record[3])
2188 : getMDOrNull(
false))),
2195 return error(
"Invalid record");
2199 MetadataList.assignValue(
2201 DITemplateValueParameter,
2202 (
Context, Record[1], getMDString(Record[2]),
2203 getDITypeRefOrNull(Record[3]),
2204 (
Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(
false),
2205 (
Record.size() == 6) ? getMDOrNull(Record[5])
2206 : getMDOrNull(Record[4]))),
2213 return error(
"Invalid record");
2215 IsDistinct =
Record[0] & 1;
2221 Annotations = getMDOrNull(Record[12]);
2223 MetadataList.assignValue(
2225 (
Context, getMDOrNull(Record[1]),
2226 getMDString(Record[2]), getMDString(Record[3]),
2227 getMDOrNull(Record[4]), Record[5],
2228 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2229 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2230 Record[11], Annotations)),
2237 MetadataList.assignValue(
2240 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2241 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2242 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2243 getMDOrNull(Record[10]),
nullptr, Record[11],
nullptr)),
2250 NeedUpgradeToDIGlobalVariableExpression =
true;
2251 Metadata *Expr = getMDOrNull(Record[9]);
2252 uint32_t AlignInBits = 0;
2253 if (
Record.size() > 11) {
2254 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2255 return error(
"Alignment value is too large");
2256 AlignInBits =
Record[11];
2258 GlobalVariable *Attach =
nullptr;
2264 Expr = DIExpression::get(
Context,
2265 {dwarf::DW_OP_constu, CI->getZExtValue(),
2266 dwarf::DW_OP_stack_value});
2273 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2274 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2275 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2276 getMDOrNull(Record[10]),
nullptr, AlignInBits,
nullptr));
2278 DIGlobalVariableExpression *DGVE =
nullptr;
2280 DGVE = DIGlobalVariableExpression::getDistinct(
2286 MetadataList.assignValue(MDNode, NextMetadataNo);
2289 return error(
"Invalid record");
2295 return error(
"Invalid DIAssignID record.");
2297 IsDistinct =
Record[0] & 1;
2299 return error(
"Invalid DIAssignID record. Must be distinct");
2308 return error(
"Invalid record");
2310 IsDistinct =
Record[0] & 1;
2311 bool HasAlignment =
Record[0] & 2;
2315 bool HasTag = !HasAlignment &&
Record.size() > 8;
2317 uint32_t AlignInBits = 0;
2320 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2321 return error(
"Alignment value is too large");
2324 Annotations = getMDOrNull(Record[9]);
2327 MetadataList.assignValue(
2329 (
Context, getMDOrNull(Record[1 + HasTag]),
2330 getMDString(Record[2 + HasTag]),
2331 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2332 getDITypeRefOrNull(Record[5 + HasTag]),
2333 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2340 return error(
"Invalid record");
2342 IsDistinct =
Record[0] & 1;
2345 bool IsArtificial =
Record[0] & 2;
2346 std::optional<unsigned> CoroSuspendIdx;
2348 uint64_t RawSuspendIdx =
Record[6];
2349 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2350 if (RawSuspendIdx > (uint64_t)std::numeric_limits<unsigned>::max())
2351 return error(
"CoroSuspendIdx value is too large");
2352 CoroSuspendIdx = RawSuspendIdx;
2356 MetadataList.assignValue(
2358 (
Context, getMDOrNull(Record[1]),
2359 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2360 Column, IsArtificial, CoroSuspendIdx)),
2367 return error(
"Invalid record");
2369 IsDistinct =
Record[0] & 1;
2374 if (
Error Err = upgradeDIExpression(
Version, Elts, Buffer))
2384 return error(
"Invalid record");
2387 Metadata *Expr = getMDOrNull(Record[2]);
2389 Expr = DIExpression::get(
Context, {});
2390 MetadataList.assignValue(
2392 (
Context, getMDOrNull(Record[1]), Expr)),
2399 return error(
"Invalid record");
2402 MetadataList.assignValue(
2404 (
Context, getMDString(Record[1]),
2405 getMDOrNull(Record[2]), Record[3],
2406 getMDString(Record[5]),
2407 getMDString(Record[4]), Record[6],
2408 getDITypeRefOrNull(Record[7]))),
2415 return error(
"Invalid DIImportedEntity record");
2418 bool HasFile = (
Record.size() >= 7);
2419 bool HasElements = (
Record.size() >= 8);
2420 MetadataList.assignValue(
2422 (
Context, Record[1], getMDOrNull(Record[2]),
2423 getDITypeRefOrNull(Record[3]),
2424 HasFile ? getMDOrNull(Record[6]) :
nullptr,
2425 HasFile ? Record[4] : 0, getMDString(Record[5]),
2426 HasElements ? getMDOrNull(Record[7]) :
nullptr)),
2436 ++NumMDStringLoaded;
2438 MetadataList.assignValue(MD, NextMetadataNo);
2443 auto CreateNextMDString = [&](StringRef Str) {
2444 ++NumMDStringLoaded;
2448 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2453 if (
Record.size() % 2 == 0)
2454 return error(
"Invalid record");
2455 unsigned ValueID =
Record[0];
2456 if (ValueID >= ValueList.size())
2457 return error(
"Invalid record");
2459 if (
Error Err = parseGlobalObjectAttachment(
2460 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2467 if (
Error Err = parseMetadataKindRecord(Record))
2474 for (uint64_t Elt : Record) {
2478 "Invalid record: DIArgList should not contain forward refs");
2480 return error(
"Invalid record");
2490#undef GET_OR_DISTINCT
2493Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2494 ArrayRef<uint64_t> Record, StringRef Blob,
2495 function_ref<
void(StringRef)> CallBack) {
2500 return error(
"Invalid record: metadata strings layout");
2502 unsigned NumStrings =
Record[0];
2503 unsigned StringsOffset =
Record[1];
2505 return error(
"Invalid record: metadata strings with no strings");
2506 if (StringsOffset > Blob.
size())
2507 return error(
"Invalid record: metadata strings corrupt offset");
2509 StringRef Lengths = Blob.
slice(0, StringsOffset);
2510 SimpleBitstreamCursor
R(Lengths);
2512 StringRef Strings = Blob.
drop_front(StringsOffset);
2514 if (
R.AtEndOfStream())
2515 return error(
"Invalid record: metadata strings bad length");
2521 return error(
"Invalid record: metadata strings truncated chars");
2525 }
while (--NumStrings);
2530Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2531 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2533 for (
unsigned I = 0,
E =
Record.size();
I !=
E;
I += 2) {
2534 auto K = MDKindMap.find(Record[
I]);
2535 if (K == MDKindMap.end())
2536 return error(
"Invalid ID");
2540 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
2553 PlaceholderQueue Placeholders;
2557 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2560 switch (Entry.Kind) {
2563 return error(
"Malformed block");
2566 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2575 ++NumMDRecordLoaded;
2579 switch (MaybeRecord.
get()) {
2583 unsigned RecordLength =
Record.size();
2585 return error(
"Invalid record");
2586 if (RecordLength % 2 == 0) {
2588 if (
Error Err = parseGlobalObjectAttachment(
F,
Record))
2595 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
2596 unsigned Kind =
Record[i];
2597 auto I = MDKindMap.find(Kind);
2598 if (
I == MDKindMap.end())
2599 return error(
"Invalid ID");
2600 if (
I->second == LLVMContext::MD_tbaa && StripTBAA)
2603 auto Idx =
Record[i + 1];
2604 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2605 !MetadataList.lookup(Idx)) {
2608 lazyLoadOneMetadata(Idx, Placeholders);
2610 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2620 return error(
"Invalid metadata attachment");
2622 if (HasSeenOldLoopTags &&
I->second == LLVMContext::MD_loop)
2625 if (
I->second == LLVMContext::MD_tbaa) {
2638Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2641 return error(
"Invalid record");
2643 unsigned Kind =
Record[0];
2646 unsigned NewKind = TheModule.getMDKindID(Name.str());
2647 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2648 return error(
"Conflicting METADATA_KIND records");
2662 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2665 switch (Entry.Kind) {
2668 return error(
"Malformed block");
2678 ++NumMDRecordLoaded;
2682 switch (MaybeCode.
get()) {
2695 Pimpl = std::move(RHS.Pimpl);
2699 : Pimpl(
std::
move(RHS.Pimpl)) {}
2707 Stream, TheModule, ValueList,
std::
move(Callbacks), IsImporting)) {}
2709Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2710 return Pimpl->parseMetadata(ModuleLevel);
2718 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2722 return Pimpl->lookupSubprogramForFunction(
F);
2727 return Pimpl->parseMetadataAttachment(
F, InstructionList);
2731 return Pimpl->parseMetadataKinds();
2735 return Pimpl->setStripTBAA(StripTBAA);
2744 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...
ReachingDefInfo InstSet & ToRemove
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)
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.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static DILocalScope * getRetainedNodeScope(MDNode *N)
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.
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.
A vector that has set insertion semantics.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
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_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.
FunctionAddr VTableAddr Value
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)
auto dyn_cast_or_null(const Y &Val)
FunctionAddr VTableAddr uintptr_t uintptr_t Version
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...