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] =
551 using SPToEntitiesMap =
557 template <
typename NodeT>
558 void upgradeOneCULocalsList(SPToEntitiesMap &SPToEntities,
DICompileUnit *
CU,
559 unsigned ListIndex) {
565 return !isa_and_nonnull<DILocalScope>(getScope(cast<NodeT>(MD)));
575 else if (
auto *SP = findEnclosingSubprogram(LS))
576 SPToEntities[SP].push_back(MD);
584 void upgradeCULocals() {
585 NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu");
589 SPToEntitiesMap SPToEntities;
596 upgradeOneCULocalsList<DIGlobalVariableExpression>(SPToEntities,
CU, 6);
598 upgradeOneCULocalsList<DIImportedEntity>(SPToEntities,
CU, 7);
600 upgradeOneCULocalsList<DICompositeType>(SPToEntities,
CU, 4);
604 for (
auto &[SP, Nodes] : SPToEntities)
605 SP->retainNodes(Nodes.begin(), Nodes.end());
606 SPToEntities.clear();
609 ParentSubprogram.clear();
614 void upgradeDeclareExpressions(
Function &
F) {
615 if (!NeedDeclareExpressionUpgrade)
618 auto UpdateDeclareIfNeeded = [&](
auto *Declare) {
619 auto *DIExpr = Declare->getExpression();
620 if (!DIExpr || !DIExpr->startsWithDeref() ||
624 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
631 if (DVR.isDbgDeclare())
632 UpdateDeclareIfNeeded(&DVR);
635 UpdateDeclareIfNeeded(DDI);
643 auto N = Expr.
size();
644 switch (FromVersion) {
646 return error(
"Invalid record");
648 if (
N >= 3 && Expr[
N - 3] == dwarf::DW_OP_bit_piece)
653 if (
N && Expr[0] == dwarf::DW_OP_deref) {
654 auto End = Expr.
end();
655 if (Expr.
size() >= 3 &&
657 End = std::prev(End, 3);
658 std::move(std::next(Expr.
begin()), End, Expr.
begin());
659 *std::prev(End) = dwarf::DW_OP_deref;
661 NeedDeclareExpressionUpgrade =
true;
667 while (!SubExpr.empty()) {
672 switch (SubExpr.front()) {
676 case dwarf::DW_OP_constu:
677 case dwarf::DW_OP_minus:
678 case dwarf::DW_OP_plus:
688 HistoricSize = std::min(SubExpr.size(), HistoricSize);
691 switch (SubExpr.front()) {
692 case dwarf::DW_OP_plus:
693 Buffer.
push_back(dwarf::DW_OP_plus_uconst);
694 Buffer.
append(Args.begin(), Args.end());
696 case dwarf::DW_OP_minus:
698 Buffer.
append(Args.begin(), Args.end());
703 Buffer.
append(Args.begin(), Args.end());
708 SubExpr = SubExpr.slice(HistoricSize);
726 enum class DebugInfoUpgradeMode {
735 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
736 if (Mode == DebugInfoUpgradeMode::None)
738 upgradeCUSubprograms();
739 upgradeCUVariables();
740 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
745 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
746 DebugInfoUpgradeMode DIUpgradeMode) {
747 resolveForwardRefsAndPlaceholders(Placeholders);
748 upgradeDebugInfo(DIUpgradeMode);
751 << NewDistinctSPs.size() <<
" subprogram(s).\n");
752 NewDistinctSPs.clear();
755 void callMDTypeCallback(
Metadata **Val,
unsigned TypeID);
761 : MetadataList(TheModule.
getContext(), Stream.SizeInBytes()),
762 ValueList(ValueList), Stream(Stream), Context(TheModule.
getContext()),
763 TheModule(TheModule), Callbacks(
std::
move(Callbacks)),
764 IsImporting(IsImporting) {}
768 bool hasFwdRefs()
const {
return MetadataList.hasFwdRefs(); }
771 if (
ID < MDStringRef.size())
772 return lazyLoadOneMDString(
ID);
773 if (
auto *MD = MetadataList.lookup(
ID))
777 if (
ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
778 PlaceholderQueue Placeholders;
779 lazyLoadOneMetadata(
ID, Placeholders);
781 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
782 return MetadataList.lookup(
ID);
784 return MetadataList.getMetadataFwdRef(
ID);
788 return FunctionsWithSPs.lookup(
F);
801 unsigned size()
const {
return MetadataList.size(); }
807MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
808 IndexCursor = Stream;
810 GlobalDeclAttachmentPos = 0;
813 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
821 switch (Entry.Kind) {
824 return error(
"Malformed block");
831 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
833 if (
Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
838 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
839 return std::move(Err);
843 IndexCursor.readRecord(Entry.ID,
Record, &Blob))
846 return MaybeRecord.takeError();
847 unsigned NumStrings =
Record[0];
848 MDStringRef.reserve(NumStrings);
849 auto IndexNextMDString = [&](
StringRef Str) {
850 MDStringRef.push_back(Str);
852 if (
auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
853 return std::move(Err);
859 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
860 return std::move(Err);
862 if (Expected<unsigned> MaybeRecord =
863 IndexCursor.readRecord(
Entry.ID, Record))
866 return MaybeRecord.takeError();
868 return error(
"Invalid record");
870 auto BeginPos = IndexCursor.GetCurrentBitNo();
871 if (
Error Err = IndexCursor.JumpToBit(BeginPos +
Offset))
872 return std::move(Err);
873 Expected<BitstreamEntry> MaybeEntry =
874 IndexCursor.advanceSkippingSubblocks(
880 "Corrupted bitcode: Expected `Record` when trying to find the "
883 if (Expected<unsigned> MaybeCode =
884 IndexCursor.readRecord(
Entry.ID, Record))
886 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
887 "find the Metadata index");
889 return MaybeCode.takeError();
891 auto CurrentValue = BeginPos;
892 GlobalMetadataBitPosIndex.reserve(
Record.size());
893 for (
auto &Elt : Record) {
895 GlobalMetadataBitPosIndex.push_back(CurrentValue);
902 return error(
"Corrupted Metadata block");
905 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
906 return std::move(Err);
910 if (Expected<unsigned> MaybeCode =
911 IndexCursor.readRecord(
Entry.ID, Record)) {
912 Code = MaybeCode.get();
915 return MaybeCode.takeError();
919 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
920 Code = MaybeCode.get();
922 return MaybeCode.takeError();
927 if (Expected<unsigned> MaybeNextBitCode =
928 IndexCursor.readRecord(Code, Record))
931 return MaybeNextBitCode.takeError();
935 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
936 for (
unsigned i = 0; i !=
Size; ++i) {
941 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
942 assert(MD &&
"Invalid metadata: expect fwd ref to MDNode");
948 if (!GlobalDeclAttachmentPos)
949 GlobalDeclAttachmentPos = SavedPos;
951 NumGlobalDeclAttachSkipped++;
995 GlobalMetadataBitPosIndex.clear();
1009Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1011 if (!GlobalDeclAttachmentPos)
1015 BitstreamCursor TempCursor = Stream;
1016 SmallVector<uint64_t, 64>
Record;
1020 return std::move(Err);
1022 BitstreamEntry
Entry;
1027 return std::move(
E);
1029 switch (
Entry.Kind) {
1032 return error(
"Malformed block");
1035 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1047 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1051 NumGlobalDeclAttachParsed++;
1056 return std::move(Err);
1058 if (Expected<unsigned> MaybeRecord =
1062 return MaybeRecord.takeError();
1063 if (
Record.size() % 2 == 0)
1064 return error(
"Invalid record");
1065 unsigned ValueID =
Record[0];
1066 if (ValueID >= ValueList.size())
1067 return error(
"Invalid record");
1073 if (
Error Err = parseGlobalObjectAttachment(
1074 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1075 return std::move(Err);
1077 return std::move(Err);
1082void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(
Metadata **Val,
1084 if (Callbacks.MDType) {
1085 (*Callbacks.MDType)(Val,
TypeID, Callbacks.GetTypeByID,
1086 Callbacks.GetContainedTypeID);
1094 if (!ModuleLevel && MetadataList.hasFwdRefs())
1095 return error(
"Invalid metadata: fwd refs into function blocks");
1099 auto EntryPos = Stream.GetCurrentBitNo();
1105 PlaceholderQueue Placeholders;
1106 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1107 : DebugInfoUpgradeMode::Partial;
1111 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1113 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1115 return SuccessOrErr.takeError();
1116 if (SuccessOrErr.get()) {
1119 MetadataList.resize(MDStringRef.size() +
1120 GlobalMetadataBitPosIndex.size());
1125 SuccessOrErr = loadGlobalDeclAttachments();
1127 return SuccessOrErr.takeError();
1128 assert(SuccessOrErr.get());
1133 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1136 Stream.ReadBlockEnd();
1137 if (
Error Err = IndexCursor.JumpToBit(EntryPos))
1139 if (
Error Err = Stream.SkipBlock()) {
1150 unsigned NextMetadataNo = MetadataList.size();
1155 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1158 switch (Entry.Kind) {
1161 return error(
"Malformed block");
1164 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1174 ++NumMDRecordLoaded;
1176 Stream.readRecord(Entry.ID,
Record, &Blob)) {
1177 if (
Error Err = parseOneMetadata(
Record, MaybeCode.
get(), Placeholders,
1178 Blob, NextMetadataNo))
1185MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
1186 ++NumMDStringLoaded;
1190 MetadataList.assignValue(MDS,
ID);
1194void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1195 unsigned ID, PlaceholderQueue &Placeholders) {
1196 assert(
ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1197 assert(
ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
1199 if (
auto *MD = MetadataList.lookup(
ID)) {
1203 if (!
N || !
N->isTemporary())
1208 if (
Error Err = IndexCursor.JumpToBit(
1209 GlobalMetadataBitPosIndex[
ID - MDStringRef.size()]))
1213 if (
Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1217 ++NumMDRecordLoaded;
1219 IndexCursor.readRecord(Entry.ID,
Record, &Blob)) {
1221 parseOneMetadata(
Record, MaybeCode.
get(), Placeholders, Blob,
ID))
1231void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1232 PlaceholderQueue &Placeholders) {
1233 DenseSet<unsigned> Temporaries;
1236 Placeholders.getTemporaries(MetadataList, Temporaries);
1239 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
1244 for (
auto ID : Temporaries)
1245 lazyLoadOneMetadata(
ID, Placeholders);
1246 Temporaries.clear();
1250 while (MetadataList.hasFwdRefs())
1251 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1256 MetadataList.tryToResolveCycles();
1260 Placeholders.flush(MetadataList);
1264 Type *Ty,
unsigned TyID) {
1276 if (Idx < ValueList.
size() && ValueList[Idx] &&
1277 ValueList[Idx]->getType() == Ty)
1283Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1284 SmallVectorImpl<uint64_t> &Record,
unsigned Code,
1285 PlaceholderQueue &Placeholders, StringRef Blob,
unsigned &NextMetadataNo) {
1287 bool IsDistinct =
false;
1288 auto getMD = [&](
unsigned ID) ->
Metadata * {
1289 if (
ID < MDStringRef.size())
1290 return lazyLoadOneMDString(
ID);
1292 if (
auto *MD = MetadataList.lookup(
ID))
1296 if (
ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1300 MetadataList.getMetadataFwdRef(NextMetadataNo);
1301 lazyLoadOneMetadata(
ID, Placeholders);
1302 return MetadataList.lookup(
ID);
1305 return MetadataList.getMetadataFwdRef(
ID);
1307 if (
auto *MD = MetadataList.getMetadataIfResolved(
ID))
1309 return &Placeholders.getPlaceholderOp(
ID);
1311 auto getMDOrNull = [&](
unsigned ID) ->
Metadata * {
1313 return getMD(
ID - 1);
1316 auto getMDString = [&](
unsigned ID) -> MDString * {
1319 auto MDS = getMDOrNull(
ID);
1324 auto getDITypeRefOrNull = [&](
unsigned ID) {
1325 return MetadataList.upgradeTypeRef(getMDOrNull(
ID));
1328 auto getMetadataOrConstant = [&](
bool IsMetadata,
1331 return getMDOrNull(Entry);
1333 ConstantInt::get(Type::getInt64Ty(
Context), Entry));
1336#define GET_OR_DISTINCT(CLASS, ARGS) \
1337 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1346 if (
Error E = Stream.ReadCode().moveInto(Code))
1349 ++NumMDRecordLoaded;
1350 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1352 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1354 return MaybeNextBitCode.takeError();
1358 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1359 for (
unsigned i = 0; i !=
Size; ++i) {
1360 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1362 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1371 if (
Record.size() % 2 == 1)
1372 return error(
"Invalid record");
1376 auto dropRecord = [&] {
1380 if (
Record.size() != 2) {
1385 unsigned TyID =
Record[0];
1386 Type *Ty = Callbacks.GetTypeByID(TyID);
1392 Value *
V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1395 return error(
"Invalid value reference from old fn metadata");
1403 if (
Record.size() % 2 == 1)
1404 return error(
"Invalid record");
1408 for (
unsigned i = 0; i !=
Size; i += 2) {
1409 unsigned TyID =
Record[i];
1410 Type *Ty = Callbacks.GetTypeByID(TyID);
1412 return error(
"Invalid record");
1418 return error(
"Invalid value reference from old metadata");
1421 "Expected non-function-local metadata");
1422 callMDTypeCallback(&MD, TyID);
1433 return error(
"Invalid record");
1435 unsigned TyID =
Record[0];
1436 Type *Ty = Callbacks.GetTypeByID(TyID);
1438 return error(
"Invalid record");
1442 return error(
"Invalid value reference from metadata");
1445 callMDTypeCallback(&MD, TyID);
1446 MetadataList.assignValue(MD, NextMetadataNo);
1456 for (
unsigned ID : Record)
1467 return error(
"Invalid record");
1471 unsigned Column =
Record[2];
1473 Metadata *InlinedAt = getMDOrNull(Record[4]);
1475 uint64_t AtomGroup =
Record.size() == 8 ?
Record[6] : 0;
1477 MetadataList.assignValue(
1479 ImplicitCode, AtomGroup, AtomRank)),
1486 return error(
"Invalid record");
1493 return error(
"Invalid record");
1495 auto *Header = getMDString(Record[3]);
1497 for (
unsigned I = 4,
E =
Record.size();
I !=
E; ++
I)
1499 MetadataList.assignValue(
1515 switch (Record[0] >> 1) {
1526 DISubrange, (
Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1527 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1530 return error(
"Invalid record: Unsupported version of DISubrange");
1533 MetadataList.assignValue(Val, NextMetadataNo);
1534 IsDistinct =
Record[0] & 1;
1541 (
Context, getMDOrNull(Record[1]),
1542 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1543 getMDOrNull(Record[4])));
1545 MetadataList.assignValue(Val, NextMetadataNo);
1546 IsDistinct =
Record[0] & 1;
1552 return error(
"Invalid record");
1554 IsDistinct =
Record[0] & 1;
1555 bool IsUnsigned =
Record[0] & 2;
1556 bool IsBigInt =
Record[0] & 4;
1561 const size_t NumWords =
Record.size() - 3;
1566 MetadataList.assignValue(
1575 return error(
"Invalid record");
1577 IsDistinct =
Record[0] & 1;
1578 bool SizeIsMetadata =
Record[0] & 2;
1582 uint32_t NumExtraInhabitants = (
Record.size() > 7) ?
Record[7] : 0;
1583 uint32_t DataSizeInBits = (
Record.size() > 8) ?
Record[8] : 0;
1584 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1586 unsigned LineNo = 0;
1589 File = getMDOrNull(Record[9]);
1591 Scope = getMDOrNull(Record[11]);
1593 MetadataList.assignValue(
1595 (
Context, Record[1], getMDString(Record[2]), File,
1596 LineNo, Scope, SizeInBits, Record[4], Record[5],
1597 NumExtraInhabitants, DataSizeInBits, Flags)),
1604 return error(
"Invalid record");
1606 IsDistinct =
Record[0] & 1;
1607 bool SizeIsMetadata =
Record[0] & 2;
1610 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1614 auto ReadWideInt = [&]() {
1616 unsigned NumWords =
Encoded >> 32;
1623 APInt Numerator = ReadWideInt();
1624 APInt Denominator = ReadWideInt();
1627 unsigned LineNo = 0;
1635 return error(
"Invalid record");
1637 MetadataList.assignValue(
1639 (
Context, Record[1], getMDString(Record[2]), File,
1640 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1641 Record[7], Record[8], Numerator, Denominator)),
1648 return error(
"Invalid record");
1650 IsDistinct =
Record[0] & 1;
1651 bool SizeIsMetadata =
Record[0] & 2;
1652 bool SizeIs8 =
Record.size() == 8;
1655 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1656 unsigned Offset = SizeIs8 ? 5 : 6;
1658 getMetadataOrConstant(SizeIsMetadata, Record[
Offset]);
1660 MetadataList.assignValue(
1662 (
Context, Record[1], getMDString(Record[2]),
1663 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1664 StringLocationExp, SizeInBits, Record[
Offset + 1],
1672 return error(
"Invalid record");
1676 std::optional<unsigned> DWARFAddressSpace;
1677 if (
Record.size() > 12 && Record[12])
1678 DWARFAddressSpace =
Record[12] - 1;
1681 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1686 if (
Record.size() > 14) {
1688 Annotations = getMDOrNull(Record[13]);
1690 PtrAuthData.emplace(Record[14]);
1693 IsDistinct =
Record[0] & 1;
1694 bool SizeIsMetadata =
Record[0] & 2;
1697 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1698 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1700 MetadataList.assignValue(
1702 (
Context, Record[1], getMDString(Record[2]),
1703 getMDOrNull(Record[3]), Record[4],
1704 getDITypeRefOrNull(Record[5]),
1705 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1706 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1707 getDITypeRefOrNull(Record[11]), Annotations)),
1714 return error(
"Invalid record");
1716 IsDistinct =
Record[0] & 1;
1717 bool SizeIsMetadata =
Record[0] & 2;
1720 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1722 MetadataList.assignValue(
1724 (
Context, getMDString(Record[1]),
1725 getMDOrNull(Record[2]), Record[3],
1726 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1727 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1728 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1729 getMDOrNull(Record[12]))),
1736 return error(
"Invalid record");
1740 IsDistinct =
Record[0] & 0x1;
1741 bool IsNotUsedInTypeRef =
Record[0] & 2;
1742 bool SizeIsMetadata =
Record[0] & 4;
1744 MDString *
Name = getMDString(Record[2]);
1749 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1750 return error(
"Alignment value is too large");
1751 uint32_t AlignInBits =
Record[8];
1753 uint32_t NumExtraInhabitants = (
Record.size() > 22) ?
Record[22] : 0;
1756 unsigned RuntimeLang =
Record[12];
1757 std::optional<uint32_t> EnumKind;
1760 Metadata *TemplateParams =
nullptr;
1785 (
Tag == dwarf::DW_TAG_enumeration_type ||
1786 Tag == dwarf::DW_TAG_class_type ||
1787 Tag == dwarf::DW_TAG_structure_type ||
1788 Tag == dwarf::DW_TAG_union_type)) {
1794 StringRef NameStr =
Name->getString();
1796 TemplateParams = getMDOrNull(Record[14]);
1798 BaseType = getDITypeRefOrNull(Record[6]);
1800 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1802 Elements = getMDOrNull(Record[11]);
1803 VTableHolder = getDITypeRefOrNull(Record[13]);
1804 TemplateParams = getMDOrNull(Record[14]);
1808 DataLocation = getMDOrNull(Record[17]);
1809 if (
Record.size() > 19) {
1810 Associated = getMDOrNull(Record[18]);
1811 Allocated = getMDOrNull(Record[19]);
1813 if (
Record.size() > 20) {
1814 Rank = getMDOrNull(Record[20]);
1816 if (
Record.size() > 21) {
1817 Annotations = getMDOrNull(Record[21]);
1819 if (
Record.size() > 23) {
1820 Specification = getMDOrNull(Record[23]);
1823 BitStride = getMDOrNull(Record[25]);
1829 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1831 DICompositeType *CT =
nullptr;
1835 SizeInBits, AlignInBits, OffsetInBits, Specification,
1836 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1837 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1838 Allocated, Rank, Annotations, BitStride);
1845 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1846 VTableHolder, TemplateParams, Identifier, Discriminator,
1847 DataLocation, Associated, Allocated, Rank, Annotations,
1848 Specification, NumExtraInhabitants, BitStride));
1849 if (!IsNotUsedInTypeRef && Identifier)
1852 MetadataList.assignValue(CT, NextMetadataNo);
1858 return error(
"Invalid record");
1859 bool IsOldTypeArray =
Record[0] < 2;
1862 IsDistinct =
Record[0] & 0x1;
1866 Types = MetadataList.upgradeTypeArray(Types);
1868 MetadataList.assignValue(
1877 return error(
"Invalid record");
1881 MetadataList.assignValue(
1884 (
Context,
Record.size() >= 8 ? getMDOrNull(Record[1]) :
nullptr,
1885 getMDOrNull(Record[0 +
Offset]), getMDString(Record[1 +
Offset]),
1886 getMDString(Record[2 +
Offset]), getMDString(Record[3 +
Offset]),
1887 getMDString(Record[4 +
Offset]),
1888 Record.size() <= 7 ? 0 : Record[7],
1889 Record.size() <= 8 ?
false : Record[8])),
1897 return error(
"Invalid record");
1900 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1906 if (
Record.size() > 4 && Record[3] && Record[4])
1908 getMDString(Record[4]));
1909 MetadataList.assignValue(
1911 (
Context, getMDString(Record[1]),
1912 getMDString(Record[2]), Checksum,
1913 Record.size() > 5 ? getMDString(Record[5]) :
nullptr)),
1920 return error(
"Invalid record");
1926 const auto LangVersionMask = (uint64_t(1) << 63);
1927 const bool HasVersionedLanguage =
Record[1] & LangVersionMask;
1934 if (
Record.size() > 23 &&
1936 return error(
"Invalid DICompileUnit dialect value");
1937 const uint16_t Dialect =
1938 Record.size() > 23 ?
static_cast<uint16_t
>(
Record[23]) : uint16_t(0);
1940 auto *CU = DICompileUnit::getDistinct(
1942 HasVersionedLanguage
1943 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
1944 LanguageVersion, Dialect)
1945 : DISourceLanguageName(Record[1], Dialect),
1946 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
1947 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
1948 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1949 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1950 Record.size() <= 15 ?
nullptr : getMDOrNull(Record[15]),
1951 Record.size() <= 14 ? 0 : Record[14],
1952 Record.size() <= 16 ?
true : Record[16],
1953 Record.size() <= 17 ?
false : Record[17],
1954 Record.size() <= 18 ? 0 : Record[18],
1955 Record.size() <= 19 ?
false : Record[19],
1960 Record.size() <= 20 ?
nullptr : getMDString(Record[20]),
1961 Record.size() <= 21 ?
nullptr : getMDString(Record[21]));
1963 MetadataList.assignValue(CU, NextMetadataNo);
1968 CUSubprograms.push_back({CU,
Record[11]});
1973 return error(
"Invalid record");
1975 bool HasSPFlags =
Record[0] & 4;
1988 const unsigned DIFlagMainSubprogram = 1 << 21;
1989 bool HasOldMainSubprogramFlag =
Flags & DIFlagMainSubprogram;
1990 if (HasOldMainSubprogramFlag)
1994 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1996 if (HasOldMainSubprogramFlag && HasSPFlags)
1997 SPFlags |= DISubprogram::SPFlagMainSubprogram;
1998 else if (!HasSPFlags)
2000 Record[7], Record[8],
2001 Record[14], Record[11],
2002 HasOldMainSubprogramFlag);
2005 IsDistinct = (
Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2011 bool HasUnit =
Record[0] & 2;
2012 if (!HasSPFlags && HasUnit &&
Record.size() < 19)
2013 return error(
"Invalid record");
2014 if (HasSPFlags && !HasUnit)
2015 return error(
"Invalid record");
2018 bool HasThisAdj =
true;
2019 bool HasThrownTypes =
true;
2020 bool HasAnnotations =
false;
2021 bool HasTargetFuncName =
false;
2022 unsigned OffsetA = 0;
2023 unsigned OffsetB = 0;
2026 bool UsesKeyInstructions =
false;
2030 if (
Record.size() >= 19) {
2034 HasThisAdj =
Record.size() >= 20;
2035 HasThrownTypes =
Record.size() >= 21;
2037 HasAnnotations =
Record.size() >= 19;
2038 HasTargetFuncName =
Record.size() >= 20;
2039 UsesKeyInstructions =
Record.size() >= 21 ?
Record[20] : 0;
2042 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2046 getDITypeRefOrNull(Record[1]),
2047 getMDString(Record[2]),
2048 getMDString(Record[3]),
2049 getMDOrNull(Record[4]),
2051 getMDOrNull(Record[6]),
2052 Record[7 + OffsetA],
2053 getDITypeRefOrNull(Record[8 + OffsetA]),
2054 Record[10 + OffsetA],
2055 HasThisAdj ? Record[16 + OffsetB] : 0,
2058 HasUnit ? CUorFn :
nullptr,
2059 getMDOrNull(Record[13 + OffsetB]),
2060 getMDOrNull(Record[14 + OffsetB]),
2061 getMDOrNull(Record[15 + OffsetB]),
2062 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2064 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2066 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2068 UsesKeyInstructions));
2069 MetadataList.assignValue(SP, NextMetadataNo);
2073 NewDistinctSPs.push_back(SP);
2079 if (
F->isMaterializable())
2082 FunctionsWithSPs[
F] =
SP;
2083 else if (!
F->empty())
2084 F->setSubprogram(SP);
2091 return error(
"Invalid record");
2094 MetadataList.assignValue(
2096 (
Context, getMDOrNull(Record[1]),
2097 getMDOrNull(Record[2]), Record[3], Record[4])),
2104 return error(
"Invalid record");
2107 MetadataList.assignValue(
2109 (
Context, getMDOrNull(Record[1]),
2110 getMDOrNull(Record[2]), Record[3])),
2116 IsDistinct =
Record[0] & 1;
2117 MetadataList.assignValue(
2119 (
Context, getMDOrNull(Record[1]),
2120 getMDOrNull(Record[2]), getMDString(Record[3]),
2121 getMDOrNull(Record[4]), Record[5])),
2130 Name = getMDString(Record[2]);
2131 else if (
Record.size() == 5)
2132 Name = getMDString(Record[3]);
2134 return error(
"Invalid record");
2136 IsDistinct =
Record[0] & 1;
2137 bool ExportSymbols =
Record[0] & 2;
2138 MetadataList.assignValue(
2140 (
Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2147 return error(
"Invalid record");
2150 MetadataList.assignValue(
2152 (
Context, Record[1], Record[2], getMDString(Record[3]),
2153 getMDString(Record[4]))),
2160 return error(
"Invalid record");
2163 MetadataList.assignValue(
2165 (
Context, Record[1], Record[2], getMDOrNull(Record[3]),
2166 getMDOrNull(Record[4]))),
2173 return error(
"Invalid record");
2176 MetadataList.assignValue(
2178 (
Context, getMDString(Record[1]),
2179 getDITypeRefOrNull(Record[2]),
2180 (
Record.size() == 4) ? getMDOrNull(Record[3])
2181 : getMDOrNull(
false))),
2188 return error(
"Invalid record");
2192 MetadataList.assignValue(
2194 DITemplateValueParameter,
2195 (
Context, Record[1], getMDString(Record[2]),
2196 getDITypeRefOrNull(Record[3]),
2197 (
Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(
false),
2198 (
Record.size() == 6) ? getMDOrNull(Record[5])
2199 : getMDOrNull(Record[4]))),
2206 return error(
"Invalid record");
2208 IsDistinct =
Record[0] & 1;
2214 Annotations = getMDOrNull(Record[12]);
2216 MetadataList.assignValue(
2218 (
Context, getMDOrNull(Record[1]),
2219 getMDString(Record[2]), getMDString(Record[3]),
2220 getMDOrNull(Record[4]), Record[5],
2221 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2222 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2223 Record[11], Annotations)),
2230 MetadataList.assignValue(
2233 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2234 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2235 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2236 getMDOrNull(Record[10]),
nullptr, Record[11],
nullptr)),
2243 NeedUpgradeToDIGlobalVariableExpression =
true;
2244 Metadata *Expr = getMDOrNull(Record[9]);
2245 uint32_t AlignInBits = 0;
2246 if (
Record.size() > 11) {
2247 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2248 return error(
"Alignment value is too large");
2249 AlignInBits =
Record[11];
2251 GlobalVariable *Attach =
nullptr;
2257 Expr = DIExpression::get(
Context,
2258 {dwarf::DW_OP_constu, CI->getZExtValue(),
2259 dwarf::DW_OP_stack_value});
2266 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2267 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2268 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2269 getMDOrNull(Record[10]),
nullptr, AlignInBits,
nullptr));
2271 DIGlobalVariableExpression *DGVE =
nullptr;
2273 DGVE = DIGlobalVariableExpression::getDistinct(
2279 MetadataList.assignValue(MDNode, NextMetadataNo);
2282 return error(
"Invalid record");
2288 return error(
"Invalid DIAssignID record.");
2290 IsDistinct =
Record[0] & 1;
2292 return error(
"Invalid DIAssignID record. Must be distinct");
2301 return error(
"Invalid record");
2303 IsDistinct =
Record[0] & 1;
2304 bool HasAlignment =
Record[0] & 2;
2308 bool HasTag = !HasAlignment &&
Record.size() > 8;
2310 uint32_t AlignInBits = 0;
2313 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2314 return error(
"Alignment value is too large");
2317 Annotations = getMDOrNull(Record[9]);
2320 MetadataList.assignValue(
2322 (
Context, getMDOrNull(Record[1 + HasTag]),
2323 getMDString(Record[2 + HasTag]),
2324 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2325 getDITypeRefOrNull(Record[5 + HasTag]),
2326 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2333 return error(
"Invalid record");
2335 IsDistinct =
Record[0] & 1;
2338 bool IsArtificial =
Record[0] & 2;
2339 std::optional<unsigned> CoroSuspendIdx;
2341 uint64_t RawSuspendIdx =
Record[6];
2342 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2343 if (RawSuspendIdx > (uint64_t)std::numeric_limits<unsigned>::max())
2344 return error(
"CoroSuspendIdx value is too large");
2345 CoroSuspendIdx = RawSuspendIdx;
2349 MetadataList.assignValue(
2351 (
Context, getMDOrNull(Record[1]),
2352 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2353 Column, IsArtificial, CoroSuspendIdx)),
2360 return error(
"Invalid record");
2362 IsDistinct =
Record[0] & 1;
2367 if (
Error Err = upgradeDIExpression(
Version, Elts, Buffer))
2377 return error(
"Invalid record");
2380 Metadata *Expr = getMDOrNull(Record[2]);
2382 Expr = DIExpression::get(
Context, {});
2383 MetadataList.assignValue(
2385 (
Context, getMDOrNull(Record[1]), Expr)),
2392 return error(
"Invalid record");
2395 MetadataList.assignValue(
2397 (
Context, getMDString(Record[1]),
2398 getMDOrNull(Record[2]), Record[3],
2399 getMDString(Record[5]),
2400 getMDString(Record[4]), Record[6],
2401 getDITypeRefOrNull(Record[7]))),
2408 return error(
"Invalid DIImportedEntity record");
2411 bool HasFile = (
Record.size() >= 7);
2412 bool HasElements = (
Record.size() >= 8);
2413 MetadataList.assignValue(
2415 (
Context, Record[1], getMDOrNull(Record[2]),
2416 getDITypeRefOrNull(Record[3]),
2417 HasFile ? getMDOrNull(Record[6]) :
nullptr,
2418 HasFile ? Record[4] : 0, getMDString(Record[5]),
2419 HasElements ? getMDOrNull(Record[7]) :
nullptr)),
2429 ++NumMDStringLoaded;
2431 MetadataList.assignValue(MD, NextMetadataNo);
2436 auto CreateNextMDString = [&](StringRef Str) {
2437 ++NumMDStringLoaded;
2441 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2446 if (
Record.size() % 2 == 0)
2447 return error(
"Invalid record");
2448 unsigned ValueID =
Record[0];
2449 if (ValueID >= ValueList.size())
2450 return error(
"Invalid record");
2452 if (
Error Err = parseGlobalObjectAttachment(
2453 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2460 if (
Error Err = parseMetadataKindRecord(Record))
2467 for (uint64_t Elt : Record) {
2471 "Invalid record: DIArgList should not contain forward refs");
2473 return error(
"Invalid record");
2483#undef GET_OR_DISTINCT
2486Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2487 ArrayRef<uint64_t> Record, StringRef Blob,
2488 function_ref<
void(StringRef)> CallBack) {
2493 return error(
"Invalid record: metadata strings layout");
2495 unsigned NumStrings =
Record[0];
2496 unsigned StringsOffset =
Record[1];
2498 return error(
"Invalid record: metadata strings with no strings");
2499 if (StringsOffset > Blob.
size())
2500 return error(
"Invalid record: metadata strings corrupt offset");
2502 StringRef Lengths = Blob.
slice(0, StringsOffset);
2503 SimpleBitstreamCursor
R(Lengths);
2505 StringRef Strings = Blob.
drop_front(StringsOffset);
2507 if (
R.AtEndOfStream())
2508 return error(
"Invalid record: metadata strings bad length");
2514 return error(
"Invalid record: metadata strings truncated chars");
2518 }
while (--NumStrings);
2523Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2524 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2526 for (
unsigned I = 0,
E =
Record.size();
I !=
E;
I += 2) {
2527 auto K = MDKindMap.find(Record[
I]);
2528 if (K == MDKindMap.end())
2529 return error(
"Invalid ID");
2533 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
2546 PlaceholderQueue Placeholders;
2550 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2553 switch (Entry.Kind) {
2556 return error(
"Malformed block");
2559 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2568 ++NumMDRecordLoaded;
2572 switch (MaybeRecord.
get()) {
2576 unsigned RecordLength =
Record.size();
2578 return error(
"Invalid record");
2579 if (RecordLength % 2 == 0) {
2581 if (
Error Err = parseGlobalObjectAttachment(
F,
Record))
2588 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
2589 unsigned Kind =
Record[i];
2590 auto I = MDKindMap.find(Kind);
2591 if (
I == MDKindMap.end())
2592 return error(
"Invalid ID");
2593 if (
I->second == LLVMContext::MD_tbaa && StripTBAA)
2596 auto Idx =
Record[i + 1];
2597 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2598 !MetadataList.lookup(Idx)) {
2601 lazyLoadOneMetadata(Idx, Placeholders);
2603 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2613 return error(
"Invalid metadata attachment");
2615 if (HasSeenOldLoopTags &&
I->second == LLVMContext::MD_loop)
2618 if (
I->second == LLVMContext::MD_tbaa) {
2631Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2634 return error(
"Invalid record");
2636 unsigned Kind =
Record[0];
2639 unsigned NewKind = TheModule.getMDKindID(Name.str());
2640 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2641 return error(
"Conflicting METADATA_KIND records");
2655 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2658 switch (Entry.Kind) {
2661 return error(
"Malformed block");
2671 ++NumMDRecordLoaded;
2675 switch (MaybeCode.
get()) {
2688 Pimpl = std::move(RHS.Pimpl);
2692 : Pimpl(
std::
move(RHS.Pimpl)) {}
2700 Stream, TheModule, ValueList,
std::
move(Callbacks), IsImporting)) {}
2702Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2703 return Pimpl->parseMetadata(ModuleLevel);
2711 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2715 return Pimpl->lookupSubprogramForFunction(
F);
2720 return Pimpl->parseMetadataAttachment(
F, InstructionList);
2724 return Pimpl->parseMetadataKinds();
2728 return Pimpl->setStripTBAA(StripTBAA);
2737 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.
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.
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...