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");
73 cl::desc(
"Import full type definitions for ThinLTO."));
77 cl::desc(
"Force disable the lazy-loading on-demand of metadata when "
78 "loading bitcode for importing."));
82class BitcodeReaderMetadataList {
105 LLVMContext &Context;
109 unsigned RefsUpperBound;
112 BitcodeReaderMetadataList(LLVMContext &
C,
size_t RefsUpperBound)
114 RefsUpperBound(std::
min((size_t)std::numeric_limits<unsigned>::
max(),
117 using const_iterator = SmallVector<TrackingMDRef, 1>::const_iterator;
120 unsigned size()
const {
return MetadataPtrs.size(); }
121 void resize(
unsigned N) { MetadataPtrs.resize(
N); }
122 void push_back(
Metadata *MD) { MetadataPtrs.emplace_back(MD); }
123 void clear() { MetadataPtrs.clear(); }
125 void pop_back() { MetadataPtrs.pop_back(); }
126 bool empty()
const {
return MetadataPtrs.empty(); }
127 const_iterator
begin()
const {
return MetadataPtrs.begin(); }
128 const_iterator
end()
const {
return MetadataPtrs.end(); }
130 Metadata *operator[](
unsigned i)
const {
return MetadataPtrs[i]; }
133 if (
I < MetadataPtrs.size())
134 return MetadataPtrs[
I];
138 void shrinkTo(
unsigned N) {
139 assert(
N <=
size() &&
"Invalid shrinkTo request!");
140 assert(ForwardReference.empty() &&
"Unexpected forward refs");
141 assert(UnresolvedNodes.empty() &&
"Unexpected unresolved node");
142 MetadataPtrs.resize(
N);
147 Metadata *getMetadataFwdRef(
unsigned Idx);
153 Metadata *getMetadataIfResolved(
unsigned Idx);
155 MDNode *getMDNodeFwdRefOrNull(
unsigned Idx);
156 void assignValue(
Metadata *MD,
unsigned Idx);
157 void tryToResolveCycles();
158 bool hasFwdRefs()
const {
return !ForwardReference.empty(); }
159 int getNextFwdRef() {
161 return *ForwardReference.begin();
165 void addTypeRef(MDString &
UUID, DICompositeType &CT);
180void BitcodeReaderMetadataList::assignValue(
Metadata *MD,
unsigned Idx) {
182 if (!MDN->isResolved())
183 UnresolvedNodes.
insert(Idx);
193 TrackingMDRef &OldMD = MetadataPtrs[Idx];
201 PrevMD->replaceAllUsesWith(MD);
205Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(
unsigned Idx) {
207 if (Idx >= RefsUpperBound)
213 if (
Metadata *MD = MetadataPtrs[Idx])
220 ++NumMDNodeTemporary;
222 MetadataPtrs[Idx].reset(MD);
226Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(
unsigned Idx) {
229 if (!
N->isResolved())
234MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(
unsigned Idx) {
238void BitcodeReaderMetadataList::tryToResolveCycles() {
244 for (
const auto &
Ref : OldTypeRefs.FwdDecls)
245 OldTypeRefs.Final.insert(
Ref);
246 OldTypeRefs.FwdDecls.clear();
250 for (
const auto &Array : OldTypeRefs.Arrays)
251 Array.second->replaceAllUsesWith(resolveTypeArray(
Array.first.get()));
252 OldTypeRefs.Arrays.clear();
257 for (
const auto &
Ref : OldTypeRefs.Unknown) {
258 if (DICompositeType *CT = OldTypeRefs.Final.lookup(
Ref.first))
259 Ref.second->replaceAllUsesWith(CT);
261 Ref.second->replaceAllUsesWith(
Ref.first);
263 OldTypeRefs.Unknown.clear();
265 if (UnresolvedNodes.
empty())
270 for (
unsigned I : UnresolvedNodes) {
271 auto &MD = MetadataPtrs[
I];
276 assert(!
N->isTemporary() &&
"Unexpected forward reference");
281 UnresolvedNodes.clear();
284void BitcodeReaderMetadataList::addTypeRef(MDString &
UUID,
285 DICompositeType &CT) {
288 OldTypeRefs.FwdDecls.insert(std::make_pair(&
UUID, &CT));
290 OldTypeRefs.Final.insert(std::make_pair(&
UUID, &CT));
298 if (
auto *CT = OldTypeRefs.Final.lookup(
UUID))
301 auto &
Ref = OldTypeRefs.Unknown[
UUID];
307Metadata *BitcodeReaderMetadataList::upgradeTypeArray(
Metadata *MaybeTuple) {
309 if (!Tuple || Tuple->isDistinct())
313 if (!Tuple->isTemporary())
314 return resolveTypeArray(Tuple);
318 OldTypeRefs.Arrays.emplace_back(
319 std::piecewise_construct, std::forward_as_tuple(Tuple),
321 return OldTypeRefs.Arrays.back().second.get();
324Metadata *BitcodeReaderMetadataList::resolveTypeArray(
Metadata *MaybeTuple) {
326 if (!Tuple || Tuple->isDistinct())
331 Ops.reserve(Tuple->getNumOperands());
332 for (
Metadata *MD : Tuple->operands())
333 Ops.push_back(upgradeTypeRef(MD));
340class PlaceholderQueue {
343 std::deque<DistinctMDOperandPlaceholder> PHs;
346 ~PlaceholderQueue() {
348 "PlaceholderQueue hasn't been flushed before being destroyed");
350 bool empty()
const {
return PHs.empty(); }
351 DistinctMDOperandPlaceholder &getPlaceholderOp(
unsigned ID);
352 void flush(BitcodeReaderMetadataList &MetadataList);
356 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
357 DenseSet<unsigned> &Temporaries) {
358 for (
auto &PH : PHs) {
359 auto ID = PH.getID();
360 auto *MD = MetadataList.lookup(ID);
366 if (
N &&
N->isTemporary())
374DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(
unsigned ID) {
375 PHs.emplace_back(ID);
379void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
380 while (!PHs.empty()) {
381 auto *MD = MetadataList.lookup(PHs.front().getID());
382 assert(MD &&
"Flushing placeholder on unassigned MD");
385 assert(MDN->isResolved() &&
386 "Flushing Placeholder while cycles aren't resolved");
388 PHs.front().replaceUseWith(MD);
399 BitcodeReaderMetadataList MetadataList;
412 std::vector<StringRef> MDStringRef;
416 MDString *lazyLoadOneMDString(
unsigned Idx);
419 std::vector<uint64_t> GlobalMetadataBitPosIndex;
424 uint64_t GlobalDeclAttachmentPos = 0;
429 unsigned NumGlobalDeclAttachSkipped = 0;
430 unsigned NumGlobalDeclAttachParsed = 0;
443 void lazyLoadOneMetadata(
unsigned Idx, PlaceholderQueue &Placeholders);
447 std::vector<std::pair<DICompileUnit *, unsigned>> CUSubprograms;
461 bool StripTBAA =
false;
462 bool HasSeenOldLoopTags =
false;
463 bool NeedUpgradeToDIGlobalVariableExpression =
false;
464 bool NeedDeclareExpressionUpgrade =
false;
468 GlobalVariableExpression;
474 bool IsImporting =
false;
477 PlaceholderQueue &Placeholders,
StringRef Blob,
478 unsigned &NextMetadataNo);
485 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
488 void upgradeCUSubprograms() {
489 for (
auto CU_SP : CUSubprograms)
492 for (
auto &
Op : SPs->operands())
494 SP->replaceUnit(CU_SP.first);
495 CUSubprograms.clear();
499 void upgradeCUVariables() {
500 if (!NeedUpgradeToDIGlobalVariableExpression)
504 if (
NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu"))
505 for (
unsigned I = 0, E = CUNodes->getNumOperands();
I != E; ++
I) {
508 for (
unsigned I = 0;
I < GVs->getNumOperands();
I++)
521 for (
auto &GV : TheModule.globals()) {
523 GV.getMetadata(LLVMContext::MD_dbg, MDs);
524 GV.eraseMetadata(LLVMContext::MD_dbg);
532 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
534 GV.addMetadata(LLVMContext::MD_dbg, *MD);
541 if (
auto *SP = ParentSubprogram[S]) {
549 if (!Visited.
insert(S).second)
553 return ParentSubprogram[InitialScope] =
559 using SPToEntitiesMap =
565 template <
typename NodeT>
566 void upgradeOneCULocalsList(SPToEntitiesMap &SPToEntities,
DICompileUnit *
CU,
567 unsigned ListIndex) {
573 return !isa_and_nonnull<DILocalScope>(getScope(cast<NodeT>(MD)));
583 else if (
auto *SP = findEnclosingSubprogram(LS))
584 SPToEntities[SP].push_back(MD);
592 void upgradeCULocals() {
593 NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu");
597 SPToEntitiesMap SPToEntities;
604 upgradeOneCULocalsList<DIGlobalVariableExpression>(SPToEntities,
CU, 6);
606 upgradeOneCULocalsList<DIImportedEntity>(SPToEntities,
CU, 7);
608 upgradeOneCULocalsList<DICompositeType>(SPToEntities,
CU, 4);
612 for (
auto &[SP, Nodes] : SPToEntities)
613 SP->retainNodes(Nodes.begin(), Nodes.end());
614 SPToEntities.clear();
617 ParentSubprogram.clear();
622 void upgradeDeclareExpressions(
Function &
F) {
623 if (!NeedDeclareExpressionUpgrade)
626 auto UpdateDeclareIfNeeded = [&](
auto *Declare) {
627 auto *DIExpr = Declare->getExpression();
628 if (!DIExpr || !DIExpr->startsWithDeref() ||
632 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
639 if (DVR.isDbgDeclare())
640 UpdateDeclareIfNeeded(&DVR);
643 UpdateDeclareIfNeeded(DDI);
648 Error upgradeDIExpression(uint64_t FromVersion,
651 auto N = Expr.
size();
652 switch (FromVersion) {
654 return error(
"Invalid record");
656 if (
N >= 3 && Expr[
N - 3] == dwarf::DW_OP_bit_piece)
661 if (
N && Expr[0] == dwarf::DW_OP_deref) {
662 auto End = Expr.
end();
663 if (Expr.
size() >= 3 &&
665 End = std::prev(End, 3);
666 std::move(std::next(Expr.
begin()), End, Expr.
begin());
667 *std::prev(End) = dwarf::DW_OP_deref;
669 NeedDeclareExpressionUpgrade =
true;
675 while (!SubExpr.empty()) {
680 switch (SubExpr.front()) {
684 case dwarf::DW_OP_constu:
685 case dwarf::DW_OP_minus:
686 case dwarf::DW_OP_plus:
696 HistoricSize = std::min(SubExpr.size(), HistoricSize);
699 switch (SubExpr.front()) {
700 case dwarf::DW_OP_plus:
701 Buffer.
push_back(dwarf::DW_OP_plus_uconst);
702 Buffer.
append(Args.begin(), Args.end());
704 case dwarf::DW_OP_minus:
706 Buffer.
append(Args.begin(), Args.end());
711 Buffer.
append(Args.begin(), Args.end());
716 SubExpr = SubExpr.slice(HistoricSize);
734 enum class DebugInfoUpgradeMode {
743 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
744 if (Mode == DebugInfoUpgradeMode::None)
746 upgradeCUSubprograms();
747 upgradeCUVariables();
748 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
753 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
754 DebugInfoUpgradeMode DIUpgradeMode) {
755 resolveForwardRefsAndPlaceholders(Placeholders);
756 upgradeDebugInfo(DIUpgradeMode);
759 << NewDistinctSPs.size() <<
" subprogram(s).\n");
760 NewDistinctSPs.clear();
763 void callMDTypeCallback(
Metadata **Val,
unsigned TypeID);
769 : MetadataList(TheModule.
getContext(), Stream.SizeInBytes()),
770 ValueList(ValueList), Stream(Stream), Context(TheModule.
getContext()),
771 TheModule(TheModule), Callbacks(
std::
move(Callbacks)),
772 IsImporting(IsImporting) {}
776 bool hasFwdRefs()
const {
return MetadataList.hasFwdRefs(); }
779 if (ID < MDStringRef.size())
780 return lazyLoadOneMDString(ID);
781 if (
auto *MD = MetadataList.lookup(ID))
785 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
786 PlaceholderQueue Placeholders;
787 lazyLoadOneMetadata(ID, Placeholders);
789 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
790 return MetadataList.lookup(ID);
792 return MetadataList.getMetadataFwdRef(ID);
796 return FunctionsWithSPs.lookup(
F);
809 unsigned size()
const {
return MetadataList.size(); }
815MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
816 IndexCursor = Stream;
818 GlobalDeclAttachmentPos = 0;
821 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
829 switch (Entry.Kind) {
832 return error(
"Malformed block");
839 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
841 if (
Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
846 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
847 return std::move(Err);
851 IndexCursor.readRecord(Entry.ID,
Record, &Blob))
854 return MaybeRecord.takeError();
855 unsigned NumStrings =
Record[0];
856 MDStringRef.reserve(NumStrings);
857 auto IndexNextMDString = [&](
StringRef Str) {
858 MDStringRef.push_back(Str);
860 if (
auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
861 return std::move(Err);
867 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
868 return std::move(Err);
870 if (Expected<unsigned> MaybeRecord =
871 IndexCursor.readRecord(
Entry.ID, Record))
874 return MaybeRecord.takeError();
876 return error(
"Invalid record");
878 auto BeginPos = IndexCursor.GetCurrentBitNo();
879 if (
Error Err = IndexCursor.JumpToBit(BeginPos +
Offset))
880 return std::move(Err);
881 Expected<BitstreamEntry> MaybeEntry =
882 IndexCursor.advanceSkippingSubblocks(
888 "Corrupted bitcode: Expected `Record` when trying to find the "
891 if (Expected<unsigned> MaybeCode =
892 IndexCursor.readRecord(
Entry.ID, Record))
894 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
895 "find the Metadata index");
897 return MaybeCode.takeError();
899 auto CurrentValue = BeginPos;
900 GlobalMetadataBitPosIndex.reserve(
Record.size());
901 for (
auto &Elt : Record) {
903 GlobalMetadataBitPosIndex.push_back(CurrentValue);
910 return error(
"Corrupted Metadata block");
913 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
914 return std::move(Err);
918 if (Expected<unsigned> MaybeCode =
919 IndexCursor.readRecord(
Entry.ID, Record)) {
920 Code = MaybeCode.get();
923 return MaybeCode.takeError();
927 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
928 Code = MaybeCode.get();
930 return MaybeCode.takeError();
935 if (Expected<unsigned> MaybeNextBitCode =
936 IndexCursor.readRecord(Code, Record))
939 return MaybeNextBitCode.takeError();
943 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
944 for (
unsigned i = 0; i !=
Size; ++i) {
949 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
950 assert(MD &&
"Invalid metadata: expect fwd ref to MDNode");
956 if (!GlobalDeclAttachmentPos)
957 GlobalDeclAttachmentPos = SavedPos;
959 NumGlobalDeclAttachSkipped++;
1003 MDStringRef.clear();
1004 GlobalMetadataBitPosIndex.clear();
1018Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1020 if (!GlobalDeclAttachmentPos)
1024 BitstreamCursor TempCursor = Stream;
1025 SmallVector<uint64_t, 64>
Record;
1029 return std::move(Err);
1031 BitstreamEntry
Entry;
1036 return std::move(
E);
1038 switch (
Entry.Kind) {
1041 return error(
"Malformed block");
1044 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1056 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1060 NumGlobalDeclAttachParsed++;
1065 return std::move(Err);
1067 if (Expected<unsigned> MaybeRecord =
1071 return MaybeRecord.takeError();
1072 if (
Record.size() % 2 == 0)
1073 return error(
"Invalid record");
1074 unsigned ValueID =
Record[0];
1075 if (ValueID >= ValueList.size())
1076 return error(
"Invalid record");
1082 if (
Error Err = parseGlobalObjectAttachment(
1083 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1084 return std::move(Err);
1086 return std::move(Err);
1091void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(
Metadata **Val,
1093 if (Callbacks.MDType) {
1094 (*Callbacks.MDType)(Val,
TypeID, Callbacks.GetTypeByID,
1095 Callbacks.GetContainedTypeID);
1103 if (!ModuleLevel && MetadataList.hasFwdRefs())
1104 return error(
"Invalid metadata: fwd refs into function blocks");
1108 auto EntryPos = Stream.GetCurrentBitNo();
1114 PlaceholderQueue Placeholders;
1115 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1116 : DebugInfoUpgradeMode::Partial;
1120 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1122 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1124 return SuccessOrErr.takeError();
1125 if (SuccessOrErr.get()) {
1128 MetadataList.resize(MDStringRef.size() +
1129 GlobalMetadataBitPosIndex.size());
1134 SuccessOrErr = loadGlobalDeclAttachments();
1136 return SuccessOrErr.takeError();
1137 assert(SuccessOrErr.get());
1142 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1145 Stream.ReadBlockEnd();
1146 if (
Error Err = IndexCursor.JumpToBit(EntryPos))
1148 if (
Error Err = Stream.SkipBlock()) {
1159 unsigned NextMetadataNo = MetadataList.size();
1164 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1167 switch (Entry.Kind) {
1170 return error(
"Malformed block");
1173 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1183 ++NumMDRecordLoaded;
1185 Stream.readRecord(Entry.ID,
Record, &Blob)) {
1186 if (
Error Err = parseOneMetadata(
Record, MaybeCode.
get(), Placeholders,
1187 Blob, NextMetadataNo))
1194MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
1195 ++NumMDStringLoaded;
1196 if (
Metadata *MD = MetadataList.lookup(ID))
1199 MetadataList.assignValue(MDS, ID);
1203void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1204 unsigned ID, PlaceholderQueue &Placeholders) {
1205 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1206 assert(ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
1208 if (
auto *MD = MetadataList.lookup(ID)) {
1212 if (!
N || !
N->isTemporary())
1217 if (
Error Err = IndexCursor.JumpToBit(
1218 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1222 if (
Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1226 ++NumMDRecordLoaded;
1228 IndexCursor.readRecord(Entry.ID,
Record, &Blob)) {
1230 parseOneMetadata(
Record, MaybeCode.
get(), Placeholders, Blob, ID))
1240void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1241 PlaceholderQueue &Placeholders) {
1242 DenseSet<unsigned> Temporaries;
1245 Placeholders.getTemporaries(MetadataList, Temporaries);
1248 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
1253 for (
auto ID : Temporaries)
1254 lazyLoadOneMetadata(ID, Placeholders);
1255 Temporaries.clear();
1259 while (MetadataList.hasFwdRefs())
1260 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1265 MetadataList.tryToResolveCycles();
1269 Placeholders.flush(MetadataList);
1273 Type *Ty,
unsigned TyID) {
1285 if (Idx < ValueList.
size() && ValueList[Idx] &&
1286 ValueList[Idx]->getType() == Ty)
1292Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1293 SmallVectorImpl<uint64_t> &Record,
unsigned Code,
1294 PlaceholderQueue &Placeholders, StringRef Blob,
unsigned &NextMetadataNo) {
1296 bool IsDistinct =
false;
1297 auto getMD = [&](
unsigned ID) ->
Metadata * {
1298 if (ID < MDStringRef.size())
1299 return lazyLoadOneMDString(ID);
1301 if (
auto *MD = MetadataList.lookup(ID))
1305 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1309 MetadataList.getMetadataFwdRef(NextMetadataNo);
1310 lazyLoadOneMetadata(ID, Placeholders);
1311 return MetadataList.lookup(ID);
1314 return MetadataList.getMetadataFwdRef(ID);
1316 if (
auto *MD = MetadataList.getMetadataIfResolved(ID))
1318 return &Placeholders.getPlaceholderOp(ID);
1320 auto getMDOrNull = [&](
unsigned ID) ->
Metadata * {
1322 return getMD(ID - 1);
1325 auto getMDString = [&](
unsigned ID) -> MDString * {
1328 auto MDS = getMDOrNull(ID);
1333 auto getDITypeRefOrNull = [&](
unsigned ID) {
1334 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1337 auto getMetadataOrConstant = [&](
bool IsMetadata,
1340 return getMDOrNull(Entry);
1342 ConstantInt::get(Type::getInt64Ty(
Context), Entry));
1345#define GET_OR_DISTINCT(CLASS, ARGS) \
1346 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1355 if (
Error E = Stream.ReadCode().moveInto(Code))
1358 ++NumMDRecordLoaded;
1359 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1361 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1363 return MaybeNextBitCode.takeError();
1367 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1368 for (
unsigned i = 0; i !=
Size; ++i) {
1369 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1371 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1380 if (
Record.size() % 2 == 1)
1381 return error(
"Invalid record");
1385 auto dropRecord = [&] {
1389 if (
Record.size() != 2) {
1394 unsigned TyID =
Record[0];
1395 Type *Ty = Callbacks.GetTypeByID(TyID);
1401 Value *
V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1404 return error(
"Invalid value reference from old fn metadata");
1412 if (
Record.size() % 2 == 1)
1413 return error(
"Invalid record");
1417 for (
unsigned i = 0; i !=
Size; i += 2) {
1418 unsigned TyID =
Record[i];
1419 Type *Ty = Callbacks.GetTypeByID(TyID);
1421 return error(
"Invalid record");
1427 return error(
"Invalid value reference from old metadata");
1430 "Expected non-function-local metadata");
1431 callMDTypeCallback(&MD, TyID);
1442 return error(
"Invalid record");
1444 unsigned TyID =
Record[0];
1445 Type *Ty = Callbacks.GetTypeByID(TyID);
1447 return error(
"Invalid record");
1451 return error(
"Invalid value reference from metadata");
1454 callMDTypeCallback(&MD, TyID);
1455 MetadataList.assignValue(MD, NextMetadataNo);
1465 for (
unsigned ID : Record)
1476 return error(
"Invalid record");
1480 unsigned Column =
Record[2];
1482 Metadata *InlinedAt = getMDOrNull(Record[4]);
1486 MetadataList.assignValue(
1488 ImplicitCode, AtomGroup, AtomRank)),
1495 return error(
"Invalid record");
1502 return error(
"Invalid record");
1504 auto *Header = getMDString(Record[3]);
1506 for (
unsigned I = 4,
E =
Record.size();
I !=
E; ++
I)
1508 MetadataList.assignValue(
1524 switch (Record[0] >> 1) {
1535 DISubrange, (
Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1536 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1539 return error(
"Invalid record: Unsupported version of DISubrange");
1542 MetadataList.assignValue(Val, NextMetadataNo);
1543 IsDistinct =
Record[0] & 1;
1550 (
Context, getMDOrNull(Record[1]),
1551 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1552 getMDOrNull(Record[4])));
1554 MetadataList.assignValue(Val, NextMetadataNo);
1555 IsDistinct =
Record[0] & 1;
1561 return error(
"Invalid record");
1563 IsDistinct =
Record[0] & 1;
1564 bool IsUnsigned =
Record[0] & 2;
1565 bool IsBigInt =
Record[0] & 4;
1570 const size_t NumWords =
Record.size() - 3;
1575 MetadataList.assignValue(
1584 return error(
"Invalid record");
1586 IsDistinct =
Record[0] & 1;
1587 bool SizeIsMetadata =
Record[0] & 2;
1591 uint32_t NumExtraInhabitants = (
Record.size() > 7) ?
Record[7] : 0;
1592 uint32_t DataSizeInBits = (
Record.size() > 8) ?
Record[8] : 0;
1593 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1595 unsigned LineNo = 0;
1598 File = getMDOrNull(Record[9]);
1600 Scope = getMDOrNull(Record[11]);
1602 MetadataList.assignValue(
1604 (
Context, Record[1], getMDString(Record[2]), File,
1605 LineNo, Scope, SizeInBits, Record[4], Record[5],
1606 NumExtraInhabitants, DataSizeInBits, Flags)),
1613 return error(
"Invalid record");
1615 IsDistinct =
Record[0] & 1;
1616 bool SizeIsMetadata =
Record[0] & 2;
1619 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1623 auto ReadWideInt = [&]() {
1625 unsigned NumWords =
Encoded >> 32;
1632 APInt Numerator = ReadWideInt();
1633 APInt Denominator = ReadWideInt();
1636 unsigned LineNo = 0;
1644 return error(
"Invalid record");
1646 MetadataList.assignValue(
1648 (
Context, Record[1], getMDString(Record[2]), File,
1649 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1650 Record[7], Record[8], Numerator, Denominator)),
1657 return error(
"Invalid record");
1659 IsDistinct =
Record[0] & 1;
1660 bool SizeIsMetadata =
Record[0] & 2;
1661 bool SizeIs8 =
Record.size() == 8;
1664 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1665 unsigned Offset = SizeIs8 ? 5 : 6;
1667 getMetadataOrConstant(SizeIsMetadata, Record[
Offset]);
1669 MetadataList.assignValue(
1671 (
Context, Record[1], getMDString(Record[2]),
1672 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1673 StringLocationExp, SizeInBits, Record[
Offset + 1],
1681 return error(
"Invalid record");
1685 std::optional<unsigned> DWARFAddressSpace;
1686 if (
Record.size() > 12 && Record[12])
1687 DWARFAddressSpace =
Record[12] - 1;
1690 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1695 if (
Record.size() > 14) {
1697 Annotations = getMDOrNull(Record[13]);
1699 PtrAuthData.emplace(Record[14]);
1702 IsDistinct =
Record[0] & 1;
1703 bool SizeIsMetadata =
Record[0] & 2;
1706 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1707 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1709 MetadataList.assignValue(
1711 (
Context, Record[1], getMDString(Record[2]),
1712 getMDOrNull(Record[3]), Record[4],
1713 getDITypeRefOrNull(Record[5]),
1714 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1715 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1716 getDITypeRefOrNull(Record[11]), Annotations)),
1723 return error(
"Invalid record");
1725 IsDistinct =
Record[0] & 1;
1726 bool SizeIsMetadata =
Record[0] & 2;
1729 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1731 MetadataList.assignValue(
1733 (
Context, getMDString(Record[1]),
1734 getMDOrNull(Record[2]), Record[3],
1735 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1736 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1737 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1738 getMDOrNull(Record[12]))),
1745 return error(
"Invalid record");
1749 IsDistinct =
Record[0] & 0x1;
1750 bool IsNotUsedInTypeRef =
Record[0] & 2;
1751 bool SizeIsMetadata =
Record[0] & 4;
1753 MDString *
Name = getMDString(Record[2]);
1758 if (Record[8] > (
uint64_t)std::numeric_limits<uint32_t>::max())
1759 return error(
"Alignment value is too large");
1760 uint32_t AlignInBits =
Record[8];
1762 uint32_t NumExtraInhabitants = (
Record.size() > 22) ?
Record[22] : 0;
1765 unsigned RuntimeLang =
Record[12];
1766 std::optional<uint32_t> EnumKind;
1769 Metadata *TemplateParams =
nullptr;
1794 (
Tag == dwarf::DW_TAG_enumeration_type ||
1795 Tag == dwarf::DW_TAG_class_type ||
1796 Tag == dwarf::DW_TAG_structure_type ||
1797 Tag == dwarf::DW_TAG_union_type)) {
1803 StringRef NameStr =
Name->getString();
1805 TemplateParams = getMDOrNull(Record[14]);
1807 BaseType = getDITypeRefOrNull(Record[6]);
1809 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1811 Elements = getMDOrNull(Record[11]);
1812 VTableHolder = getDITypeRefOrNull(Record[13]);
1813 TemplateParams = getMDOrNull(Record[14]);
1817 DataLocation = getMDOrNull(Record[17]);
1818 if (
Record.size() > 19) {
1819 Associated = getMDOrNull(Record[18]);
1820 Allocated = getMDOrNull(Record[19]);
1822 if (
Record.size() > 20) {
1823 Rank = getMDOrNull(Record[20]);
1825 if (
Record.size() > 21) {
1826 Annotations = getMDOrNull(Record[21]);
1828 if (
Record.size() > 23) {
1829 Specification = getMDOrNull(Record[23]);
1832 BitStride = getMDOrNull(Record[25]);
1838 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1840 DICompositeType *CT =
nullptr;
1844 SizeInBits, AlignInBits, OffsetInBits, Specification,
1845 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1846 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1847 Allocated, Rank, Annotations, BitStride);
1854 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1855 VTableHolder, TemplateParams, Identifier, Discriminator,
1856 DataLocation, Associated, Allocated, Rank, Annotations,
1857 Specification, NumExtraInhabitants, BitStride));
1858 if (!IsNotUsedInTypeRef && Identifier)
1861 MetadataList.assignValue(CT, NextMetadataNo);
1867 return error(
"Invalid record");
1868 bool IsOldTypeArray =
Record[0] < 2;
1871 IsDistinct =
Record[0] & 0x1;
1875 Types = MetadataList.upgradeTypeArray(Types);
1877 MetadataList.assignValue(
1886 return error(
"Invalid record");
1890 MetadataList.assignValue(
1893 (
Context,
Record.size() >= 8 ? getMDOrNull(Record[1]) :
nullptr,
1894 getMDOrNull(Record[0 +
Offset]), getMDString(Record[1 +
Offset]),
1895 getMDString(Record[2 +
Offset]), getMDString(Record[3 +
Offset]),
1896 getMDString(Record[4 +
Offset]),
1897 Record.size() <= 7 ? 0 : Record[7],
1898 Record.size() <= 8 ?
false : Record[8])),
1906 return error(
"Invalid record");
1909 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1915 if (
Record.size() > 4 && Record[3] && Record[4])
1917 getMDString(Record[4]));
1918 MetadataList.assignValue(
1920 (
Context, getMDString(Record[1]),
1921 getMDString(Record[2]), Checksum,
1922 Record.size() > 5 ? getMDString(Record[5]) :
nullptr)),
1929 return error(
"Invalid record");
1935 const auto LangVersionMask = (
uint64_t(1) << 63);
1936 const bool HasVersionedLanguage =
Record[1] & LangVersionMask;
1943 if (
Record.size() > 23 &&
1945 return error(
"Invalid DICompileUnit dialect value");
1946 const uint16_t Dialect =
1947 Record.size() > 23 ?
static_cast<uint16_t
>(
Record[23]) : uint16_t(0);
1949 auto *CU = DICompileUnit::getDistinct(
1951 HasVersionedLanguage
1952 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
1953 LanguageVersion, Dialect)
1954 : DISourceLanguageName(Record[1], Dialect),
1955 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
1956 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
1957 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1958 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1959 Record.size() <= 15 ?
nullptr : getMDOrNull(Record[15]),
1960 Record.size() <= 14 ? 0 : Record[14],
1961 Record.size() <= 16 ?
true : Record[16],
1962 Record.size() <= 17 ?
false : Record[17],
1963 Record.size() <= 18 ? 0 : Record[18],
1964 Record.size() <= 19 ?
false : Record[19],
1969 Record.size() <= 20 ?
nullptr : getMDString(Record[20]),
1970 Record.size() <= 21 ?
nullptr : getMDString(Record[21]));
1972 MetadataList.assignValue(CU, NextMetadataNo);
1977 CUSubprograms.push_back({CU,
Record[11]});
1982 return error(
"Invalid record");
1984 bool HasSPFlags =
Record[0] & 4;
1997 const unsigned DIFlagMainSubprogram = 1 << 21;
1998 bool HasOldMainSubprogramFlag =
Flags & DIFlagMainSubprogram;
1999 if (HasOldMainSubprogramFlag)
2003 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
2005 if (HasOldMainSubprogramFlag && HasSPFlags)
2006 SPFlags |= DISubprogram::SPFlagMainSubprogram;
2007 else if (!HasSPFlags)
2009 Record[7], Record[8],
2010 Record[14], Record[11],
2011 HasOldMainSubprogramFlag);
2014 IsDistinct = (
Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2020 bool HasUnit =
Record[0] & 2;
2021 if (!HasSPFlags && HasUnit &&
Record.size() < 19)
2022 return error(
"Invalid record");
2023 if (HasSPFlags && !HasUnit)
2024 return error(
"Invalid record");
2027 bool HasThisAdj =
true;
2028 bool HasThrownTypes =
true;
2029 bool HasAnnotations =
false;
2030 bool HasTargetFuncName =
false;
2031 unsigned OffsetA = 0;
2032 unsigned OffsetB = 0;
2035 bool UsesKeyInstructions =
false;
2039 if (
Record.size() >= 19) {
2043 HasThisAdj =
Record.size() >= 20;
2044 HasThrownTypes =
Record.size() >= 21;
2046 HasAnnotations =
Record.size() >= 19;
2047 HasTargetFuncName =
Record.size() >= 20;
2048 UsesKeyInstructions =
Record.size() >= 21 ?
Record[20] : 0;
2051 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2055 getDITypeRefOrNull(Record[1]),
2056 getMDString(Record[2]),
2057 getMDString(Record[3]),
2058 getMDOrNull(Record[4]),
2060 getMDOrNull(Record[6]),
2061 Record[7 + OffsetA],
2062 getDITypeRefOrNull(Record[8 + OffsetA]),
2063 Record[10 + OffsetA],
2064 HasThisAdj ? Record[16 + OffsetB] : 0,
2067 HasUnit ? CUorFn :
nullptr,
2068 getMDOrNull(Record[13 + OffsetB]),
2069 getMDOrNull(Record[14 + OffsetB]),
2070 getMDOrNull(Record[15 + OffsetB]),
2071 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2073 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2075 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2077 UsesKeyInstructions));
2078 MetadataList.assignValue(SP, NextMetadataNo);
2082 NewDistinctSPs.push_back(SP);
2088 if (
F->isMaterializable())
2091 FunctionsWithSPs[
F] =
SP;
2092 else if (!
F->empty())
2093 F->setSubprogram(SP);
2100 return error(
"Invalid record");
2103 MetadataList.assignValue(
2105 (
Context, getMDOrNull(Record[1]),
2106 getMDOrNull(Record[2]), Record[3], Record[4])),
2113 return error(
"Invalid record");
2116 MetadataList.assignValue(
2118 (
Context, getMDOrNull(Record[1]),
2119 getMDOrNull(Record[2]), Record[3])),
2125 IsDistinct =
Record[0] & 1;
2126 MetadataList.assignValue(
2128 (
Context, getMDOrNull(Record[1]),
2129 getMDOrNull(Record[2]), getMDString(Record[3]),
2130 getMDOrNull(Record[4]), Record[5])),
2139 Name = getMDString(Record[2]);
2140 else if (
Record.size() == 5)
2141 Name = getMDString(Record[3]);
2143 return error(
"Invalid record");
2145 IsDistinct =
Record[0] & 1;
2146 bool ExportSymbols =
Record[0] & 2;
2147 MetadataList.assignValue(
2149 (
Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2156 return error(
"Invalid record");
2159 MetadataList.assignValue(
2161 (
Context, Record[1], Record[2], getMDString(Record[3]),
2162 getMDString(Record[4]))),
2169 return error(
"Invalid record");
2172 MetadataList.assignValue(
2174 (
Context, Record[1], Record[2], getMDOrNull(Record[3]),
2175 getMDOrNull(Record[4]))),
2182 return error(
"Invalid record");
2185 MetadataList.assignValue(
2187 (
Context, getMDString(Record[1]),
2188 getDITypeRefOrNull(Record[2]),
2189 (
Record.size() == 4) ? getMDOrNull(Record[3])
2190 : getMDOrNull(
false))),
2197 return error(
"Invalid record");
2201 MetadataList.assignValue(
2203 DITemplateValueParameter,
2204 (
Context, Record[1], getMDString(Record[2]),
2205 getDITypeRefOrNull(Record[3]),
2206 (
Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(
false),
2207 (
Record.size() == 6) ? getMDOrNull(Record[5])
2208 : getMDOrNull(Record[4]))),
2215 return error(
"Invalid record");
2217 IsDistinct =
Record[0] & 1;
2223 Annotations = getMDOrNull(Record[12]);
2225 MetadataList.assignValue(
2227 (
Context, getMDOrNull(Record[1]),
2228 getMDString(Record[2]), getMDString(Record[3]),
2229 getMDOrNull(Record[4]), Record[5],
2230 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2231 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2232 Record[11], Annotations)),
2239 MetadataList.assignValue(
2242 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2243 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2244 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2245 getMDOrNull(Record[10]),
nullptr, Record[11],
nullptr)),
2252 NeedUpgradeToDIGlobalVariableExpression =
true;
2253 Metadata *Expr = getMDOrNull(Record[9]);
2254 uint32_t AlignInBits = 0;
2255 if (
Record.size() > 11) {
2256 if (Record[11] > (
uint64_t)std::numeric_limits<uint32_t>::max())
2257 return error(
"Alignment value is too large");
2258 AlignInBits =
Record[11];
2260 GlobalVariable *Attach =
nullptr;
2266 Expr = DIExpression::get(
Context,
2267 {dwarf::DW_OP_constu, CI->getZExtValue(),
2268 dwarf::DW_OP_stack_value});
2275 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2276 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2277 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2278 getMDOrNull(Record[10]),
nullptr, AlignInBits,
nullptr));
2280 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[DGV];
2281 if (Attach || Expr) {
2283 DGVE = DIGlobalVariableExpression::getDistinct(
2291 MetadataList.assignValue(MDNode, NextMetadataNo);
2294 return error(
"Invalid record");
2300 return error(
"Invalid DIAssignID record.");
2302 IsDistinct =
Record[0] & 1;
2304 return error(
"Invalid DIAssignID record. Must be distinct");
2313 return error(
"Invalid record");
2315 IsDistinct =
Record[0] & 1;
2316 bool HasAlignment =
Record[0] & 2;
2320 bool HasTag = !HasAlignment &&
Record.size() > 8;
2322 uint32_t AlignInBits = 0;
2325 if (Record[8] > (
uint64_t)std::numeric_limits<uint32_t>::max())
2326 return error(
"Alignment value is too large");
2329 Annotations = getMDOrNull(Record[9]);
2332 MetadataList.assignValue(
2334 (
Context, getMDOrNull(Record[1 + HasTag]),
2335 getMDString(Record[2 + HasTag]),
2336 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2337 getDITypeRefOrNull(Record[5 + HasTag]),
2338 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2345 return error(
"Invalid record");
2347 IsDistinct =
Record[0] & 1;
2350 bool IsArtificial =
Record[0] & 2;
2351 std::optional<unsigned> CoroSuspendIdx;
2354 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2355 if (RawSuspendIdx > (
uint64_t)std::numeric_limits<unsigned>::max())
2356 return error(
"CoroSuspendIdx value is too large");
2357 CoroSuspendIdx = RawSuspendIdx;
2361 MetadataList.assignValue(
2363 (
Context, getMDOrNull(Record[1]),
2364 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2365 Column, IsArtificial, CoroSuspendIdx)),
2372 return error(
"Invalid record");
2374 IsDistinct =
Record[0] & 1;
2379 if (
Error Err = upgradeDIExpression(
Version, Elts, Buffer))
2389 return error(
"Invalid record");
2392 Metadata *Expr = getMDOrNull(Record[2]);
2394 Expr = DIExpression::get(
Context, {});
2395 MetadataList.assignValue(
2397 (
Context, getMDOrNull(Record[1]), Expr)),
2404 return error(
"Invalid record");
2407 MetadataList.assignValue(
2409 (
Context, getMDString(Record[1]),
2410 getMDOrNull(Record[2]), Record[3],
2411 getMDString(Record[5]),
2412 getMDString(Record[4]), Record[6],
2413 getDITypeRefOrNull(Record[7]))),
2420 return error(
"Invalid record");
2423 MetadataList.assignValue(
2425 getMDOrNull(Record[2]), Record[3],
2426 getDITypeRefOrNull(Record[4]),
2427 getMDOrNull(Record[5]))),
2434 return error(
"Invalid DIImportedEntity record");
2437 bool HasFile = (
Record.size() >= 7);
2438 bool HasElements = (
Record.size() >= 8);
2439 MetadataList.assignValue(
2441 (
Context, Record[1], getMDOrNull(Record[2]),
2442 getDITypeRefOrNull(Record[3]),
2443 HasFile ? getMDOrNull(Record[6]) :
nullptr,
2444 HasFile ? Record[4] : 0, getMDString(Record[5]),
2445 HasElements ? getMDOrNull(Record[7]) :
nullptr)),
2455 ++NumMDStringLoaded;
2457 MetadataList.assignValue(MD, NextMetadataNo);
2462 auto CreateNextMDString = [&](StringRef Str) {
2466 ++NumMDStringLoaded;
2470 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2475 if (
Record.size() % 2 == 0)
2476 return error(
"Invalid record");
2477 unsigned ValueID =
Record[0];
2478 if (ValueID >= ValueList.size())
2479 return error(
"Invalid record");
2481 if (
Error Err = parseGlobalObjectAttachment(
2482 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2489 if (
Error Err = parseMetadataKindRecord(Record))
2500 "Invalid record: DIArgList should not contain forward refs");
2502 return error(
"Invalid record");
2512#undef GET_OR_DISTINCT
2515Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2516 ArrayRef<uint64_t> Record, StringRef Blob,
2517 function_ref<
void(StringRef)> CallBack) {
2522 return error(
"Invalid record: metadata strings layout");
2524 unsigned NumStrings =
Record[0];
2525 unsigned StringsOffset =
Record[1];
2527 return error(
"Invalid record: metadata strings with no strings");
2528 if (StringsOffset > Blob.
size())
2529 return error(
"Invalid record: metadata strings corrupt offset");
2531 StringRef Lengths = Blob.
slice(0, StringsOffset);
2532 SimpleBitstreamCursor
R(Lengths);
2534 StringRef Strings = Blob.
drop_front(StringsOffset);
2536 if (
R.AtEndOfStream())
2537 return error(
"Invalid record: metadata strings bad length");
2543 return error(
"Invalid record: metadata strings truncated chars");
2547 }
while (--NumStrings);
2552Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2553 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2555 for (
unsigned I = 0,
E =
Record.size();
I !=
E;
I += 2) {
2556 auto K = MDKindMap.find(Record[
I]);
2557 if (K == MDKindMap.end())
2558 return error(
"Invalid ID");
2562 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
2575 PlaceholderQueue Placeholders;
2579 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2582 switch (Entry.Kind) {
2585 return error(
"Malformed block");
2588 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2597 ++NumMDRecordLoaded;
2601 switch (MaybeRecord.
get()) {
2605 unsigned RecordLength =
Record.size();
2607 return error(
"Invalid record");
2608 if (RecordLength % 2 == 0) {
2610 if (
Error Err = parseGlobalObjectAttachment(
F,
Record))
2617 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
2618 unsigned Kind =
Record[i];
2619 auto I = MDKindMap.find(Kind);
2620 if (
I == MDKindMap.end())
2621 return error(
"Invalid ID");
2622 if (
I->second == LLVMContext::MD_tbaa && StripTBAA)
2625 auto Idx =
Record[i + 1];
2626 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2627 !MetadataList.lookup(Idx)) {
2630 lazyLoadOneMetadata(Idx, Placeholders);
2632 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2642 return error(
"Invalid metadata attachment");
2644 if (HasSeenOldLoopTags &&
I->second == LLVMContext::MD_loop)
2647 if (
I->second == LLVMContext::MD_tbaa) {
2660Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2663 return error(
"Invalid record");
2665 unsigned Kind =
Record[0];
2668 unsigned NewKind = TheModule.getMDKindID(Name.str());
2669 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2670 return error(
"Conflicting METADATA_KIND records");
2684 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2687 switch (Entry.Kind) {
2690 return error(
"Malformed block");
2700 ++NumMDRecordLoaded;
2704 switch (MaybeCode.
get()) {
2717 Pimpl = std::move(RHS.Pimpl);
2721 : Pimpl(
std::
move(RHS.Pimpl)) {}
2729 Stream, TheModule, ValueList,
std::
move(Callbacks), IsImporting)) {}
2731Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2732 return Pimpl->parseMetadata(ModuleLevel);
2740 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2744 return Pimpl->lookupSubprogramForFunction(
F);
2749 return Pimpl->parseMetadataAttachment(
F, InstructionList);
2753 return Pimpl->parseMetadataKinds();
2757 return Pimpl->setStripTBAA(StripTBAA);
2766 return Pimpl->upgradeDebugIntrinsics(
F);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
#define LLVM_LIKELY(EXPR)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define GET_OR_DISTINCT(CLASS, ARGS)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
This file defines the SmallString class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
std::pair< llvm::MachO::Target, std::string > UUID
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
@ AF_DontPopBlockAtEnd
If this flag is used, the advance() method does not automatically pop the block scope when the end of...
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
MDString * getRawIdentifier() const
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
DISPFlags
Debug info subprogram flags.
bool isForwardDecl() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
A Module instance is used to store all the information related to an LLVM module.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
iterator_range< op_iterator > operands()
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Implements a dense probed hash-table based set with some number of buckets stored inline.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
Get the string size.
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
LLVM Value Representation.
std::pair< iterator, bool > insert(const ValueT &V)
An efficient, type-erasing, non-owning reference to a callable.
constexpr char LanguageVersion[]
Key for Kernel::Metadata::mLanguageVersion.
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< CodeNode * > Code
LLVM_ABI Instruction & back() const
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
std::error_code make_error_code(BitcodeError E)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
LLVM_ABI MDNode * upgradeInstructionLoopAttachment(MDNode &N)
Upgrade the loop attachment metadata node.
auto cast_or_null(const Y &Val)
bool isa_and_nonnull(const Y &Val)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
static const DIScope * getScope(const NodeT *N)
auto dyn_cast_or_null(const Y &Val)
bool mayBeOldLoopAttachmentTag(StringRef Name)
Check whether a string looks like an old loop attachment tag.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
@ Ref
The access may reference the value stored in memory.
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
void consumeError(Error Err)
Consume a Error without doing anything.
Implement std::hash so that hash_code can be used in STL containers.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...