67#define DEBUG_TYPE "bitcode-reader"
69STATISTIC(NumMDStringLoaded,
"Number of MDStrings loaded");
70STATISTIC(NumMDNodeTemporary,
"Number of MDNode::Temporary created");
71STATISTIC(NumMDRecordLoaded,
"Number of Metadata records loaded");
77 cl::desc(
"Import full type definitions for ThinLTO."));
81 cl::desc(
"Force disable the lazy-loading on-demand of metadata when "
82 "loading bitcode for importing."));
86static int64_t unrotateSign(
uint64_t U) {
return (U & 1) ? ~(U >> 1) : U >> 1; }
88class BitcodeReaderMetadataList {
101 SmallDenseSet<unsigned, 1> UnresolvedNodes;
105 SmallDenseMap<MDString *, TempMDTuple, 1>
Unknown;
106 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
107 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
115 unsigned RefsUpperBound;
118 BitcodeReaderMetadataList(LLVMContext &
C,
size_t RefsUpperBound)
120 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::
max(),
124 unsigned size()
const {
return MetadataPtrs.
size(); }
125 void resize(
unsigned N) { MetadataPtrs.
resize(
N); }
127 void clear() { MetadataPtrs.
clear(); }
129 void pop_back() { MetadataPtrs.
pop_back(); }
130 bool empty()
const {
return MetadataPtrs.
empty(); }
132 Metadata *operator[](
unsigned i)
const {
134 return MetadataPtrs[i];
138 if (
I < MetadataPtrs.
size())
139 return MetadataPtrs[
I];
143 void shrinkTo(
unsigned N) {
144 assert(
N <=
size() &&
"Invalid shrinkTo request!");
146 assert(UnresolvedNodes.
empty() &&
"Unexpected unresolved node");
152 Metadata *getMetadataFwdRef(
unsigned Idx);
158 Metadata *getMetadataIfResolved(
unsigned Idx);
160 MDNode *getMDNodeFwdRefOrNull(
unsigned Idx);
161 void assignValue(
Metadata *MD,
unsigned Idx);
162 void tryToResolveCycles();
164 int getNextFwdRef() {
170 void addTypeRef(MDString &
UUID, DICompositeType &CT);
182void BitcodeReaderMetadataList::assignValue(
Metadata *MD,
unsigned Idx) {
184 if (!MDN->isResolved())
185 UnresolvedNodes.
insert(Idx);
195 TrackingMDRef &OldMD = MetadataPtrs[Idx];
203 PrevMD->replaceAllUsesWith(MD);
207Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(
unsigned Idx) {
209 if (Idx >= RefsUpperBound)
215 if (
Metadata *MD = MetadataPtrs[Idx])
222 ++NumMDNodeTemporary;
224 MetadataPtrs[Idx].reset(MD);
228Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(
unsigned Idx) {
231 if (!
N->isResolved())
236MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(
unsigned Idx) {
240void BitcodeReaderMetadataList::tryToResolveCycles() {
246 for (
const auto &
Ref : OldTypeRefs.FwdDecls)
247 OldTypeRefs.Final.insert(
Ref);
248 OldTypeRefs.FwdDecls.clear();
252 for (
const auto &Array : OldTypeRefs.Arrays)
253 Array.second->replaceAllUsesWith(resolveTypeRefArray(
Array.first.get()));
254 OldTypeRefs.Arrays.clear();
259 for (
const auto &
Ref : OldTypeRefs.Unknown) {
260 if (DICompositeType *CT = OldTypeRefs.Final.lookup(
Ref.first))
261 Ref.second->replaceAllUsesWith(CT);
263 Ref.second->replaceAllUsesWith(
Ref.first);
265 OldTypeRefs.Unknown.clear();
267 if (UnresolvedNodes.
empty())
272 for (
unsigned I : UnresolvedNodes) {
273 auto &MD = MetadataPtrs[
I];
278 assert(!
N->isTemporary() &&
"Unexpected forward reference");
283 UnresolvedNodes.clear();
286void BitcodeReaderMetadataList::addTypeRef(MDString &
UUID,
287 DICompositeType &CT) {
290 OldTypeRefs.FwdDecls.insert(std::make_pair(&
UUID, &CT));
292 OldTypeRefs.Final.insert(std::make_pair(&
UUID, &CT));
300 if (
auto *CT = OldTypeRefs.Final.lookup(
UUID))
303 auto &
Ref = OldTypeRefs.Unknown[
UUID];
309Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(
Metadata *MaybeTuple) {
311 if (!Tuple || Tuple->isDistinct())
315 if (!Tuple->isTemporary())
316 return resolveTypeRefArray(Tuple);
320 OldTypeRefs.Arrays.emplace_back(
321 std::piecewise_construct, std::forward_as_tuple(Tuple),
323 return OldTypeRefs.Arrays.back().second.get();
326Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(
Metadata *MaybeTuple) {
328 if (!Tuple || Tuple->isDistinct())
333 Ops.reserve(Tuple->getNumOperands());
334 for (
Metadata *MD : Tuple->operands())
335 Ops.push_back(upgradeTypeRef(MD));
342class PlaceholderQueue {
345 std::deque<DistinctMDOperandPlaceholder> PHs;
348 ~PlaceholderQueue() {
350 "PlaceholderQueue hasn't been flushed before being destroyed");
352 bool empty()
const {
return PHs.empty(); }
353 DistinctMDOperandPlaceholder &getPlaceholderOp(
unsigned ID);
354 void flush(BitcodeReaderMetadataList &MetadataList);
358 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
359 DenseSet<unsigned> &Temporaries) {
360 for (
auto &PH : PHs) {
361 auto ID = PH.getID();
362 auto *MD = MetadataList.lookup(
ID);
368 if (
N &&
N->isTemporary())
376DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(
unsigned ID) {
377 PHs.emplace_back(
ID);
381void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
382 while (!PHs.empty()) {
383 auto *MD = MetadataList.lookup(PHs.front().getID());
384 assert(MD &&
"Flushing placeholder on unassigned MD");
387 assert(MDN->isResolved() &&
388 "Flushing Placeholder while cycles aren't resolved");
390 PHs.front().replaceUseWith(MD);
403 BitcodeReaderMetadataList MetadataList;
416 std::vector<StringRef> MDStringRef;
420 MDString *lazyLoadOneMDString(
unsigned Idx);
423 std::vector<uint64_t> GlobalMetadataBitPosIndex;
428 uint64_t GlobalDeclAttachmentPos = 0;
433 unsigned NumGlobalDeclAttachSkipped = 0;
434 unsigned NumGlobalDeclAttachParsed = 0;
447 void lazyLoadOneMetadata(
unsigned Idx, PlaceholderQueue &Placeholders);
451 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
460 bool StripTBAA =
false;
461 bool HasSeenOldLoopTags =
false;
462 bool NeedUpgradeToDIGlobalVariableExpression =
false;
463 bool NeedDeclareExpressionUpgrade =
false;
469 bool IsImporting =
false;
472 PlaceholderQueue &Placeholders,
StringRef Blob,
473 unsigned &NextMetadataNo);
480 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
483 void upgradeCUSubprograms() {
484 for (
auto CU_SP : CUSubprograms)
486 for (
auto &
Op : SPs->operands())
488 SP->replaceUnit(CU_SP.first);
489 CUSubprograms.clear();
493 void upgradeCUVariables() {
494 if (!NeedUpgradeToDIGlobalVariableExpression)
498 if (
NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu"))
499 for (
unsigned I = 0, E = CUNodes->getNumOperands();
I != E; ++
I) {
502 for (
unsigned I = 0;
I < GVs->getNumOperands();
I++)
512 for (
auto &GV : TheModule.globals()) {
514 GV.getMetadata(LLVMContext::MD_dbg, MDs);
515 GV.eraseMetadata(LLVMContext::MD_dbg);
520 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
522 GV.addMetadata(LLVMContext::MD_dbg, *MD);
529 if (
auto *SP = ParentSubprogram[S]) {
537 if (!Visited.
insert(S).second)
541 return ParentSubprogram[InitialScope] =
547 void upgradeCULocals() {
548 if (
NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu")) {
549 for (
MDNode *
N : CUNodes->operands()) {
554 if (
CU->getRawImportedEntities()) {
557 for (
Metadata *
Op :
CU->getImportedEntities()->operands()) {
560 EntitiesToRemove.
insert(IE);
564 if (!EntitiesToRemove.
empty()) {
567 for (
Metadata *
Op :
CU->getImportedEntities()->operands()) {
574 std::map<DISubprogram *, SmallVector<Metadata *>> SPToEntities;
575 for (
auto *
I : EntitiesToRemove) {
577 if (
auto *SP = findEnclosingSubprogram(
579 SPToEntities[SP].push_back(Entity);
584 for (
auto I = SPToEntities.begin();
I != SPToEntities.end(); ++
I) {
586 auto RetainedNodes = SP->getRetainedNodes();
588 RetainedNodes.end());
590 SP->replaceRetainedNodes(
MDNode::get(Context, MDs));
600 ParentSubprogram.clear();
605 void upgradeDeclareExpressions(
Function &
F) {
606 if (!NeedDeclareExpressionUpgrade)
609 auto UpdateDeclareIfNeeded = [&](
auto *Declare) {
610 auto *DIExpr = Declare->getExpression();
611 if (!DIExpr || !DIExpr->startsWithDeref() ||
615 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
622 if (DVR.isDbgDeclare())
623 UpdateDeclareIfNeeded(&DVR);
626 UpdateDeclareIfNeeded(DDI);
634 auto N = Expr.
size();
635 switch (FromVersion) {
637 return error(
"Invalid record");
639 if (
N >= 3 && Expr[
N - 3] == dwarf::DW_OP_bit_piece)
644 if (
N && Expr[0] == dwarf::DW_OP_deref) {
645 auto End = Expr.
end();
646 if (Expr.
size() >= 3 &&
648 End = std::prev(End, 3);
649 std::move(std::next(Expr.
begin()), End, Expr.
begin());
650 *std::prev(End) = dwarf::DW_OP_deref;
652 NeedDeclareExpressionUpgrade =
true;
658 while (!SubExpr.empty()) {
663 switch (SubExpr.front()) {
667 case dwarf::DW_OP_constu:
668 case dwarf::DW_OP_minus:
669 case dwarf::DW_OP_plus:
679 HistoricSize = std::min(SubExpr.size(), HistoricSize);
682 switch (SubExpr.front()) {
683 case dwarf::DW_OP_plus:
684 Buffer.
push_back(dwarf::DW_OP_plus_uconst);
685 Buffer.
append(Args.begin(), Args.end());
687 case dwarf::DW_OP_minus:
689 Buffer.
append(Args.begin(), Args.end());
694 Buffer.
append(Args.begin(), Args.end());
699 SubExpr = SubExpr.slice(HistoricSize);
712 void upgradeDebugInfo(
bool ModuleLevel) {
713 upgradeCUSubprograms();
714 upgradeCUVariables();
719 void callMDTypeCallback(
Metadata **Val,
unsigned TypeID);
725 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
726 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
727 TheModule(TheModule), Callbacks(
std::
move(Callbacks)),
728 IsImporting(IsImporting) {}
732 bool hasFwdRefs()
const {
return MetadataList.hasFwdRefs(); }
735 if (
ID < MDStringRef.size())
736 return lazyLoadOneMDString(
ID);
737 if (
auto *MD = MetadataList.lookup(
ID))
741 if (
ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
742 PlaceholderQueue Placeholders;
743 lazyLoadOneMetadata(
ID, Placeholders);
744 resolveForwardRefsAndPlaceholders(Placeholders);
745 return MetadataList.lookup(
ID);
747 return MetadataList.getMetadataFwdRef(
ID);
751 return FunctionsWithSPs.lookup(
F);
764 unsigned size()
const {
return MetadataList.size(); }
770MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
771 IndexCursor = Stream;
773 GlobalDeclAttachmentPos = 0;
784 switch (Entry.Kind) {
787 return error(
"Malformed block");
802 return std::move(Err);
809 return MaybeRecord.takeError();
810 unsigned NumStrings =
Record[0];
811 MDStringRef.reserve(NumStrings);
812 auto IndexNextMDString = [&](
StringRef Str) {
813 MDStringRef.push_back(Str);
815 if (
auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
816 return std::move(Err);
822 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
823 return std::move(Err);
825 if (Expected<unsigned> MaybeRecord =
826 IndexCursor.readRecord(
Entry.ID, Record))
829 return MaybeRecord.takeError();
830 if (Record.
size() != 2)
831 return error(
"Invalid record");
832 auto Offset = Record[0] + (Record[1] << 32);
833 auto BeginPos = IndexCursor.GetCurrentBitNo();
834 if (
Error Err = IndexCursor.JumpToBit(BeginPos +
Offset))
835 return std::move(Err);
836 Expected<BitstreamEntry> MaybeEntry =
837 IndexCursor.advanceSkippingSubblocks(
843 "Corrupted bitcode: Expected `Record` when trying to find the "
846 if (Expected<unsigned> MaybeCode =
847 IndexCursor.readRecord(
Entry.ID, Record))
849 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
850 "find the Metadata index");
852 return MaybeCode.takeError();
854 auto CurrentValue = BeginPos;
855 GlobalMetadataBitPosIndex.reserve(Record.
size());
856 for (
auto &Elt : Record) {
858 GlobalMetadataBitPosIndex.push_back(CurrentValue);
865 return error(
"Corrupted Metadata block");
868 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
869 return std::move(Err);
873 if (Expected<unsigned> MaybeCode =
874 IndexCursor.readRecord(
Entry.ID, Record)) {
875 Code = MaybeCode.get();
878 return MaybeCode.takeError();
881 SmallString<8>
Name(Record.begin(), Record.end());
882 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
883 Code = MaybeCode.get();
885 return MaybeCode.takeError();
890 if (Expected<unsigned> MaybeNextBitCode =
891 IndexCursor.readRecord(Code, Record))
894 return MaybeNextBitCode.takeError();
897 unsigned Size = Record.size();
898 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
899 for (
unsigned i = 0; i !=
Size; ++i) {
904 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
905 assert(MD &&
"Invalid metadata: expect fwd ref to MDNode");
911 if (!GlobalDeclAttachmentPos)
912 GlobalDeclAttachmentPos = SavedPos;
914 NumGlobalDeclAttachSkipped++;
958 GlobalMetadataBitPosIndex.clear();
972Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
974 if (!GlobalDeclAttachmentPos)
978 BitstreamCursor TempCursor = Stream;
979 SmallVector<uint64_t, 64> Record;
983 return std::move(Err);
985 BitstreamEntry
Entry;
992 switch (
Entry.Kind) {
995 return error(
"Malformed block");
998 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1010 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1014 NumGlobalDeclAttachParsed++;
1019 return std::move(Err);
1021 if (Expected<unsigned> MaybeRecord =
1025 return MaybeRecord.takeError();
1026 if (Record.
size() % 2 == 0)
1027 return error(
"Invalid record");
1028 unsigned ValueID = Record[0];
1029 if (ValueID >= ValueList.size())
1030 return error(
"Invalid record");
1036 if (
Error Err = parseGlobalObjectAttachment(
1037 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1038 return std::move(Err);
1040 return std::move(Err);
1045void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(
Metadata **Val,
1047 if (Callbacks.MDType) {
1048 (*Callbacks.MDType)(Val,
TypeID, Callbacks.GetTypeByID,
1049 Callbacks.GetContainedTypeID);
1057 if (!ModuleLevel && MetadataList.hasFwdRefs())
1058 return error(
"Invalid metadata: fwd refs into function blocks");
1062 auto EntryPos = Stream.GetCurrentBitNo();
1068 PlaceholderQueue Placeholders;
1072 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1074 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1076 return SuccessOrErr.takeError();
1077 if (SuccessOrErr.get()) {
1080 MetadataList.resize(MDStringRef.size() +
1081 GlobalMetadataBitPosIndex.size());
1086 SuccessOrErr = loadGlobalDeclAttachments();
1088 return SuccessOrErr.takeError();
1089 assert(SuccessOrErr.get());
1093 resolveForwardRefsAndPlaceholders(Placeholders);
1094 upgradeDebugInfo(ModuleLevel);
1097 Stream.ReadBlockEnd();
1098 if (
Error Err = IndexCursor.JumpToBit(EntryPos))
1100 if (
Error Err = Stream.SkipBlock()) {
1111 unsigned NextMetadataNo = MetadataList.size();
1116 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1119 switch (Entry.Kind) {
1122 return error(
"Malformed block");
1124 resolveForwardRefsAndPlaceholders(Placeholders);
1125 upgradeDebugInfo(ModuleLevel);
1135 ++NumMDRecordLoaded;
1137 Stream.readRecord(Entry.ID,
Record, &Blob)) {
1138 if (
Error Err = parseOneMetadata(
Record, MaybeCode.
get(), Placeholders,
1139 Blob, NextMetadataNo))
1146MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
1147 ++NumMDStringLoaded;
1151 MetadataList.assignValue(MDS,
ID);
1155void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1156 unsigned ID, PlaceholderQueue &Placeholders) {
1157 assert(
ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1158 assert(
ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
1160 if (
auto *MD = MetadataList.lookup(
ID)) {
1164 if (!
N || !
N->isTemporary())
1169 if (
Error Err = IndexCursor.JumpToBit(
1170 GlobalMetadataBitPosIndex[
ID - MDStringRef.size()]))
1174 if (
Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1178 ++NumMDRecordLoaded;
1180 IndexCursor.readRecord(Entry.ID,
Record, &Blob)) {
1182 parseOneMetadata(
Record, MaybeCode.
get(), Placeholders, Blob,
ID))
1192void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1193 PlaceholderQueue &Placeholders) {
1194 DenseSet<unsigned> Temporaries;
1197 Placeholders.getTemporaries(MetadataList, Temporaries);
1200 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
1205 for (
auto ID : Temporaries)
1206 lazyLoadOneMetadata(
ID, Placeholders);
1207 Temporaries.clear();
1211 while (MetadataList.hasFwdRefs())
1212 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1217 MetadataList.tryToResolveCycles();
1221 Placeholders.flush(MetadataList);
1225 Type *Ty,
unsigned TyID) {
1237 if (Idx < ValueList.
size() && ValueList[Idx] &&
1238 ValueList[Idx]->getType() == Ty)
1244Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1245 SmallVectorImpl<uint64_t> &Record,
unsigned Code,
1246 PlaceholderQueue &Placeholders, StringRef Blob,
unsigned &NextMetadataNo) {
1248 bool IsDistinct =
false;
1249 auto getMD = [&](
unsigned ID) ->
Metadata * {
1250 if (
ID < MDStringRef.size())
1251 return lazyLoadOneMDString(
ID);
1253 if (
auto *MD = MetadataList.lookup(
ID))
1257 if (
ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1261 MetadataList.getMetadataFwdRef(NextMetadataNo);
1262 lazyLoadOneMetadata(
ID, Placeholders);
1263 return MetadataList.lookup(
ID);
1266 return MetadataList.getMetadataFwdRef(
ID);
1268 if (
auto *MD = MetadataList.getMetadataIfResolved(
ID))
1270 return &Placeholders.getPlaceholderOp(
ID);
1272 auto getMDOrNull = [&](
unsigned ID) ->
Metadata * {
1274 return getMD(
ID - 1);
1277 auto getMDOrNullWithoutPlaceholders = [&](
unsigned ID) ->
Metadata * {
1279 return MetadataList.getMetadataFwdRef(
ID - 1);
1282 auto getMDString = [&](
unsigned ID) -> MDString * {
1285 auto MDS = getMDOrNull(
ID);
1290 auto getDITypeRefOrNull = [&](
unsigned ID) {
1291 return MetadataList.upgradeTypeRef(getMDOrNull(
ID));
1294 auto getMetadataOrConstant = [&](
bool IsMetadata,
1297 return getMDOrNull(Entry);
1302#define GET_OR_DISTINCT(CLASS, ARGS) \
1303 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1312 if (
Error E = Stream.ReadCode().moveInto(Code))
1315 ++NumMDRecordLoaded;
1316 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1318 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1320 return MaybeNextBitCode.takeError();
1324 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1325 for (
unsigned i = 0; i !=
Size; ++i) {
1326 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1328 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1337 if (Record.
size() % 2 == 1)
1338 return error(
"Invalid record");
1342 auto dropRecord = [&] {
1346 if (Record.
size() != 2) {
1351 unsigned TyID = Record[0];
1352 Type *Ty = Callbacks.GetTypeByID(TyID);
1358 Value *
V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1361 return error(
"Invalid value reference from old fn metadata");
1369 if (Record.
size() % 2 == 1)
1370 return error(
"Invalid record");
1374 for (
unsigned i = 0; i !=
Size; i += 2) {
1375 unsigned TyID = Record[i];
1376 Type *Ty = Callbacks.GetTypeByID(TyID);
1378 return error(
"Invalid record");
1384 return error(
"Invalid value reference from old metadata");
1387 "Expected non-function-local metadata");
1388 callMDTypeCallback(&MD, TyID);
1398 if (Record.
size() != 2)
1399 return error(
"Invalid record");
1401 unsigned TyID = Record[0];
1402 Type *Ty = Callbacks.GetTypeByID(TyID);
1404 return error(
"Invalid record");
1408 return error(
"Invalid value reference from metadata");
1411 callMDTypeCallback(&MD, TyID);
1412 MetadataList.assignValue(MD, NextMetadataNo);
1422 for (
unsigned ID : Record)
1432 if (Record.size() != 5 && Record.size() != 6 && Record.size() != 8)
1433 return error(
"Invalid record");
1435 IsDistinct = Record[0];
1436 unsigned Line = Record[1];
1437 unsigned Column = Record[2];
1439 Metadata *InlinedAt = getMDOrNull(Record[4]);
1440 bool ImplicitCode = Record.size() >= 6 && Record[5];
1441 uint64_t AtomGroup = Record.size() == 8 ? Record[6] : 0;
1442 uint8_t AtomRank = Record.size() == 8 ? Record[7] : 0;
1443 MetadataList.assignValue(
1445 ImplicitCode, AtomGroup, AtomRank)),
1451 if (Record.size() < 4)
1452 return error(
"Invalid record");
1454 IsDistinct = Record[0];
1455 unsigned Tag = Record[1];
1459 return error(
"Invalid record");
1461 auto *Header = getMDString(Record[3]);
1463 for (
unsigned I = 4,
E = Record.size();
I !=
E; ++
I)
1465 MetadataList.assignValue(
1481 switch (Record[0] >> 1) {
1484 (
Context, Record[1], unrotateSign(Record[2])));
1488 unrotateSign(Record[2])));
1492 DISubrange, (
Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1493 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1496 return error(
"Invalid record: Unsupported version of DISubrange");
1499 MetadataList.assignValue(Val, NextMetadataNo);
1500 IsDistinct = Record[0] & 1;
1507 (
Context, getMDOrNull(Record[1]),
1508 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1509 getMDOrNull(Record[4])));
1511 MetadataList.assignValue(Val, NextMetadataNo);
1512 IsDistinct = Record[0] & 1;
1517 if (Record.size() < 3)
1518 return error(
"Invalid record");
1520 IsDistinct = Record[0] & 1;
1521 bool IsUnsigned = Record[0] & 2;
1522 bool IsBigInt = Record[0] & 4;
1526 const uint64_t
BitWidth = Record[1];
1527 const size_t NumWords = Record.size() - 3;
1530 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1532 MetadataList.assignValue(
1540 if (Record.size() < 6 || Record.size() > 8)
1541 return error(
"Invalid record");
1543 IsDistinct = Record[0] & 1;
1544 bool SizeIsMetadata = Record[0] & 2;
1548 uint32_t NumExtraInhabitants = (Record.size() > 7) ? Record[7] : 0;
1550 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1552 MetadataList.assignValue(
1554 (
Context, Record[1], getMDString(Record[2]), SizeInBits,
1555 Record[4], Record[5], NumExtraInhabitants, Flags)),
1561 if (Record.size() < 11)
1562 return error(
"Invalid record");
1564 IsDistinct = Record[0] & 1;
1565 bool SizeIsMetadata = Record[0] & 2;
1568 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1572 auto ReadWideInt = [&]() {
1574 unsigned NumWords =
Encoded >> 32;
1581 APInt Numerator = ReadWideInt();
1582 APInt Denominator = ReadWideInt();
1584 if (
Offset != Record.size())
1585 return error(
"Invalid record");
1587 MetadataList.assignValue(
1589 (
Context, Record[1], getMDString(Record[2]), SizeInBits,
1590 Record[4], Record[5], Flags, Record[7], Record[8],
1591 Numerator, Denominator)),
1597 if (Record.size() > 9 || Record.size() < 8)
1598 return error(
"Invalid record");
1600 IsDistinct = Record[0] & 1;
1601 bool SizeIsMetadata = Record[0] & 2;
1602 bool SizeIs8 = Record.size() == 8;
1605 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1606 unsigned Offset = SizeIs8 ? 5 : 6;
1608 getMetadataOrConstant(SizeIsMetadata, Record[
Offset]);
1610 MetadataList.assignValue(
1612 (
Context, Record[1], getMDString(Record[2]),
1613 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1614 StringLocationExp, SizeInBits, Record[
Offset + 1],
1621 if (Record.size() < 12 || Record.size() > 15)
1622 return error(
"Invalid record");
1626 std::optional<unsigned> DWARFAddressSpace;
1627 if (Record.size() > 12 && Record[12])
1628 DWARFAddressSpace = Record[12] - 1;
1631 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1636 if (Record.size() > 14) {
1638 Annotations = getMDOrNull(Record[13]);
1640 PtrAuthData.emplace(Record[14]);
1643 IsDistinct = Record[0] & 1;
1644 bool SizeIsMetadata = Record[0] & 2;
1647 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1648 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1650 MetadataList.assignValue(
1652 (
Context, Record[1], getMDString(Record[2]),
1653 getMDOrNull(Record[3]), Record[4],
1654 getDITypeRefOrNull(Record[5]),
1655 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1656 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1657 getDITypeRefOrNull(Record[11]), Annotations)),
1663 if (Record.size() != 13)
1664 return error(
"Invalid record");
1666 IsDistinct = Record[0] & 1;
1667 bool SizeIsMetadata = Record[0] & 2;
1670 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1672 MetadataList.assignValue(
1674 (
Context, getMDString(Record[1]),
1675 getMDOrNull(Record[2]), Record[3],
1676 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1677 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1678 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1679 getMDOrNull(Record[12]))),
1685 if (Record.size() < 16 || Record.size() > 26)
1686 return error(
"Invalid record");
1690 IsDistinct = Record[0] & 0x1;
1691 bool IsNotUsedInTypeRef = Record[0] & 2;
1692 bool SizeIsMetadata = Record[0] & 4;
1693 unsigned Tag = Record[1];
1694 MDString *
Name = getMDString(Record[2]);
1696 unsigned Line = Record[4];
1699 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1700 return error(
"Alignment value is too large");
1701 uint32_t AlignInBits = Record[8];
1703 uint32_t NumExtraInhabitants = (Record.size() > 22) ? Record[22] : 0;
1706 unsigned RuntimeLang = Record[12];
1707 std::optional<uint32_t> EnumKind;
1710 Metadata *TemplateParams =
nullptr;
1735 (
Tag == dwarf::DW_TAG_enumeration_type ||
1736 Tag == dwarf::DW_TAG_class_type ||
1737 Tag == dwarf::DW_TAG_structure_type ||
1738 Tag == dwarf::DW_TAG_union_type)) {
1744 StringRef NameStr =
Name->getString();
1746 TemplateParams = getMDOrNull(Record[14]);
1748 BaseType = getDITypeRefOrNull(Record[6]);
1750 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1752 Elements = getMDOrNull(Record[11]);
1753 VTableHolder = getDITypeRefOrNull(Record[13]);
1754 TemplateParams = getMDOrNull(Record[14]);
1755 if (Record.size() > 16)
1757 if (Record.size() > 17)
1758 DataLocation = getMDOrNull(Record[17]);
1759 if (Record.size() > 19) {
1760 Associated = getMDOrNull(Record[18]);
1761 Allocated = getMDOrNull(Record[19]);
1763 if (Record.size() > 20) {
1764 Rank = getMDOrNull(Record[20]);
1766 if (Record.size() > 21) {
1767 Annotations = getMDOrNull(Record[21]);
1769 if (Record.size() > 23) {
1770 Specification = getMDOrNull(Record[23]);
1772 if (Record.size() > 25)
1773 BitStride = getMDOrNull(Record[25]);
1777 EnumKind = Record[24];
1779 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1781 DICompositeType *CT =
nullptr;
1785 SizeInBits, AlignInBits, OffsetInBits, Specification,
1786 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1787 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1788 Allocated, Rank, Annotations, BitStride);
1795 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1796 VTableHolder, TemplateParams, Identifier, Discriminator,
1797 DataLocation, Associated, Allocated, Rank, Annotations,
1798 Specification, NumExtraInhabitants, BitStride));
1799 if (!IsNotUsedInTypeRef && Identifier)
1802 MetadataList.assignValue(CT, NextMetadataNo);
1807 if (Record.size() < 3 || Record.size() > 4)
1808 return error(
"Invalid record");
1809 bool IsOldTypeRefArray = Record[0] < 2;
1810 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1812 IsDistinct = Record[0] & 0x1;
1816 Types = MetadataList.upgradeTypeRefArray(Types);
1818 MetadataList.assignValue(
1826 if (Record.size() < 5 || Record.size() > 9)
1827 return error(
"Invalid record");
1829 unsigned Offset = Record.size() >= 8 ? 2 : 1;
1830 IsDistinct = Record[0];
1831 MetadataList.assignValue(
1834 (
Context, Record.size() >= 8 ? getMDOrNull(Record[1]) :
nullptr,
1835 getMDOrNull(Record[0 +
Offset]), getMDString(Record[1 +
Offset]),
1836 getMDString(Record[2 +
Offset]), getMDString(Record[3 +
Offset]),
1837 getMDString(Record[4 +
Offset]),
1838 Record.size() <= 7 ? 0 : Record[7],
1839 Record.size() <= 8 ?
false : Record[8])),
1846 if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1847 return error(
"Invalid record");
1849 IsDistinct = Record[0];
1850 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1856 if (Record.size() > 4 && Record[3] && Record[4])
1858 getMDString(Record[4]));
1859 MetadataList.assignValue(
1861 (
Context, getMDString(Record[1]),
1862 getMDString(Record[2]), Checksum,
1863 Record.size() > 5 ? getMDString(Record[5]) :
nullptr)),
1869 if (Record.size() < 14 || Record.size() > 22)
1870 return error(
"Invalid record");
1876 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1877 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1878 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1879 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1880 Record.size() <= 15 ?
nullptr : getMDOrNull(Record[15]),
1881 Record.size() <= 14 ? 0 : Record[14],
1882 Record.size() <= 16 ?
true : Record[16],
1883 Record.size() <= 17 ?
false : Record[17],
1884 Record.size() <= 18 ? 0 : Record[18],
1885 Record.size() <= 19 ?
false : Record[19],
1886 Record.size() <= 20 ?
nullptr : getMDString(Record[20]),
1887 Record.size() <= 21 ?
nullptr : getMDString(Record[21]));
1889 MetadataList.assignValue(CU, NextMetadataNo);
1893 if (
Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1894 CUSubprograms.push_back({CU, SPs});
1898 if (Record.size() < 18 || Record.size() > 22)
1899 return error(
"Invalid record");
1901 bool HasSPFlags = Record[0] & 4;
1914 const unsigned DIFlagMainSubprogram = 1 << 21;
1915 bool HasOldMainSubprogramFlag =
Flags & DIFlagMainSubprogram;
1916 if (HasOldMainSubprogramFlag)
1920 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1922 if (HasOldMainSubprogramFlag && HasSPFlags)
1923 SPFlags |= DISubprogram::SPFlagMainSubprogram;
1924 else if (!HasSPFlags)
1926 Record[7], Record[8],
1927 Record[14], Record[11],
1928 HasOldMainSubprogramFlag);
1931 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
1937 bool HasUnit = Record[0] & 2;
1938 if (!HasSPFlags && HasUnit && Record.size() < 19)
1939 return error(
"Invalid record");
1940 if (HasSPFlags && !HasUnit)
1941 return error(
"Invalid record");
1944 bool HasThisAdj =
true;
1945 bool HasThrownTypes =
true;
1946 bool HasAnnotations =
false;
1947 bool HasTargetFuncName =
false;
1948 unsigned OffsetA = 0;
1949 unsigned OffsetB = 0;
1952 bool UsesKeyInstructions =
false;
1956 if (Record.size() >= 19) {
1960 HasThisAdj = Record.size() >= 20;
1961 HasThrownTypes = Record.size() >= 21;
1963 HasAnnotations = Record.size() >= 19;
1964 HasTargetFuncName = Record.size() >= 20;
1965 UsesKeyInstructions = Record.size() >= 21 ? Record[20] : 0;
1968 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1972 getDITypeRefOrNull(Record[1]),
1973 getMDString(Record[2]),
1974 getMDString(Record[3]),
1975 getMDOrNull(Record[4]),
1977 getMDOrNull(Record[6]),
1978 Record[7 + OffsetA],
1979 getDITypeRefOrNull(Record[8 + OffsetA]),
1980 Record[10 + OffsetA],
1981 HasThisAdj ? Record[16 + OffsetB] : 0,
1984 HasUnit ? CUorFn :
nullptr,
1985 getMDOrNull(Record[13 + OffsetB]),
1986 getMDOrNull(Record[14 + OffsetB]),
1987 getMDOrNull(Record[15 + OffsetB]),
1988 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1990 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
1992 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
1994 UsesKeyInstructions));
1995 MetadataList.assignValue(SP, NextMetadataNo);
2002 if (
F->isMaterializable())
2005 FunctionsWithSPs[
F] =
SP;
2006 else if (!
F->empty())
2007 F->setSubprogram(SP);
2013 if (Record.size() != 5)
2014 return error(
"Invalid record");
2016 IsDistinct = Record[0];
2017 MetadataList.assignValue(
2019 (
Context, getMDOrNull(Record[1]),
2020 getMDOrNull(Record[2]), Record[3], Record[4])),
2026 if (Record.size() != 4)
2027 return error(
"Invalid record");
2029 IsDistinct = Record[0];
2030 MetadataList.assignValue(
2032 (
Context, getMDOrNull(Record[1]),
2033 getMDOrNull(Record[2]), Record[3])),
2039 IsDistinct = Record[0] & 1;
2040 MetadataList.assignValue(
2042 (
Context, getMDOrNull(Record[1]),
2043 getMDOrNull(Record[2]), getMDString(Record[3]),
2044 getMDOrNull(Record[4]), Record[5])),
2052 if (Record.size() == 3)
2053 Name = getMDString(Record[2]);
2054 else if (Record.size() == 5)
2055 Name = getMDString(Record[3]);
2057 return error(
"Invalid record");
2059 IsDistinct = Record[0] & 1;
2060 bool ExportSymbols = Record[0] & 2;
2061 MetadataList.assignValue(
2063 (
Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2069 if (Record.size() != 5)
2070 return error(
"Invalid record");
2072 IsDistinct = Record[0];
2073 MetadataList.assignValue(
2075 (
Context, Record[1], Record[2], getMDString(Record[3]),
2076 getMDString(Record[4]))),
2082 if (Record.size() != 5)
2083 return error(
"Invalid record");
2085 IsDistinct = Record[0];
2086 MetadataList.assignValue(
2088 (
Context, Record[1], Record[2], getMDOrNull(Record[3]),
2089 getMDOrNull(Record[4]))),
2095 if (Record.size() < 3 || Record.size() > 4)
2096 return error(
"Invalid record");
2098 IsDistinct = Record[0];
2099 MetadataList.assignValue(
2101 (
Context, getMDString(Record[1]),
2102 getDITypeRefOrNull(Record[2]),
2103 (Record.size() == 4) ? getMDOrNull(Record[3])
2104 : getMDOrNull(
false))),
2110 if (Record.size() < 5 || Record.size() > 6)
2111 return error(
"Invalid record");
2113 IsDistinct = Record[0];
2115 MetadataList.assignValue(
2117 DITemplateValueParameter,
2118 (
Context, Record[1], getMDString(Record[2]),
2119 getDITypeRefOrNull(Record[3]),
2120 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(
false),
2121 (Record.size() == 6) ? getMDOrNull(Record[5])
2122 : getMDOrNull(Record[4]))),
2128 if (Record.size() < 11 || Record.size() > 13)
2129 return error(
"Invalid record");
2131 IsDistinct = Record[0] & 1;
2132 unsigned Version = Record[0] >> 1;
2136 if (Record.size() > 12)
2137 Annotations = getMDOrNull(Record[12]);
2139 MetadataList.assignValue(
2141 (
Context, getMDOrNull(Record[1]),
2142 getMDString(Record[2]), getMDString(Record[3]),
2143 getMDOrNull(Record[4]), Record[5],
2144 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2145 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2146 Record[11], Annotations)),
2153 MetadataList.assignValue(
2156 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2157 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2158 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2159 getMDOrNull(Record[10]),
nullptr, Record[11],
nullptr)),
2166 NeedUpgradeToDIGlobalVariableExpression =
true;
2167 Metadata *Expr = getMDOrNull(Record[9]);
2168 uint32_t AlignInBits = 0;
2169 if (Record.size() > 11) {
2170 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2171 return error(
"Alignment value is too large");
2172 AlignInBits = Record[11];
2174 GlobalVariable *Attach =
nullptr;
2181 {dwarf::DW_OP_constu, CI->getZExtValue(),
2182 dwarf::DW_OP_stack_value});
2189 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2190 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2191 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2192 getMDOrNull(Record[10]),
nullptr, AlignInBits,
nullptr));
2194 DIGlobalVariableExpression *DGVE =
nullptr;
2202 MetadataList.assignValue(MDNode, NextMetadataNo);
2205 return error(
"Invalid record");
2210 if (Record.size() != 1)
2211 return error(
"Invalid DIAssignID record.");
2213 IsDistinct = Record[0] & 1;
2215 return error(
"Invalid DIAssignID record. Must be distinct");
2223 if (Record.size() < 8 || Record.size() > 10)
2224 return error(
"Invalid record");
2226 IsDistinct = Record[0] & 1;
2227 bool HasAlignment = Record[0] & 2;
2231 bool HasTag = !HasAlignment && Record.size() > 8;
2233 uint32_t AlignInBits = 0;
2236 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2237 return error(
"Alignment value is too large");
2238 AlignInBits = Record[8];
2239 if (Record.size() > 9)
2240 Annotations = getMDOrNull(Record[9]);
2243 MetadataList.assignValue(
2245 (
Context, getMDOrNull(Record[1 + HasTag]),
2246 getMDString(Record[2 + HasTag]),
2247 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2248 getDITypeRefOrNull(Record[5 + HasTag]),
2249 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2255 if (Record.size() < 5 || Record.size() > 7)
2256 return error(
"Invalid record");
2258 IsDistinct = Record[0] & 1;
2259 uint64_t
Line = Record[4];
2260 uint64_t Column = Record.size() > 5 ? Record[5] : 0;
2261 bool IsArtificial = Record[0] & 2;
2262 std::optional<unsigned> CoroSuspendIdx;
2263 if (Record.size() > 6) {
2264 uint64_t RawSuspendIdx = Record[6];
2265 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2266 if (RawSuspendIdx > (uint64_t)std::numeric_limits<unsigned>::max())
2267 return error(
"CoroSuspendIdx value is too large");
2268 CoroSuspendIdx = RawSuspendIdx;
2272 MetadataList.assignValue(
2274 (
Context, getMDOrNull(Record[1]),
2275 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2276 Column, IsArtificial, CoroSuspendIdx)),
2282 if (Record.size() < 1)
2283 return error(
"Invalid record");
2285 IsDistinct = Record[0] & 1;
2286 uint64_t
Version = Record[0] >> 1;
2287 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2290 if (
Error Err = upgradeDIExpression(
Version, Elts, Buffer))
2299 if (Record.size() != 3)
2300 return error(
"Invalid record");
2302 IsDistinct = Record[0];
2303 Metadata *Expr = getMDOrNull(Record[2]);
2306 MetadataList.assignValue(
2308 (
Context, getMDOrNull(Record[1]), Expr)),
2314 if (Record.size() != 8)
2315 return error(
"Invalid record");
2317 IsDistinct = Record[0];
2318 MetadataList.assignValue(
2320 (
Context, getMDString(Record[1]),
2321 getMDOrNull(Record[2]), Record[3],
2322 getMDString(Record[4]), getMDString(Record[5]),
2323 Record[6], getDITypeRefOrNull(Record[7]))),
2329 if (Record.size() < 6 || Record.size() > 8)
2330 return error(
"Invalid DIImportedEntity record");
2332 IsDistinct = Record[0];
2333 bool HasFile = (Record.size() >= 7);
2334 bool HasElements = (Record.size() >= 8);
2335 MetadataList.assignValue(
2337 (
Context, Record[1], getMDOrNull(Record[2]),
2338 getDITypeRefOrNull(Record[3]),
2339 HasFile ? getMDOrNull(Record[6]) :
nullptr,
2340 HasFile ? Record[4] : 0, getMDString(Record[5]),
2341 HasElements ? getMDOrNull(Record[7]) :
nullptr)),
2347 std::string
String(Record.begin(), Record.end());
2351 ++NumMDStringLoaded;
2353 MetadataList.assignValue(MD, NextMetadataNo);
2358 auto CreateNextMDString = [&](StringRef Str) {
2359 ++NumMDStringLoaded;
2363 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2368 if (Record.size() % 2 == 0)
2369 return error(
"Invalid record");
2370 unsigned ValueID = Record[0];
2371 if (ValueID >= ValueList.size())
2372 return error(
"Invalid record");
2374 if (
Error Err = parseGlobalObjectAttachment(
2375 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2382 if (
Error Err = parseMetadataKindRecord(Record))
2389 for (uint64_t Elt : Record) {
2393 "Invalid record: DIArgList should not contain forward refs");
2395 return error(
"Invalid record");
2405#undef GET_OR_DISTINCT
2408Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2409 ArrayRef<uint64_t> Record, StringRef Blob,
2410 function_ref<
void(StringRef)> CallBack) {
2414 if (Record.
size() != 2)
2415 return error(
"Invalid record: metadata strings layout");
2417 unsigned NumStrings = Record[0];
2418 unsigned StringsOffset = Record[1];
2420 return error(
"Invalid record: metadata strings with no strings");
2421 if (StringsOffset > Blob.
size())
2422 return error(
"Invalid record: metadata strings corrupt offset");
2424 StringRef Lengths = Blob.
slice(0, StringsOffset);
2425 SimpleBitstreamCursor
R(Lengths);
2427 StringRef Strings = Blob.
drop_front(StringsOffset);
2429 if (
R.AtEndOfStream())
2430 return error(
"Invalid record: metadata strings bad length");
2436 return error(
"Invalid record: metadata strings truncated chars");
2440 }
while (--NumStrings);
2445Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2446 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2448 for (
unsigned I = 0,
E = Record.
size();
I !=
E;
I += 2) {
2449 auto K = MDKindMap.find(Record[
I]);
2450 if (K == MDKindMap.end())
2451 return error(
"Invalid ID");
2455 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
2468 PlaceholderQueue Placeholders;
2472 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2475 switch (Entry.Kind) {
2478 return error(
"Malformed block");
2480 resolveForwardRefsAndPlaceholders(Placeholders);
2489 ++NumMDRecordLoaded;
2493 switch (MaybeRecord.
get()) {
2497 unsigned RecordLength =
Record.size();
2499 return error(
"Invalid record");
2500 if (RecordLength % 2 == 0) {
2502 if (
Error Err = parseGlobalObjectAttachment(
F,
Record))
2509 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
2510 unsigned Kind =
Record[i];
2512 if (
I == MDKindMap.end())
2513 return error(
"Invalid ID");
2514 if (
I->second == LLVMContext::MD_tbaa && StripTBAA)
2517 auto Idx =
Record[i + 1];
2518 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2519 !MetadataList.lookup(Idx)) {
2522 lazyLoadOneMetadata(Idx, Placeholders);
2523 resolveForwardRefsAndPlaceholders(Placeholders);
2533 return error(
"Invalid metadata attachment");
2535 if (HasSeenOldLoopTags &&
I->second == LLVMContext::MD_loop)
2538 if (
I->second == LLVMContext::MD_tbaa) {
2551Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2554 return error(
"Invalid record");
2556 unsigned Kind =
Record[0];
2559 unsigned NewKind = TheModule.getMDKindID(Name.str());
2560 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2561 return error(
"Conflicting METADATA_KIND records");
2575 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2578 switch (Entry.Kind) {
2581 return error(
"Malformed block");
2591 ++NumMDRecordLoaded;
2595 switch (MaybeCode.
get()) {
2608 Pimpl = std::move(RHS.Pimpl);
2612 : Pimpl(
std::
move(RHS.Pimpl)) {}
2620 Stream, TheModule, ValueList,
std::
move(Callbacks), IsImporting)) {}
2622Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2623 return Pimpl->parseMetadata(ModuleLevel);
2631 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2635 return Pimpl->lookupSubprogramForFunction(
F);
2640 return Pimpl->parseMetadataAttachment(
F, InstructionList);
2644 return Pimpl->parseMetadataKinds();
2648 return Pimpl->setStripTBAA(StripTBAA);
2657 return Pimpl->upgradeDebugIntrinsics(
F);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
#define LLVM_LIKELY(EXPR)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define GET_OR_DISTINCT(CLASS, ARGS)
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallString class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
std::pair< llvm::MachO::Target, std::string > UUID
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
@ AF_DontPopBlockAtEnd
If this flag is used, the advance() method does not automatically pop the block scope when the end of...
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
MDString * getRawIdentifier() const
ChecksumKind
Which algorithm (e.g.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
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....
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
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.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A vector that has set insertion semantics.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
bool contains(const key_type &key) const
Check if the SetVector contains the given key.
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...
reference emplace_back(ArgTypes &&... Args)
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.
StringRef - 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
size - 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.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Scope
Defines the scope in which this symbol should be visible: Default â Visible in the public interface o...
NodeAddr< CodeNode * > Code
LLVM_ABI Instruction & back() const
This is an optimization pass for GlobalISel generic memory operations.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
FunctionAddr VTableAddr Value
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
std::error_code make_error_code(BitcodeError E)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI MDNode * upgradeInstructionLoopAttachment(MDNode &N)
Upgrade the loop attachment metadata node.
auto cast_or_null(const Y &Val)
bool isa_and_nonnull(const Y &Val)
auto dyn_cast_or_null(const Y &Val)
FunctionAddr VTableAddr uintptr_t uintptr_t Version
bool mayBeOldLoopAttachmentTag(StringRef Name)
Check whether a string looks like an old loop attachment tag.
LLVM_ABI 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...
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.
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...