63#define DEBUG_TYPE "bitcode-reader"
65STATISTIC(NumMDStringLoaded,
"Number of MDStrings loaded");
66STATISTIC(NumMDNodeTemporary,
"Number of MDNode::Temporary created");
67STATISTIC(NumMDRecordLoaded,
"Number of Metadata records loaded");
71class BitcodeReaderMetadataList {
98 unsigned RefsUpperBound;
101 BitcodeReaderMetadataList(LLVMContext &
C,
size_t RefsUpperBound)
103 RefsUpperBound(std::
min((size_t)std::numeric_limits<unsigned>::
max(),
106 using const_iterator = SmallVector<TrackingMDRef, 1>::const_iterator;
109 unsigned size()
const {
return MetadataPtrs.size(); }
110 void resize(
unsigned N) { MetadataPtrs.resize(
N); }
111 void push_back(
Metadata *MD) { MetadataPtrs.emplace_back(MD); }
112 void clear() { MetadataPtrs.clear(); }
114 void pop_back() { MetadataPtrs.pop_back(); }
115 bool empty()
const {
return MetadataPtrs.empty(); }
116 const_iterator
begin()
const {
return MetadataPtrs.begin(); }
117 const_iterator
end()
const {
return MetadataPtrs.end(); }
119 Metadata *operator[](
unsigned i)
const {
return MetadataPtrs[i]; }
122 if (
I < MetadataPtrs.size())
123 return MetadataPtrs[
I];
127 void shrinkTo(
unsigned N) {
128 assert(
N <=
size() &&
"Invalid shrinkTo request!");
129 assert(ForwardReference.empty() &&
"Unexpected forward refs");
130 assert(UnresolvedNodes.empty() &&
"Unexpected unresolved node");
131 MetadataPtrs.resize(
N);
136 Metadata *getMetadataFwdRef(
unsigned Idx);
142 Metadata *getMetadataIfResolved(
unsigned Idx);
144 MDNode *getMDNodeFwdRefOrNull(
unsigned Idx);
145 void assignValue(
Metadata *MD,
unsigned Idx);
146 void tryToResolveCycles();
147 bool hasFwdRefs()
const {
return !ForwardReference.empty(); }
148 int getNextFwdRef() {
150 return *ForwardReference.begin();
154 void addTypeRef(MDString &
UUID, DICompositeType &CT);
169void BitcodeReaderMetadataList::assignValue(
Metadata *MD,
unsigned Idx) {
171 if (!MDN->isResolved())
172 UnresolvedNodes.
insert(Idx);
182 TrackingMDRef &OldMD = MetadataPtrs[
Idx];
190 PrevMD->replaceAllUsesWith(MD);
194Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(
unsigned Idx) {
196 if (Idx >= RefsUpperBound)
202 if (
Metadata *MD = MetadataPtrs[Idx])
209 ++NumMDNodeTemporary;
211 MetadataPtrs[
Idx].reset(MD);
215Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(
unsigned Idx) {
218 if (!
N->isResolved())
223MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(
unsigned Idx) {
227void BitcodeReaderMetadataList::tryToResolveCycles() {
233 for (
const auto &[
UUID, CT] : OldTypeRefs.FwdDecls)
234 OldTypeRefs.Final.try_emplace(
UUID, CT);
235 OldTypeRefs.FwdDecls.clear();
239 for (
const auto &Array : OldTypeRefs.Arrays)
240 Array.second->replaceAllUsesWith(resolveTypeArray(
Array.first.get()));
241 OldTypeRefs.Arrays.clear();
246 for (
const auto &
Ref : OldTypeRefs.Unknown) {
247 if (DICompositeType *CT = OldTypeRefs.Final.lookup(
Ref.first))
248 Ref.second->replaceAllUsesWith(CT);
250 Ref.second->replaceAllUsesWith(
Ref.first);
252 OldTypeRefs.Unknown.clear();
254 if (UnresolvedNodes.
empty())
259 for (
unsigned I : UnresolvedNodes) {
260 auto &MD = MetadataPtrs[
I];
265 assert(!
N->isTemporary() &&
"Unexpected forward reference");
270 UnresolvedNodes.clear();
273void BitcodeReaderMetadataList::addTypeRef(MDString &
UUID,
274 DICompositeType &CT) {
277 OldTypeRefs.FwdDecls.insert(std::make_pair(&
UUID, &CT));
279 OldTypeRefs.Final.insert(std::make_pair(&
UUID, &CT));
287 if (
auto *CT = OldTypeRefs.Final.lookup(
UUID))
290 auto &
Ref = OldTypeRefs.Unknown[
UUID];
296Metadata *BitcodeReaderMetadataList::upgradeTypeArray(
Metadata *MaybeTuple) {
298 if (!Tuple ||
Tuple->isDistinct())
302 if (!
Tuple->isTemporary())
303 return resolveTypeArray(Tuple);
307 OldTypeRefs.Arrays.emplace_back(
308 std::piecewise_construct, std::forward_as_tuple(Tuple),
310 return OldTypeRefs.Arrays.back().second.get();
313Metadata *BitcodeReaderMetadataList::resolveTypeArray(
Metadata *MaybeTuple) {
315 if (!Tuple ||
Tuple->isDistinct())
320 Ops.reserve(
Tuple->getNumOperands());
322 Ops.push_back(upgradeTypeRef(MD));
340 New->replaceOperandWith(0, New);
346 unsigned NumOperands =
Domain->getNumOperands();
347 bool HadDescription = NumOperands == 2;
349 if (NumOperands == 0 || NumOperands > 2 ||
376 if (UpgradedDomain ==
Domain)
380 Ops[1] = UpgradedDomain;
382 Upgraded[Scope] = Upgrade;
388class PlaceholderQueue {
391 std::deque<DistinctMDOperandPlaceholder> PHs;
394 ~PlaceholderQueue() {
396 "PlaceholderQueue hasn't been flushed before being destroyed");
398 bool empty()
const {
return PHs.empty(); }
399 DistinctMDOperandPlaceholder &getPlaceholderOp(
unsigned ID);
400 void flush(BitcodeReaderMetadataList &MetadataList);
404 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
405 DenseSet<unsigned> &Temporaries) {
406 for (
auto &PH : PHs) {
407 auto ID = PH.getID();
408 auto *MD = MetadataList.lookup(ID);
414 if (
N &&
N->isTemporary())
422DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(
unsigned ID) {
423 PHs.emplace_back(ID);
427void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
428 while (!PHs.empty()) {
429 auto *MD = MetadataList.lookup(PHs.front().getID());
430 assert(MD &&
"Flushing placeholder on unassigned MD");
433 assert(MDN->isResolved() &&
434 "Flushing Placeholder while cycles aren't resolved");
436 PHs.front().replaceUseWith(MD);
447 const BitReaderOptions &Opts;
448 BitcodeReaderMetadataList MetadataList;
461 std::vector<StringRef> MDStringRef;
465 MDString *lazyLoadOneMDString(
unsigned Idx);
468 std::vector<uint64_t> GlobalMetadataBitPosIndex;
473 uint64_t GlobalDeclAttachmentPos = 0;
478 unsigned NumGlobalDeclAttachSkipped = 0;
479 unsigned NumGlobalDeclAttachParsed = 0;
492 void lazyLoadOneMetadata(
unsigned Idx, PlaceholderQueue &Placeholders);
496 std::vector<std::pair<DICompileUnit *, unsigned>> CUSubprograms;
510 bool StripTBAA =
false;
511 bool HasSeenOldLoopTags =
false;
516 bool NeedUpgradeToDIGlobalVariableExpression =
false;
517 bool NeedDeclareExpressionUpgrade =
false;
521 GlobalVariableExpression;
527 bool IsImporting =
false;
530 PlaceholderQueue &Placeholders,
StringRef Blob,
531 unsigned &NextMetadataNo);
538 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
541 void upgradeCUSubprograms() {
542 for (
auto CU_SP : CUSubprograms)
545 for (
auto &
Op : SPs->operands())
547 SP->replaceUnit(CU_SP.first);
548 CUSubprograms.clear();
552 void upgradeCUVariables() {
553 if (!NeedUpgradeToDIGlobalVariableExpression)
557 if (
NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu"))
558 for (
unsigned I = 0, E = CUNodes->getNumOperands();
I != E; ++
I) {
561 for (
unsigned I = 0;
I < GVs->getNumOperands();
I++)
574 for (
auto &GV : TheModule.globals()) {
576 GV.getMetadata(LLVMContext::MD_dbg, MDs);
577 GV.eraseMetadata(LLVMContext::MD_dbg);
585 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
587 GV.addMetadata(LLVMContext::MD_dbg, *MD);
594 if (
auto *SP = ParentSubprogram[S]) {
602 if (!Visited.
insert(S).second)
606 return ParentSubprogram[InitialScope] =
612 using SPToEntitiesMap =
618 template <
typename NodeT>
619 void upgradeOneCULocalsList(SPToEntitiesMap &SPToEntities,
DICompileUnit *
CU,
620 unsigned ListIndex) {
626 return !isa_and_nonnull<DILocalScope>(getScope(cast<NodeT>(MD)));
636 else if (
auto *SP = findEnclosingSubprogram(LS))
637 SPToEntities[SP].push_back(MD);
645 void upgradeCULocals() {
646 NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu");
650 SPToEntitiesMap SPToEntities;
657 upgradeOneCULocalsList<DIGlobalVariableExpression>(SPToEntities,
CU, 6);
659 upgradeOneCULocalsList<DIImportedEntity>(SPToEntities,
CU, 7);
661 upgradeOneCULocalsList<DICompositeType>(SPToEntities,
CU, 4);
665 for (
auto &[SP, Nodes] : SPToEntities)
666 SP->retainNodes(Nodes.begin(), Nodes.end());
667 SPToEntities.clear();
670 ParentSubprogram.clear();
675 void upgradeDeclareExpressions(
Function &
F) {
676 if (!NeedDeclareExpressionUpgrade)
679 auto UpdateDeclareIfNeeded = [&](
auto *Declare) {
680 auto *DIExpr = Declare->getExpression();
681 if (!DIExpr || !DIExpr->startsWithDeref() ||
685 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
692 if (DVR.isDbgDeclare())
693 UpdateDeclareIfNeeded(&DVR);
696 UpdateDeclareIfNeeded(DDI);
701 Error upgradeDIExpression(uint64_t FromVersion,
704 auto N = Expr.
size();
705 switch (FromVersion) {
707 return error(
"Invalid record");
709 if (
N >= 3 && Expr[
N - 3] == dwarf::DW_OP_bit_piece)
714 if (
N && Expr[0] == dwarf::DW_OP_deref) {
716 if (Expr.
size() >= 3 &&
720 *std::prev(
End) = dwarf::DW_OP_deref;
722 NeedDeclareExpressionUpgrade =
true;
728 while (!SubExpr.empty()) {
733 switch (SubExpr.front()) {
737 case dwarf::DW_OP_constu:
738 case dwarf::DW_OP_minus:
739 case dwarf::DW_OP_plus:
749 HistoricSize = std::min(SubExpr.size(), HistoricSize);
752 switch (SubExpr.front()) {
753 case dwarf::DW_OP_plus:
754 Buffer.
push_back(dwarf::DW_OP_plus_uconst);
755 Buffer.
append(Args.begin(), Args.end());
757 case dwarf::DW_OP_minus:
759 Buffer.
append(Args.begin(), Args.end());
764 Buffer.
append(Args.begin(), Args.end());
769 SubExpr = SubExpr.slice(HistoricSize);
787 enum class DebugInfoUpgradeMode {
796 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
797 if (Mode == DebugInfoUpgradeMode::None)
799 upgradeCUSubprograms();
800 upgradeCUVariables();
801 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
806 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
807 DebugInfoUpgradeMode DIUpgradeMode) {
808 resolveForwardRefsAndPlaceholders(Placeholders);
809 upgradeDebugInfo(DIUpgradeMode);
812 << NewDistinctSPs.size() <<
" subprogram(s).\n");
813 NewDistinctSPs.clear();
816 void callMDTypeCallback(
Metadata **Val,
unsigned TypeID);
823 MetadataList(TheModule.
getContext(), Stream.SizeInBytes()),
824 ValueList(ValueList), Stream(Stream), Context(TheModule.
getContext()),
825 TheModule(TheModule), Callbacks(
std::
move(Callbacks)),
826 IsImporting(IsImporting) {}
830 bool hasFwdRefs()
const {
return MetadataList.hasFwdRefs(); }
833 if (ID < MDStringRef.size())
834 return lazyLoadOneMDString(ID);
835 if (
auto *MD = MetadataList.lookup(ID))
839 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
840 PlaceholderQueue Placeholders;
841 lazyLoadOneMetadata(ID, Placeholders);
843 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
844 return MetadataList.lookup(ID);
846 return MetadataList.getMetadataFwdRef(ID);
850 return FunctionsWithSPs.lookup(
F);
858 if (
MDNode *Upgrade = UpgradedAliasScopes.lookup(ScopeList))
868 Ops.push_back(Scope);
874 UpgradedAliasScopes[ScopeList] = Upgrade;
886 unsigned size()
const {
return MetadataList.size(); }
892MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
893 IndexCursor = Stream;
895 GlobalDeclAttachmentPos = 0;
898 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
906 switch (Entry.Kind) {
909 return error(
"Malformed block");
916 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
918 if (
Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
923 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
924 return std::move(Err);
928 IndexCursor.readRecord(Entry.ID,
Record, &Blob))
931 return MaybeRecord.takeError();
932 unsigned NumStrings =
Record[0];
933 MDStringRef.reserve(NumStrings);
934 auto IndexNextMDString = [&](
StringRef Str) {
935 MDStringRef.push_back(Str);
937 if (
auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
938 return std::move(Err);
944 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
945 return std::move(Err);
947 if (Expected<unsigned> MaybeRecord =
948 IndexCursor.readRecord(
Entry.ID, Record))
951 return MaybeRecord.takeError();
953 return error(
"Invalid record");
955 auto BeginPos = IndexCursor.GetCurrentBitNo();
956 if (
Error Err = IndexCursor.JumpToBit(BeginPos +
Offset))
957 return std::move(Err);
958 Expected<BitstreamEntry> MaybeEntry =
959 IndexCursor.advanceSkippingSubblocks(
965 "Corrupted bitcode: Expected `Record` when trying to find the "
968 if (Expected<unsigned> MaybeCode =
969 IndexCursor.readRecord(
Entry.ID, Record))
971 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
972 "find the Metadata index");
974 return MaybeCode.takeError();
976 auto CurrentValue = BeginPos;
977 GlobalMetadataBitPosIndex.reserve(
Record.size());
978 for (
auto &Elt : Record) {
980 GlobalMetadataBitPosIndex.push_back(CurrentValue);
987 return error(
"Corrupted Metadata block");
990 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
991 return std::move(Err);
995 if (Expected<unsigned> MaybeCode =
996 IndexCursor.readRecord(
Entry.ID, Record)) {
997 Code = MaybeCode.get();
1000 return MaybeCode.takeError();
1004 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
1005 Code = MaybeCode.get();
1007 return MaybeCode.takeError();
1012 if (Expected<unsigned> MaybeNextBitCode =
1013 IndexCursor.readRecord(Code, Record))
1016 return MaybeNextBitCode.takeError();
1020 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1021 for (
unsigned i = 0; i !=
Size; ++i) {
1026 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1027 assert(MD &&
"Invalid metadata: expect fwd ref to MDNode");
1033 if (!GlobalDeclAttachmentPos)
1034 GlobalDeclAttachmentPos = SavedPos;
1036 NumGlobalDeclAttachSkipped++;
1080 MDStringRef.clear();
1081 GlobalMetadataBitPosIndex.clear();
1095Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1097 if (!GlobalDeclAttachmentPos)
1101 BitstreamCursor TempCursor = Stream;
1102 SmallVector<uint64_t, 64>
Record;
1106 return std::move(Err);
1108 BitstreamEntry
Entry;
1113 return std::move(
E);
1115 switch (
Entry.Kind) {
1118 return error(
"Malformed block");
1121 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1133 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1137 NumGlobalDeclAttachParsed++;
1142 return std::move(Err);
1144 if (Expected<unsigned> MaybeRecord =
1148 return MaybeRecord.takeError();
1149 if (
Record.size() % 2 == 0)
1150 return error(
"Invalid record");
1151 unsigned ValueID =
Record[0];
1152 if (ValueID >= ValueList.size())
1153 return error(
"Invalid record");
1159 if (
Error Err = parseGlobalObjectAttachment(
1160 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1161 return std::move(Err);
1163 return std::move(Err);
1168void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(
Metadata **Val,
1170 if (Callbacks.MDType) {
1171 (*Callbacks.MDType)(Val,
TypeID, Callbacks.GetTypeByID,
1172 Callbacks.GetContainedTypeID);
1180 if (!ModuleLevel && MetadataList.hasFwdRefs())
1181 return error(
"Invalid metadata: fwd refs into function blocks");
1185 auto EntryPos = Stream.GetCurrentBitNo();
1191 PlaceholderQueue Placeholders;
1192 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1193 : DebugInfoUpgradeMode::Partial;
1197 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1198 Opts.ondemand_mds_loading) {
1199 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1201 return SuccessOrErr.takeError();
1202 if (SuccessOrErr.get()) {
1205 MetadataList.resize(MDStringRef.size() +
1206 GlobalMetadataBitPosIndex.size());
1211 SuccessOrErr = loadGlobalDeclAttachments();
1213 return SuccessOrErr.takeError();
1214 assert(SuccessOrErr.get());
1219 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1222 Stream.ReadBlockEnd();
1223 if (
Error Err = IndexCursor.JumpToBit(EntryPos))
1225 if (
Error Err = Stream.SkipBlock()) {
1236 unsigned NextMetadataNo = MetadataList.size();
1241 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1244 switch (Entry.Kind) {
1247 return error(
"Malformed block");
1250 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1260 ++NumMDRecordLoaded;
1262 Stream.readRecord(Entry.ID,
Record, &Blob)) {
1263 if (
Error Err = parseOneMetadata(
Record, MaybeCode.
get(), Placeholders,
1264 Blob, NextMetadataNo))
1271MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
1272 ++NumMDStringLoaded;
1273 if (
Metadata *MD = MetadataList.lookup(ID))
1276 MetadataList.assignValue(MDS, ID);
1280void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1281 unsigned ID, PlaceholderQueue &Placeholders) {
1282 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1283 assert(ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
1285 if (
auto *MD = MetadataList.lookup(ID)) {
1289 if (!
N || !
N->isTemporary())
1294 if (
Error Err = IndexCursor.JumpToBit(
1295 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1299 if (
Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1303 ++NumMDRecordLoaded;
1305 IndexCursor.readRecord(Entry.ID,
Record, &Blob)) {
1307 parseOneMetadata(
Record, MaybeCode.
get(), Placeholders, Blob, ID))
1317void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1318 PlaceholderQueue &Placeholders) {
1319 DenseSet<unsigned> Temporaries;
1322 Placeholders.getTemporaries(MetadataList, Temporaries);
1325 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
1330 for (
auto ID : Temporaries)
1331 lazyLoadOneMetadata(ID, Placeholders);
1332 Temporaries.clear();
1336 while (MetadataList.hasFwdRefs())
1337 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1342 MetadataList.tryToResolveCycles();
1346 Placeholders.flush(MetadataList);
1350 Type *Ty,
unsigned TyID) {
1362 if (Idx < ValueList.
size() && ValueList[Idx] &&
1363 ValueList[Idx]->getType() == Ty)
1369Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1370 SmallVectorImpl<uint64_t> &Record,
unsigned Code,
1371 PlaceholderQueue &Placeholders, StringRef Blob,
unsigned &NextMetadataNo) {
1373 bool IsDistinct =
false;
1374 auto getMD = [&](
unsigned ID) ->
Metadata * {
1375 if (ID < MDStringRef.size())
1376 return lazyLoadOneMDString(ID);
1378 if (
auto *MD = MetadataList.lookup(ID))
1382 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1386 MetadataList.getMetadataFwdRef(NextMetadataNo);
1387 lazyLoadOneMetadata(ID, Placeholders);
1388 return MetadataList.lookup(ID);
1391 return MetadataList.getMetadataFwdRef(ID);
1393 if (
auto *MD = MetadataList.getMetadataIfResolved(ID))
1395 return &Placeholders.getPlaceholderOp(ID);
1397 auto getMDOrNull = [&](
unsigned ID) ->
Metadata * {
1399 return getMD(ID - 1);
1402 auto getMDString = [&](
unsigned ID) -> MDString * {
1405 auto MDS = getMDOrNull(ID);
1410 auto getDITypeRefOrNull = [&](
unsigned ID) {
1411 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1414 auto getMetadataOrConstant = [&](
bool IsMetadata,
1417 return getMDOrNull(Entry);
1419 ConstantInt::get(Type::getInt64Ty(
Context), Entry));
1422#define GET_OR_DISTINCT(CLASS, ARGS) \
1423 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1432 if (
Error E = Stream.ReadCode().moveInto(Code))
1435 ++NumMDRecordLoaded;
1436 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1438 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1440 return MaybeNextBitCode.takeError();
1444 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1445 for (
unsigned i = 0; i !=
Size; ++i) {
1446 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1448 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1457 if (
Record.size() % 2 == 1)
1458 return error(
"Invalid record");
1462 auto dropRecord = [&] {
1466 if (
Record.size() != 2) {
1471 unsigned TyID =
Record[0];
1472 Type *Ty = Callbacks.GetTypeByID(TyID);
1478 Value *
V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1481 return error(
"Invalid value reference from old fn metadata");
1489 if (
Record.size() % 2 == 1)
1490 return error(
"Invalid record");
1494 for (
unsigned i = 0; i !=
Size; i += 2) {
1495 unsigned TyID =
Record[i];
1496 Type *Ty = Callbacks.GetTypeByID(TyID);
1498 return error(
"Invalid record");
1504 return error(
"Invalid value reference from old metadata");
1507 "Expected non-function-local metadata");
1508 callMDTypeCallback(&MD, TyID);
1519 return error(
"Invalid record");
1521 unsigned TyID =
Record[0];
1522 Type *Ty = Callbacks.GetTypeByID(TyID);
1524 return error(
"Invalid record");
1528 return error(
"Invalid value reference from metadata");
1531 callMDTypeCallback(&MD, TyID);
1532 MetadataList.assignValue(MD, NextMetadataNo);
1542 for (
unsigned ID : Record)
1553 return error(
"Invalid record");
1557 unsigned Column =
Record[2];
1559 Metadata *InlinedAt = getMDOrNull(Record[4]);
1563 Metadata *IRLayers =
Record.size() >= 9 ? getMDOrNull(Record[8]) : nullptr;
1564 MetadataList.assignValue(
1566 (
Context, Line, Column, Scope, InlinedAt, ImplicitCode,
1567 AtomGroup, AtomRank, IRLayers)),
1574 return error(
"Invalid record");
1578 unsigned Column =
Record[2];
1583 MetadataList.assignValue(
1591 return error(
"Invalid record");
1595 for (
unsigned I = 1,
E =
Record.size();
I !=
E; ++
I)
1604 return error(
"Invalid record");
1611 return error(
"Invalid record");
1613 auto *Header = getMDString(Record[3]);
1615 for (
unsigned I = 4,
E =
Record.size();
I !=
E; ++
I)
1617 MetadataList.assignValue(
1633 switch (Record[0] >> 1) {
1644 DISubrange, (
Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1645 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1648 return error(
"Invalid record: Unsupported version of DISubrange");
1651 MetadataList.assignValue(Val, NextMetadataNo);
1652 IsDistinct =
Record[0] & 1;
1659 (
Context, getMDOrNull(Record[1]),
1660 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1661 getMDOrNull(Record[4])));
1663 MetadataList.assignValue(Val, NextMetadataNo);
1664 IsDistinct =
Record[0] & 1;
1670 return error(
"Invalid record");
1672 IsDistinct =
Record[0] & 1;
1673 bool IsUnsigned =
Record[0] & 2;
1674 bool IsBigInt =
Record[0] & 4;
1679 const size_t NumWords =
Record.size() - 3;
1684 MetadataList.assignValue(
1693 return error(
"Invalid record");
1695 IsDistinct =
Record[0] & 1;
1696 bool SizeIsMetadata =
Record[0] & 2;
1700 uint32_t NumExtraInhabitants = (
Record.size() > 7) ?
Record[7] : 0;
1701 uint32_t DataSizeInBits = (
Record.size() > 8) ?
Record[8] : 0;
1702 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1704 unsigned LineNo = 0;
1707 File = getMDOrNull(Record[9]);
1709 Scope = getMDOrNull(Record[11]);
1711 MetadataList.assignValue(
1713 (
Context, Record[1], getMDString(Record[2]), File,
1714 LineNo, Scope, SizeInBits, Record[4], Record[5],
1715 NumExtraInhabitants, DataSizeInBits, Flags)),
1722 return error(
"Invalid record");
1724 IsDistinct =
Record[0] & 1;
1725 bool SizeIsMetadata =
Record[0] & 2;
1728 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1732 auto ReadWideInt = [&]() {
1734 unsigned NumWords =
Encoded >> 32;
1741 APInt Numerator = ReadWideInt();
1742 APInt Denominator = ReadWideInt();
1745 unsigned LineNo = 0;
1753 return error(
"Invalid record");
1755 MetadataList.assignValue(
1757 (
Context, Record[1], getMDString(Record[2]), File,
1758 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1759 Record[7], Record[8], Numerator, Denominator)),
1766 return error(
"Invalid record");
1768 IsDistinct =
Record[0] & 1;
1769 bool SizeIsMetadata =
Record[0] & 2;
1774 Metadata *StringLocationExp =
nullptr;
1777 bool StringLocPresent =
Record.size() > 8;
1778 size_t SizeOffset = StringLocPresent ? 6 : 5;
1781 getMetadataOrConstant(SizeIsMetadata, Record[SizeOffset]);
1782 if (StringLocPresent) {
1783 StringLocationExp = getMDOrNull(Record[5]);
1785 if (
Record.size() == 10) {
1786 CharType = getMDOrNull(Record[9]);
1789 MetadataList.assignValue(
1791 (
Context, Record[1], getMDString(Record[2]),
1792 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1793 StringLocationExp, SizeInBits, Record[SizeOffset + 1],
1794 Record[SizeOffset + 2], CharType)),
1801 return error(
"Invalid record");
1805 std::optional<unsigned> DWARFAddressSpace;
1806 if (
Record.size() > 12 && Record[12])
1807 DWARFAddressSpace =
Record[12] - 1;
1810 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1815 if (
Record.size() > 14) {
1817 Annotations = getMDOrNull(Record[13]);
1819 PtrAuthData.emplace(Record[14]);
1822 IsDistinct =
Record[0] & 1;
1823 bool SizeIsMetadata =
Record[0] & 2;
1826 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1827 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1829 MetadataList.assignValue(
1831 (
Context, Record[1], getMDString(Record[2]),
1832 getMDOrNull(Record[3]), Record[4],
1833 getDITypeRefOrNull(Record[5]),
1834 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1835 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1836 getDITypeRefOrNull(Record[11]), Annotations)),
1843 return error(
"Invalid record");
1845 IsDistinct =
Record[0] & 1;
1846 bool SizeIsMetadata =
Record[0] & 2;
1849 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1851 MetadataList.assignValue(
1853 (
Context, getMDString(Record[1]),
1854 getMDOrNull(Record[2]), Record[3],
1855 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1856 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1857 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1858 getMDOrNull(Record[12]))),
1865 return error(
"Invalid record");
1869 IsDistinct =
Record[0] & 0x1;
1870 bool IsNotUsedInTypeRef =
Record[0] & 2;
1871 bool SizeIsMetadata =
Record[0] & 4;
1873 MDString *
Name = getMDString(Record[2]);
1878 if (Record[8] > (
uint64_t)std::numeric_limits<uint32_t>::max())
1879 return error(
"Alignment value is too large");
1880 uint32_t AlignInBits =
Record[8];
1882 uint32_t NumExtraInhabitants = (
Record.size() > 22) ?
Record[22] : 0;
1885 unsigned RuntimeLang =
Record[12];
1886 std::optional<uint32_t> EnumKind;
1889 Metadata *TemplateParams =
nullptr;
1913 if (IsImporting && !Opts.import_full_type_definitions && Identifier &&
1915 (
Tag == dwarf::DW_TAG_enumeration_type ||
1916 Tag == dwarf::DW_TAG_class_type ||
1917 Tag == dwarf::DW_TAG_structure_type ||
1918 Tag == dwarf::DW_TAG_union_type)) {
1924 StringRef NameStr =
Name->getString();
1926 TemplateParams = getMDOrNull(Record[14]);
1928 BaseType = getDITypeRefOrNull(Record[6]);
1930 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1932 Elements = getMDOrNull(Record[11]);
1933 VTableHolder = getDITypeRefOrNull(Record[13]);
1934 TemplateParams = getMDOrNull(Record[14]);
1938 DataLocation = getMDOrNull(Record[17]);
1939 if (
Record.size() > 19) {
1940 Associated = getMDOrNull(Record[18]);
1941 Allocated = getMDOrNull(Record[19]);
1943 if (
Record.size() > 20) {
1944 Rank = getMDOrNull(Record[20]);
1946 if (
Record.size() > 21) {
1947 Annotations = getMDOrNull(Record[21]);
1949 if (
Record.size() > 23) {
1950 Specification = getMDOrNull(Record[23]);
1953 BitStride = getMDOrNull(Record[25]);
1959 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1961 DICompositeType *CT =
nullptr;
1965 SizeInBits, AlignInBits, OffsetInBits, Specification,
1966 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1967 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1968 Allocated, Rank, Annotations, BitStride);
1975 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1976 VTableHolder, TemplateParams, Identifier, Discriminator,
1977 DataLocation, Associated, Allocated, Rank, Annotations,
1978 Specification, NumExtraInhabitants, BitStride));
1979 if (!IsNotUsedInTypeRef && Identifier)
1982 MetadataList.assignValue(CT, NextMetadataNo);
1988 return error(
"Invalid record");
1989 bool IsOldTypeArray =
Record[0] < 2;
1992 IsDistinct =
Record[0] & 0x1;
1996 Types = MetadataList.upgradeTypeArray(Types);
1998 MetadataList.assignValue(
2007 return error(
"Invalid record");
2011 MetadataList.assignValue(
2014 (
Context,
Record.size() >= 8 ? getMDOrNull(Record[1]) :
nullptr,
2015 getMDOrNull(Record[0 +
Offset]), getMDString(Record[1 +
Offset]),
2016 getMDString(Record[2 +
Offset]), getMDString(Record[3 +
Offset]),
2017 getMDString(Record[4 +
Offset]),
2018 Record.size() <= 7 ? 0 : Record[7],
2019 Record.size() <= 8 ?
false : Record[8])),
2027 return error(
"Invalid record");
2030 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
2036 if (
Record.size() > 4 && Record[3] && Record[4])
2038 getMDString(Record[4]));
2039 MetadataList.assignValue(
2041 (
Context, getMDString(Record[1]),
2042 getMDString(Record[2]), Checksum,
2043 Record.size() > 5 ? getMDString(Record[5]) :
nullptr)),
2050 return error(
"Invalid record");
2056 const auto LangVersionMask = (
uint64_t(1) << 63);
2057 const bool HasVersionedLanguage =
Record[1] & LangVersionMask;
2064 if (
Record.size() > 23 &&
2066 return error(
"Invalid DICompileUnit dialect value");
2067 const uint16_t Dialect =
2068 Record.size() > 23 ?
static_cast<uint16_t
>(
Record[23]) : uint16_t(0);
2070 auto *CU = DICompileUnit::getDistinct(
2072 HasVersionedLanguage
2073 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
2074 LanguageVersion, Dialect)
2075 : DISourceLanguageName(Record[1], Dialect),
2076 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
2077 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
2078 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2079 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2080 Record.size() <= 15 ?
nullptr : getMDOrNull(Record[15]),
2081 Record.size() <= 14 ? 0 : Record[14],
2082 Record.size() <= 16 ?
true : Record[16],
2083 Record.size() <= 17 ?
false : Record[17],
2084 Record.size() <= 18 ? 0 : Record[18],
2085 Record.size() <= 19 ?
false : Record[19],
2090 Record.size() <= 20 ?
nullptr : getMDString(Record[20]),
2091 Record.size() <= 21 ?
nullptr : getMDString(Record[21]));
2093 MetadataList.assignValue(CU, NextMetadataNo);
2098 CUSubprograms.push_back({CU,
Record[11]});
2103 return error(
"Invalid record");
2105 bool HasSPFlags =
Record[0] & 4;
2118 const unsigned DIFlagMainSubprogram = 1 << 21;
2119 bool HasOldMainSubprogramFlag =
Flags & DIFlagMainSubprogram;
2120 if (HasOldMainSubprogramFlag)
2124 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
2126 if (HasOldMainSubprogramFlag && HasSPFlags)
2127 SPFlags |= DISubprogram::SPFlagMainSubprogram;
2128 else if (!HasSPFlags)
2130 Record[7], Record[8],
2131 Record[14], Record[11],
2132 HasOldMainSubprogramFlag);
2135 IsDistinct = (
Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2141 bool HasUnit =
Record[0] & 2;
2142 if (!HasSPFlags && HasUnit &&
Record.size() < 19)
2143 return error(
"Invalid record");
2144 if (HasSPFlags && !HasUnit)
2145 return error(
"Invalid record");
2148 bool HasThisAdj =
true;
2149 bool HasThrownTypes =
true;
2150 bool HasAnnotations =
false;
2151 bool HasTargetFuncName =
false;
2152 unsigned OffsetA = 0;
2153 unsigned OffsetB = 0;
2156 bool UsesKeyInstructions =
false;
2160 if (
Record.size() >= 19) {
2164 HasThisAdj =
Record.size() >= 20;
2165 HasThrownTypes =
Record.size() >= 21;
2167 HasAnnotations =
Record.size() >= 19;
2168 HasTargetFuncName =
Record.size() >= 20;
2169 UsesKeyInstructions =
Record.size() >= 21 ?
Record[20] : 0;
2172 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2176 getDITypeRefOrNull(Record[1]),
2177 getMDString(Record[2]),
2178 getMDString(Record[3]),
2179 getMDOrNull(Record[4]),
2181 getMDOrNull(Record[6]),
2182 Record[7 + OffsetA],
2183 getDITypeRefOrNull(Record[8 + OffsetA]),
2184 Record[10 + OffsetA],
2185 HasThisAdj ? Record[16 + OffsetB] : 0,
2188 HasUnit ? CUorFn :
nullptr,
2189 getMDOrNull(Record[13 + OffsetB]),
2190 getMDOrNull(Record[14 + OffsetB]),
2191 getMDOrNull(Record[15 + OffsetB]),
2192 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2194 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2196 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2198 UsesKeyInstructions));
2199 MetadataList.assignValue(SP, NextMetadataNo);
2203 NewDistinctSPs.push_back(SP);
2209 if (
F->isMaterializable())
2212 FunctionsWithSPs[
F] =
SP;
2213 else if (!
F->empty())
2214 F->setSubprogram(SP);
2221 return error(
"Invalid record");
2224 MetadataList.assignValue(
2226 (
Context, getMDOrNull(Record[1]),
2227 getMDOrNull(Record[2]), Record[3], Record[4])),
2234 return error(
"Invalid record");
2237 MetadataList.assignValue(
2239 (
Context, getMDOrNull(Record[1]),
2240 getMDOrNull(Record[2]), Record[3])),
2246 IsDistinct =
Record[0] & 1;
2247 MetadataList.assignValue(
2249 (
Context, getMDOrNull(Record[1]),
2250 getMDOrNull(Record[2]), getMDString(Record[3]),
2251 getMDOrNull(Record[4]), Record[5])),
2260 Name = getMDString(Record[2]);
2261 else if (
Record.size() == 5)
2262 Name = getMDString(Record[3]);
2264 return error(
"Invalid record");
2266 IsDistinct =
Record[0] & 1;
2267 bool ExportSymbols =
Record[0] & 2;
2268 MetadataList.assignValue(
2270 (
Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2277 return error(
"Invalid record");
2280 MetadataList.assignValue(
2282 (
Context, Record[1], Record[2], getMDString(Record[3]),
2283 getMDString(Record[4]))),
2290 return error(
"Invalid record");
2293 MetadataList.assignValue(
2295 (
Context, Record[1], Record[2], getMDOrNull(Record[3]),
2296 getMDOrNull(Record[4]))),
2303 return error(
"Invalid record");
2306 MetadataList.assignValue(
2308 (
Context, getMDString(Record[1]),
2309 getDITypeRefOrNull(Record[2]),
2310 (
Record.size() == 4) ? getMDOrNull(Record[3])
2311 : getMDOrNull(
false))),
2318 return error(
"Invalid record");
2322 MetadataList.assignValue(
2324 DITemplateValueParameter,
2325 (
Context, Record[1], getMDString(Record[2]),
2326 getDITypeRefOrNull(Record[3]),
2327 (
Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(
false),
2328 (
Record.size() == 6) ? getMDOrNull(Record[5])
2329 : getMDOrNull(Record[4]))),
2336 return error(
"Invalid record");
2338 IsDistinct =
Record[0] & 1;
2344 Annotations = getMDOrNull(Record[12]);
2346 MetadataList.assignValue(
2348 (
Context, getMDOrNull(Record[1]),
2349 getMDString(Record[2]), getMDString(Record[3]),
2350 getMDOrNull(Record[4]), Record[5],
2351 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2352 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2353 Record[11], Annotations)),
2360 MetadataList.assignValue(
2363 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2364 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2365 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2366 getMDOrNull(Record[10]),
nullptr, Record[11],
nullptr)),
2373 NeedUpgradeToDIGlobalVariableExpression =
true;
2374 Metadata *Expr = getMDOrNull(Record[9]);
2375 uint32_t AlignInBits = 0;
2376 if (
Record.size() > 11) {
2377 if (Record[11] > (
uint64_t)std::numeric_limits<uint32_t>::max())
2378 return error(
"Alignment value is too large");
2379 AlignInBits =
Record[11];
2381 GlobalVariable *Attach =
nullptr;
2387 Expr = DIExpression::get(
Context,
2388 {dwarf::DW_OP_constu, CI->getZExtValue(),
2389 dwarf::DW_OP_stack_value});
2396 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2397 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2398 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2399 getMDOrNull(Record[10]),
nullptr, AlignInBits,
nullptr));
2401 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[DGV];
2402 if (Attach || Expr) {
2404 DGVE = DIGlobalVariableExpression::getDistinct(
2412 MetadataList.assignValue(MDNode, NextMetadataNo);
2415 return error(
"Invalid record");
2421 return error(
"Invalid DIAssignID record.");
2423 IsDistinct =
Record[0] & 1;
2425 return error(
"Invalid DIAssignID record. Must be distinct");
2434 return error(
"Invalid record");
2436 IsDistinct =
Record[0] & 1;
2437 bool HasAlignment =
Record[0] & 2;
2441 bool HasTag = !HasAlignment &&
Record.size() > 8;
2443 uint32_t AlignInBits = 0;
2446 if (Record[8] > (
uint64_t)std::numeric_limits<uint32_t>::max())
2447 return error(
"Alignment value is too large");
2450 Annotations = getMDOrNull(Record[9]);
2453 MetadataList.assignValue(
2455 (
Context, getMDOrNull(Record[1 + HasTag]),
2456 getMDString(Record[2 + HasTag]),
2457 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2458 getDITypeRefOrNull(Record[5 + HasTag]),
2459 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2466 return error(
"Invalid record");
2468 IsDistinct =
Record[0] & 1;
2471 bool IsArtificial =
Record[0] & 2;
2472 std::optional<unsigned> CoroSuspendIdx;
2475 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2476 if (RawSuspendIdx > (
uint64_t)std::numeric_limits<unsigned>::max())
2477 return error(
"CoroSuspendIdx value is too large");
2478 CoroSuspendIdx = RawSuspendIdx;
2482 MetadataList.assignValue(
2484 (
Context, getMDOrNull(Record[1]),
2485 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2486 Column, IsArtificial, CoroSuspendIdx)),
2493 return error(
"Invalid record");
2495 IsDistinct =
Record[0] & 1;
2500 if (
Error Err = upgradeDIExpression(
Version, Elts, Buffer))
2510 return error(
"Invalid record");
2513 Metadata *Expr = getMDOrNull(Record[2]);
2515 Expr = DIExpression::get(
Context, {});
2516 MetadataList.assignValue(
2518 (
Context, getMDOrNull(Record[1]), Expr)),
2525 return error(
"Invalid record");
2528 MetadataList.assignValue(
2530 (
Context, getMDString(Record[1]),
2531 getMDOrNull(Record[2]), Record[3],
2532 getMDString(Record[5]),
2533 getMDString(Record[4]), Record[6],
2534 getDITypeRefOrNull(Record[7]))),
2541 return error(
"Invalid record");
2544 MetadataList.assignValue(
2546 getMDOrNull(Record[2]), Record[3],
2547 getDITypeRefOrNull(Record[4]),
2548 getMDOrNull(Record[5]))),
2555 return error(
"Invalid DIImportedEntity record");
2558 bool HasFile = (
Record.size() >= 7);
2559 bool HasElements = (
Record.size() >= 8);
2560 MetadataList.assignValue(
2562 (
Context, Record[1], getMDOrNull(Record[2]),
2563 getDITypeRefOrNull(Record[3]),
2564 HasFile ? getMDOrNull(Record[6]) :
nullptr,
2565 HasFile ? Record[4] : 0, getMDString(Record[5]),
2566 HasElements ? getMDOrNull(Record[7]) :
nullptr)),
2576 ++NumMDStringLoaded;
2578 MetadataList.assignValue(MD, NextMetadataNo);
2583 auto CreateNextMDString = [&](StringRef Str) {
2587 ++NumMDStringLoaded;
2591 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2596 if (
Record.size() % 2 == 0)
2597 return error(
"Invalid record");
2598 unsigned ValueID =
Record[0];
2599 if (ValueID >= ValueList.size())
2600 return error(
"Invalid record");
2602 if (
Error Err = parseGlobalObjectAttachment(
2603 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2610 if (
Error Err = parseMetadataKindRecord(Record))
2621 "Invalid record: DIArgList should not contain forward refs");
2623 return error(
"Invalid record");
2633#undef GET_OR_DISTINCT
2636Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2637 ArrayRef<uint64_t> Record, StringRef Blob,
2638 function_ref<
void(StringRef)> CallBack) {
2643 return error(
"Invalid record: metadata strings layout");
2645 unsigned NumStrings =
Record[0];
2646 unsigned StringsOffset =
Record[1];
2648 return error(
"Invalid record: metadata strings with no strings");
2649 if (StringsOffset > Blob.
size())
2650 return error(
"Invalid record: metadata strings corrupt offset");
2652 StringRef Lengths = Blob.
slice(0, StringsOffset);
2653 SimpleBitstreamCursor
R(Lengths);
2655 StringRef Strings = Blob.
drop_front(StringsOffset);
2657 if (
R.AtEndOfStream())
2658 return error(
"Invalid record: metadata strings bad length");
2664 return error(
"Invalid record: metadata strings truncated chars");
2668 }
while (--NumStrings);
2673Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2674 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2676 for (
unsigned I = 0,
E =
Record.size();
I !=
E;
I += 2) {
2677 auto K = MDKindMap.find(Record[
I]);
2678 if (K == MDKindMap.end())
2679 return error(
"Invalid ID");
2683 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
2696 PlaceholderQueue Placeholders;
2700 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2703 switch (Entry.Kind) {
2706 return error(
"Malformed block");
2709 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2718 ++NumMDRecordLoaded;
2722 switch (MaybeRecord.
get()) {
2726 unsigned RecordLength =
Record.size();
2728 return error(
"Invalid record");
2729 if (RecordLength % 2 == 0) {
2731 if (
Error Err = parseGlobalObjectAttachment(
F,
Record))
2738 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
2739 unsigned Kind =
Record[i];
2740 auto I = MDKindMap.find(Kind);
2741 if (
I == MDKindMap.end())
2742 return error(
"Invalid ID");
2743 if (
I->second == LLVMContext::MD_tbaa && StripTBAA)
2746 auto Idx =
Record[i + 1];
2747 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2748 !MetadataList.lookup(Idx)) {
2751 lazyLoadOneMetadata(Idx, Placeholders);
2753 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2763 return error(
"Invalid metadata attachment");
2765 if (HasSeenOldLoopTags &&
I->second == LLVMContext::MD_loop)
2768 if (
I->second == LLVMContext::MD_tbaa) {
2771 }
else if (
I->second == LLVMContext::MD_tbaa_struct) {
2776 if (
I->second == LLVMContext::MD_alias_scope ||
2777 I->second == LLVMContext::MD_noalias)
2789Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2792 return error(
"Invalid record");
2794 unsigned Kind =
Record[0];
2797 unsigned NewKind = TheModule.getMDKindID(Name.str());
2798 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2799 return error(
"Conflicting METADATA_KIND records");
2813 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2816 switch (Entry.Kind) {
2819 return error(
"Malformed block");
2829 ++NumMDRecordLoaded;
2833 switch (MaybeCode.
get()) {
2846 Pimpl = std::move(RHS.Pimpl);
2850 : Pimpl(
std::
move(RHS.Pimpl)) {}
2858 Stream, TheModule, ValueList,
std::
move(Callbacks), IsImporting)) {}
2860Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2861 return Pimpl->parseMetadata(ModuleLevel);
2869 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2873 return Pimpl->lookupSubprogramForFunction(
F);
2878 return Pimpl->parseMetadataAttachment(
F, InstructionList);
2882 return Pimpl->parseMetadataKinds();
2886 return Pimpl->setStripTBAA(StripTBAA);
2895 return Pimpl->upgradeDebugIntrinsics(
F);
2899 return Pimpl->upgradeAliasScopeList(ScopeList);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
#define LLVM_LIKELY(EXPR)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define GET_OR_DISTINCT(CLASS, ARGS)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
This file 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 ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
MDString * getRawIdentifier() const
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
DISPFlags
Debug info subprogram flags.
bool isForwardDecl() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
ArrayRef< MDOperand > operands() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
LLVMContext & getContext() const
Tracking metadata reference owned by Metadata.
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
A Module instance is used to store all the information related to an LLVM module.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
iterator_range< op_iterator > operands()
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Implements a dense probed hash-table based set with some number of buckets stored inline.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
Get the string size.
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
LLVM Value Representation.
std::pair< iterator, bool > insert(const ValueT &V)
An efficient, type-erasing, non-owning reference to a callable.
constexpr char LanguageVersion[]
Key for Kernel::Metadata::mLanguageVersion.
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
@ 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...
std::enable_if_t< detail::IsValidPointer< X, Y >::value, bool > hasa(Y &&MD)
Check whether Metadata has a Value.
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.
@ Unknown
Not known to have no common set bits.
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 dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
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)
const BitReaderOptions & getBitReaderOptions(const LLVMContext &C)
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...
LLVM_ABI MDNode * UpgradeTBAAStructNode(MDNode &TBAAStructNode)
If the given !tbaa.struct node has old-style scalar field tags, return an equivalent node with each f...
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)
@ End
Run the machine verifier once, at the end of the pipeline.
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...