81 #include <system_error> 88 #define DEBUG_TYPE "bitcode-reader" 90 STATISTIC(NumMDStringLoaded,
"Number of MDStrings loaded");
91 STATISTIC(NumMDNodeTemporary,
"Number of MDNode::Temporary created");
92 STATISTIC(NumMDRecordLoaded,
"Number of Metadata records loaded");
98 cl::desc(
"Import full type definitions for ThinLTO."));
102 cl::desc(
"Force disable the lazy-loading on-demand of metadata when " 103 "loading bitcode for importing."));
107 static int64_t unrotateSign(uint64_t U) {
return U & 1 ? ~(U >> 1) : U >> 1; }
109 class BitcodeReaderMetadataList {
135 BitcodeReaderMetadataList(
LLVMContext &
C) : Context(C) {}
138 unsigned size()
const {
return MetadataPtrs.
size(); }
139 void resize(
unsigned N) { MetadataPtrs.
resize(N); }
143 void pop_back() { MetadataPtrs.
pop_back(); }
144 bool empty()
const {
return MetadataPtrs.
empty(); }
146 Metadata *operator[](
unsigned i)
const {
148 return MetadataPtrs[i];
152 if (I < MetadataPtrs.
size())
153 return MetadataPtrs[I];
157 void shrinkTo(
unsigned N) {
158 assert(N <=
size() &&
"Invalid shrinkTo request!");
159 assert(ForwardReference.
empty() &&
"Unexpected forward refs");
160 assert(UnresolvedNodes.
empty() &&
"Unexpected unresolved node");
166 Metadata *getMetadataFwdRef(
unsigned Idx);
172 Metadata *getMetadataIfResolved(
unsigned Idx);
174 MDNode *getMDNodeFwdRefOrNull(
unsigned Idx);
175 void assignValue(
Metadata *MD,
unsigned Idx);
176 void tryToResolveCycles();
177 bool hasFwdRefs()
const {
return !ForwardReference.
empty(); }
178 int getNextFwdRef() {
180 return *ForwardReference.
begin();
196 void BitcodeReaderMetadataList::assignValue(
Metadata *MD,
unsigned Idx) {
197 if (
auto *MDN = dyn_cast<MDNode>(MD))
198 if (!MDN->isResolved())
199 UnresolvedNodes.
insert(Idx);
216 TempMDTuple PrevMD(cast<MDTuple>(OldMD.
get()));
217 PrevMD->replaceAllUsesWith(MD);
218 ForwardReference.
erase(Idx);
221 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(
unsigned Idx) {
225 if (
Metadata *MD = MetadataPtrs[Idx])
229 ForwardReference.
insert(Idx);
232 ++NumMDNodeTemporary;
234 MetadataPtrs[Idx].reset(MD);
238 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(
unsigned Idx) {
240 if (
auto *N = dyn_cast_or_null<MDNode>(MD))
241 if (!N->isResolved())
246 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(
unsigned Idx) {
247 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
250 void BitcodeReaderMetadataList::tryToResolveCycles() {
251 if (!ForwardReference.
empty())
256 for (
const auto &
Ref : OldTypeRefs.FwdDecls)
257 OldTypeRefs.Final.insert(
Ref);
258 OldTypeRefs.FwdDecls.clear();
262 for (
const auto &Array : OldTypeRefs.Arrays)
263 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
264 OldTypeRefs.Arrays.clear();
269 for (
const auto &
Ref : OldTypeRefs.Unknown) {
271 Ref.second->replaceAllUsesWith(CT);
273 Ref.second->replaceAllUsesWith(
Ref.first);
275 OldTypeRefs.Unknown.clear();
277 if (UnresolvedNodes.
empty())
282 for (
unsigned I : UnresolvedNodes) {
283 auto &MD = MetadataPtrs[
I];
284 auto *N = dyn_cast_or_null<MDNode>(MD);
288 assert(!N->isTemporary() &&
"Unexpected forward reference");
293 UnresolvedNodes.clear();
296 void BitcodeReaderMetadataList::addTypeRef(
MDString &UUID,
300 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
302 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
306 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
310 if (
auto *CT = OldTypeRefs.Final.lookup(UUID))
313 auto &
Ref = OldTypeRefs.Unknown[UUID];
319 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(
Metadata *MaybeTuple) {
320 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
321 if (!Tuple || Tuple->isDistinct())
325 if (!Tuple->isTemporary())
326 return resolveTypeRefArray(Tuple);
330 OldTypeRefs.Arrays.emplace_back(
331 std::piecewise_construct, std::forward_as_tuple(Tuple),
333 return OldTypeRefs.Arrays.back().second.get();
336 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(
Metadata *MaybeTuple) {
337 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
338 if (!Tuple || Tuple->isDistinct())
343 Ops.
reserve(Tuple->getNumOperands());
344 for (
Metadata *MD : Tuple->operands())
352 class PlaceholderQueue {
355 std::deque<DistinctMDOperandPlaceholder> PHs;
358 ~PlaceholderQueue() {
359 assert(
empty() &&
"PlaceholderQueue hasn't been flushed before being destroyed");
361 bool empty() {
return PHs.empty(); }
363 void flush(BitcodeReaderMetadataList &MetadataList);
367 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
369 for (
auto &PH : PHs) {
370 auto ID = PH.getID();
371 auto *MD = MetadataList.lookup(
ID);
376 auto *N = dyn_cast_or_null<MDNode>(MD);
377 if (N && N->isTemporary())
386 PHs.emplace_back(ID);
390 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
391 while (!PHs.empty()) {
392 auto *MD = MetadataList.lookup(PHs.front().getID());
393 assert(MD &&
"Flushing placeholder on unassigned MD");
395 if (
auto *MDN = dyn_cast<MDNode>(MD))
396 assert(MDN->isResolved() &&
397 "Flushing Placeholder while cycles aren't resolved");
399 PHs.front().replaceUseWith(MD);
407 return make_error<StringError>(
412 BitcodeReaderMetadataList MetadataList;
417 std::function<Type *(unsigned)> getTypeByID;
425 std::vector<StringRef> MDStringRef;
429 MDString *lazyLoadOneMDString(
unsigned Idx);
432 std::vector<uint64_t> GlobalMetadataBitPosIndex;
441 void lazyLoadOneMetadata(
unsigned Idx, PlaceholderQueue &Placeholders);
445 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
454 bool StripTBAA =
false;
455 bool HasSeenOldLoopTags =
false;
456 bool NeedUpgradeToDIGlobalVariableExpression =
false;
457 bool NeedDeclareExpressionUpgrade =
false;
460 bool IsImporting =
false;
463 PlaceholderQueue &Placeholders,
StringRef Blob,
464 unsigned &NextMetadataNo);
471 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
474 void upgradeCUSubprograms() {
475 for (
auto CU_SP : CUSubprograms)
476 if (
auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
477 for (
auto &
Op : SPs->operands())
478 if (
auto *
SP = dyn_cast_or_null<DISubprogram>(
Op))
479 SP->replaceUnit(CU_SP.first);
480 CUSubprograms.clear();
484 void upgradeCUVariables() {
485 if (!NeedUpgradeToDIGlobalVariableExpression)
490 for (
unsigned I = 0,
E = CUNodes->getNumOperands(); I !=
E; ++
I) {
491 auto *
CU = cast<DICompileUnit>(CUNodes->getOperand(I));
492 if (
auto *GVs = dyn_cast_or_null<MDTuple>(
CU->getRawGlobalVariables()))
493 for (
unsigned I = 0; I < GVs->getNumOperands(); I++)
495 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
498 GVs->replaceOperandWith(I, DGVE);
503 for (
auto &GV : TheModule.
globals()) {
508 if (
auto *DGV = dyn_cast_or_null<DIGlobalVariable>(MD)) {
519 void upgradeDeclareExpressions(
Function &
F) {
520 if (!NeedDeclareExpressionUpgrade)
525 if (
auto *DDI = dyn_cast<DbgDeclareInst>(&I))
526 if (
auto *DIExpr = DDI->getExpression())
527 if (DIExpr->startsWithDeref() &&
528 dyn_cast_or_null<Argument>(DDI->getAddress())) {
530 Ops.
append(std::next(DIExpr->elements_begin()),
531 DIExpr->elements_end());
538 Error upgradeDIExpression(uint64_t FromVersion,
541 auto N = Expr.
size();
542 switch (FromVersion) {
544 return error(
"Invalid record");
546 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
551 if (N && Expr[0] == dwarf::DW_OP_deref) {
552 auto End = Expr.
end();
553 if (Expr.
size() >= 3 &&
555 End = std::prev(End, 3);
556 std::move(std::next(Expr.
begin()), End, Expr.
begin());
557 *std::prev(End) = dwarf::DW_OP_deref;
559 NeedDeclareExpressionUpgrade =
true;
565 while (!SubExpr.empty()) {
570 switch (SubExpr.front()) {
574 case dwarf::DW_OP_constu:
575 case dwarf::DW_OP_minus:
576 case dwarf::DW_OP_plus:
586 HistoricSize = std::min(SubExpr.size(), HistoricSize);
589 switch (SubExpr.front()) {
590 case dwarf::DW_OP_plus:
591 Buffer.
push_back(dwarf::DW_OP_plus_uconst);
592 Buffer.
append(Args.begin(), Args.end());
594 case dwarf::DW_OP_minus:
596 Buffer.
append(Args.begin(), Args.end());
601 Buffer.
append(Args.begin(), Args.end());
606 SubExpr = SubExpr.slice(HistoricSize);
619 void upgradeDebugInfo() {
620 upgradeCUSubprograms();
621 upgradeCUVariables();
629 : MetadataList(TheModule.getContext()), ValueList(ValueList),
630 Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
631 getTypeByID(
std::move(getTypeByID)), IsImporting(IsImporting) {}
633 Error parseMetadata(
bool ModuleLevel);
635 bool hasFwdRefs()
const {
return MetadataList.hasFwdRefs(); }
638 if (ID < MDStringRef.size())
639 return lazyLoadOneMDString(ID);
640 if (
auto *MD = MetadataList.lookup(ID))
644 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
645 PlaceholderQueue Placeholders;
646 lazyLoadOneMetadata(ID, Placeholders);
647 resolveForwardRefsAndPlaceholders(Placeholders);
648 return MetadataList.lookup(ID);
650 return MetadataList.getMetadataFwdRef(ID);
654 return FunctionsWithSPs.
lookup(F);
659 Error parseMetadataAttachment(
662 Error parseMetadataKinds();
667 unsigned size()
const {
return MetadataList.size(); }
668 void shrinkTo(
unsigned N) { MetadataList.shrinkTo(N); }
673 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
674 IndexCursor = Stream;
680 switch (Entry.
Kind) {
683 return error(
"Malformed block");
699 unsigned NumStrings = Record[0];
700 MDStringRef.
reserve(NumStrings);
701 auto IndexNextMDString = [&](
StringRef Str) {
702 MDStringRef.push_back(Str);
704 if (
auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
705 return std::move(Err);
714 if (Record.
size() != 2)
715 return error(
"Invalid record");
716 auto Offset = Record[0] + (Record[1] << 32);
722 "Corrupted bitcode: Expected `Record` when trying to find the " 728 "`METADATA_INDEX` when trying " 729 "to find the Metadata index");
732 auto CurrentValue = BeginPos;
733 GlobalMetadataBitPosIndex.reserve(Record.
size());
734 for (
auto &Elt : Record) {
736 GlobalMetadataBitPosIndex.push_back(CurrentValue);
743 return error(
"Corrupted Metadata block");
748 unsigned Code = IndexCursor.
readRecord(Entry.
ID, Record);
758 unsigned NextBitCode = IndexCursor.
readRecord(Code, Record);
765 for (
unsigned i = 0; i !=
Size; ++i) {
770 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
771 assert(MD &&
"Invalid metadata: expect fwd ref to MDNode");
782 if (Record.
size() % 2 == 0)
783 return error(
"Invalid record");
784 unsigned ValueID = Record[0];
785 if (ValueID >= ValueList.
size())
786 return error(
"Invalid record");
787 if (
auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
788 if (
Error Err = parseGlobalObjectAttachment(
790 return std::move(Err);
829 GlobalMetadataBitPosIndex.clear();
841 if (!ModuleLevel && MetadataList.hasFwdRefs())
842 return error(
"Invalid metadata: fwd refs into function blocks");
849 return error(
"Invalid record");
852 PlaceholderQueue Placeholders;
856 if (ModuleLevel && IsImporting && MetadataList.empty() &&
858 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
860 return SuccessOrErr.takeError();
861 if (SuccessOrErr.get()) {
864 MetadataList.resize(MDStringRef.size() +
865 GlobalMetadataBitPosIndex.size());
869 resolveForwardRefsAndPlaceholders(Placeholders);
876 return error(
"Invalid record");
882 unsigned NextMetadataNo = MetadataList.size();
888 switch (Entry.
Kind) {
891 return error(
"Malformed block");
893 resolveForwardRefsAndPlaceholders(Placeholders);
905 unsigned Code = Stream.
readRecord(Entry.
ID, Record, &Blob);
907 parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
912 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
914 if (
Metadata *MD = MetadataList.lookup(ID))
915 return cast<MDString>(MD);
917 MetadataList.assignValue(MDS, ID);
921 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
922 unsigned ID, PlaceholderQueue &Placeholders) {
923 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
924 assert(ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
926 if (
auto *MD = MetadataList.lookup(ID)) {
927 auto *N = dyn_cast_or_null<MDNode>(MD);
928 if (!N->isTemporary())
933 IndexCursor.
JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
936 unsigned Code = IndexCursor.
readRecord(Entry.ID, Record, &Blob);
937 if (
Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
943 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
944 PlaceholderQueue &Placeholders) {
948 Placeholders.getTemporaries(MetadataList, Temporaries);
951 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
956 for (
auto ID : Temporaries)
957 lazyLoadOneMetadata(ID, Placeholders);
962 while (MetadataList.hasFwdRefs())
963 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
968 MetadataList.tryToResolveCycles();
972 Placeholders.flush(MetadataList);
975 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
977 PlaceholderQueue &Placeholders,
StringRef Blob,
unsigned &NextMetadataNo) {
979 bool IsDistinct =
false;
981 if (ID < MDStringRef.size())
982 return lazyLoadOneMDString(ID);
984 if (
auto *MD = MetadataList.lookup(ID))
988 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
992 MetadataList.getMetadataFwdRef(NextMetadataNo);
993 lazyLoadOneMetadata(ID, Placeholders);
994 return MetadataList.lookup(ID);
997 return MetadataList.getMetadataFwdRef(ID);
999 if (
auto *MD = MetadataList.getMetadataIfResolved(ID))
1001 return &Placeholders.getPlaceholderOp(ID);
1003 auto getMDOrNull = [&](
unsigned ID) ->
Metadata * {
1005 return getMD(ID - 1);
1008 auto getMDOrNullWithoutPlaceholders = [&](
unsigned ID) ->
Metadata * {
1010 return MetadataList.getMetadataFwdRef(ID - 1);
1013 auto getMDString = [&](
unsigned ID) ->
MDString * {
1016 auto MDS = getMDOrNull(ID);
1017 return cast_or_null<MDString>(MDS);
1021 auto getDITypeRefOrNull = [&](
unsigned ID) {
1022 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1025 #define GET_OR_DISTINCT(CLASS, ARGS) \ 1026 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 1037 ++NumMDRecordLoaded;
1038 unsigned NextBitCode = Stream.
readRecord(Code, Record);
1040 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1045 for (
unsigned i = 0; i !=
Size; ++i) {
1046 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1048 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1057 if (Record.
size() % 2 == 1)
1058 return error(
"Invalid record");
1062 auto dropRecord = [&] {
1066 if (Record.
size() != 2) {
1071 Type *Ty = getTypeByID(Record[0]);
1077 MetadataList.assignValue(
1085 if (Record.
size() % 2 == 1)
1086 return error(
"Invalid record");
1090 for (
unsigned i = 0; i !=
Size; i += 2) {
1091 Type *Ty = getTypeByID(Record[i]);
1093 return error(
"Invalid record");
1099 assert(isa<ConstantAsMetadata>(MD) &&
1100 "Expected non-function-local metadata");
1105 MetadataList.assignValue(
MDNode::get(Context, Elts), NextMetadataNo);
1110 if (Record.
size() != 2)
1111 return error(
"Invalid record");
1113 Type *Ty = getTypeByID(Record[0]);
1115 return error(
"Invalid record");
1117 MetadataList.assignValue(
1129 for (
unsigned ID : Record)
1138 if (Record.
size() != 5 && Record.
size() != 6)
1139 return error(
"Invalid record");
1141 IsDistinct = Record[0];
1142 unsigned Line = Record[1];
1143 unsigned Column = Record[2];
1144 Metadata *Scope = getMD(Record[3]);
1145 Metadata *InlinedAt = getMDOrNull(Record[4]);
1146 bool ImplicitCode = Record.
size() == 6 && Record[5];
1147 MetadataList.assignValue(
1155 if (Record.
size() < 4)
1156 return error(
"Invalid record");
1158 IsDistinct = Record[0];
1159 unsigned Tag = Record[1];
1162 if (Tag >= 1u << 16 || Version != 0)
1163 return error(
"Invalid record");
1165 auto *Header = getMDString(Record[3]);
1167 for (
unsigned I = 4,
E = Record.
size(); I !=
E; ++
I)
1168 DwarfOps.
push_back(getMDOrNull(Record[I]));
1169 MetadataList.assignValue(
1180 switch (Record[0] >> 1) {
1183 (Context, Record[1], unrotateSign(Record.
back())));
1187 unrotateSign(Record.
back())));
1190 return error(
"Invalid record: Unsupported version of DISubrange");
1193 MetadataList.assignValue(Val, NextMetadataNo);
1194 IsDistinct = Record[0] & 1;
1199 if (Record.
size() != 3)
1200 return error(
"Invalid record");
1202 IsDistinct = Record[0] & 1;
1203 bool IsUnsigned = Record[0] & 2;
1204 MetadataList.assignValue(
1206 IsUnsigned, getMDString(Record[2]))),
1212 if (Record.
size() < 6 || Record.
size() > 7)
1213 return error(
"Invalid record");
1215 IsDistinct = Record[0];
1217 static_cast<DINode::DIFlags>(Record[6]) : DINode::FlagZero;
1219 MetadataList.assignValue(
1221 (Context, Record[1], getMDString(Record[2]), Record[3],
1222 Record[4], Record[5], Flags)),
1228 if (Record.
size() < 12 || Record.
size() > 13)
1229 return error(
"Invalid record");
1234 if (Record.
size() > 12 && Record[12])
1235 DWARFAddressSpace = Record[12] - 1;
1237 IsDistinct = Record[0];
1239 MetadataList.assignValue(
1241 (Context, Record[1], getMDString(Record[2]),
1242 getMDOrNull(Record[3]), Record[4],
1243 getDITypeRefOrNull(Record[5]),
1244 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1245 Record[9], DWARFAddressSpace, Flags,
1246 getDITypeRefOrNull(Record[11]))),
1252 if (Record.
size() < 16 || Record.
size() > 17)
1253 return error(
"Invalid record");
1257 IsDistinct = Record[0] & 0x1;
1258 bool IsNotUsedInTypeRef = Record[0] >= 2;
1259 unsigned Tag = Record[1];
1262 unsigned Line = Record[4];
1263 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1265 uint64_t SizeInBits = Record[7];
1267 return error(
"Alignment value is too large");
1269 uint64_t OffsetInBits = 0;
1272 unsigned RuntimeLang = Record[12];
1274 Metadata *TemplateParams =
nullptr;
1276 auto *Identifier = getMDString(Record[15]);
1285 (Tag == dwarf::DW_TAG_enumeration_type ||
1286 Tag == dwarf::DW_TAG_class_type ||
1287 Tag == dwarf::DW_TAG_structure_type ||
1288 Tag == dwarf::DW_TAG_union_type)) {
1289 Flags = Flags | DINode::FlagFwdDecl;
1291 BaseType = getDITypeRefOrNull(Record[6]);
1292 OffsetInBits = Record[9];
1293 Elements = getMDOrNull(Record[11]);
1294 VTableHolder = getDITypeRefOrNull(Record[13]);
1295 TemplateParams = getMDOrNull(Record[14]);
1296 if (Record.
size() > 16)
1297 Discriminator = getMDOrNull(Record[16]);
1302 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1303 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1304 VTableHolder, TemplateParams, Discriminator);
1309 (Context, Tag, Name, File, Line, Scope, BaseType,
1310 SizeInBits, AlignInBits, OffsetInBits, Flags,
1311 Elements, RuntimeLang, VTableHolder, TemplateParams,
1312 Identifier, Discriminator));
1313 if (!IsNotUsedInTypeRef && Identifier)
1314 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1316 MetadataList.assignValue(CT, NextMetadataNo);
1321 if (Record.
size() < 3 || Record.
size() > 4)
1322 return error(
"Invalid record");
1323 bool IsOldTypeRefArray = Record[0] < 2;
1324 unsigned CC = (Record.
size() > 3) ? Record[3] : 0;
1326 IsDistinct = Record[0] & 0x1;
1328 Metadata *Types = getMDOrNull(Record[2]);
1330 Types = MetadataList.upgradeTypeRefArray(Types);
1332 MetadataList.assignValue(
1340 if (Record.
size() != 6)
1341 return error(
"Invalid record");
1343 IsDistinct = Record[0];
1344 MetadataList.assignValue(
1346 (Context, getMDOrNull(Record[1]),
1347 getMDString(Record[2]), getMDString(Record[3]),
1348 getMDString(Record[4]), getMDString(Record[5]))),
1355 if (Record.
size() != 3 && Record.
size() != 5 && Record.
size() != 6)
1356 return error(
"Invalid record");
1358 IsDistinct = Record[0];
1365 if (Record.
size() > 4 && Record[3] && Record[4])
1366 Checksum.
emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
1367 getMDString(Record[4]));
1368 MetadataList.assignValue(
1371 (Context, getMDString(Record[1]), getMDString(Record[2]), Checksum,
1379 if (Record.
size() < 14 || Record.
size() > 19)
1380 return error(
"Invalid record");
1386 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1387 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1388 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1389 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1390 Record.
size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1391 Record.
size() <= 14 ? 0 : Record[14],
1392 Record.
size() <= 16 ?
true : Record[16],
1393 Record.
size() <= 17 ?
false : Record[17],
1394 Record.
size() <= 18 ? 0 : Record[18],
1395 Record.
size() <= 19 ? 0 : Record[19]);
1397 MetadataList.assignValue(
CU, NextMetadataNo);
1401 if (
Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1402 CUSubprograms.push_back({
CU, SPs});
1406 if (Record.
size() < 18 || Record.
size() > 21)
1407 return error(
"Invalid record");
1409 bool HasSPFlags = Record[0] & 4;
1414 Record[7], Record[8],
1415 Record[14], Record[11]);
1418 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
1424 bool HasUnit = Record[0] & 2;
1425 if (!HasSPFlags && HasUnit && Record.
size() < 19)
1426 return error(
"Invalid record");
1427 if (HasSPFlags && !HasUnit)
1428 return error(
"Invalid record");
1431 bool HasThisAdj =
true;
1432 bool HasThrownTypes =
true;
1433 unsigned OffsetA = 0;
1434 unsigned OffsetB = 0;
1438 if (Record.
size() >= 19) {
1442 HasThisAdj = Record.
size() >= 20;
1443 HasThrownTypes = Record.
size() >= 21;
1445 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1449 getDITypeRefOrNull(Record[1]),
1450 getMDString(Record[2]),
1451 getMDString(Record[3]),
1452 getMDOrNull(Record[4]),
1454 getMDOrNull(Record[6]),
1455 Record[7 + OffsetA],
1456 getDITypeRefOrNull(Record[8 + OffsetA]),
1457 Record[10 + OffsetA],
1458 HasThisAdj ? Record[16 + OffsetB] : 0,
1459 static_cast<DINode::DIFlags>(Record[11 + OffsetA]),
1461 HasUnit ? CUorFn :
nullptr,
1462 getMDOrNull(Record[13 + OffsetB]),
1463 getMDOrNull(Record[14 + OffsetB]),
1464 getMDOrNull(Record[15 + OffsetB]),
1465 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1468 MetadataList.assignValue(SP, NextMetadataNo);
1473 if (
auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1474 if (
auto *F = dyn_cast<Function>(CMD->getValue())) {
1478 FunctionsWithSPs[F] = SP;
1479 else if (!F->
empty())
1486 if (Record.
size() != 5)
1487 return error(
"Invalid record");
1489 IsDistinct = Record[0];
1490 MetadataList.assignValue(
1492 (Context, getMDOrNull(Record[1]),
1493 getMDOrNull(Record[2]), Record[3], Record[4])),
1499 if (Record.
size() != 4)
1500 return error(
"Invalid record");
1502 IsDistinct = Record[0];
1503 MetadataList.assignValue(
1505 (Context, getMDOrNull(Record[1]),
1506 getMDOrNull(Record[2]), Record[3])),
1514 if (Record.
size() == 3)
1515 Name = getMDString(Record[2]);
1516 else if (Record.
size() == 5)
1517 Name = getMDString(Record[3]);
1519 return error(
"Invalid record");
1521 IsDistinct = Record[0] & 1;
1522 bool ExportSymbols = Record[0] & 2;
1523 MetadataList.assignValue(
1525 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
1531 if (Record.
size() != 5)
1532 return error(
"Invalid record");
1534 IsDistinct = Record[0];
1535 MetadataList.assignValue(
1537 (Context, Record[1], Record[2], getMDString(Record[3]),
1538 getMDString(Record[4]))),
1544 if (Record.
size() != 5)
1545 return error(
"Invalid record");
1547 IsDistinct = Record[0];
1548 MetadataList.assignValue(
1550 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1551 getMDOrNull(Record[4]))),
1557 if (Record.
size() != 3)
1558 return error(
"Invalid record");
1560 IsDistinct = Record[0];
1562 (Context, getMDString(Record[1]),
1563 getDITypeRefOrNull(Record[2]))),
1569 if (Record.
size() != 5)
1570 return error(
"Invalid record");
1572 IsDistinct = Record[0];
1573 MetadataList.assignValue(
1575 (Context, Record[1], getMDString(Record[2]),
1576 getDITypeRefOrNull(Record[3]),
1577 getMDOrNull(Record[4]))),
1583 if (Record.
size() < 11 || Record.
size() > 13)
1584 return error(
"Invalid record");
1586 IsDistinct = Record[0] & 1;
1587 unsigned Version = Record[0] >> 1;
1590 MetadataList.assignValue(
1593 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1594 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1595 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1596 getMDOrNull(Record[9]), getMDOrNull(Record[10]), Record[11])),
1600 }
else if (Version == 1) {
1603 MetadataList.assignValue(
1605 (Context, getMDOrNull(Record[1]),
1606 getMDString(Record[2]), getMDString(Record[3]),
1607 getMDOrNull(Record[4]), Record[5],
1608 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1609 getMDOrNull(Record[10]),
nullptr, Record[11])),
1613 }
else if (Version == 0) {
1616 NeedUpgradeToDIGlobalVariableExpression =
true;
1617 Metadata *Expr = getMDOrNull(Record[9]);
1619 if (Record.
size() > 11) {
1621 return error(
"Alignment value is too large");
1622 AlignInBits = Record[11];
1625 if (
auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1626 if (
auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1629 }
else if (
auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1631 {dwarf::DW_OP_constu, CI->getZExtValue(),
1632 dwarf::DW_OP_stack_value});
1639 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1640 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1641 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1642 getMDOrNull(Record[10]),
nullptr, AlignInBits));
1651 auto *
MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1652 MetadataList.assignValue(
MDNode, NextMetadataNo);
1655 return error(
"Invalid record");
1661 if (Record.
size() < 8 || Record.
size() > 10)
1662 return error(
"Invalid record");
1664 IsDistinct = Record[0] & 1;
1665 bool HasAlignment = Record[0] & 2;
1669 bool HasTag = !HasAlignment && Record.
size() > 8;
1674 return error(
"Alignment value is too large");
1675 AlignInBits = Record[8 + HasTag];
1677 MetadataList.assignValue(
1679 (Context, getMDOrNull(Record[1 + HasTag]),
1680 getMDString(Record[2 + HasTag]),
1681 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1682 getDITypeRefOrNull(Record[5 + HasTag]),
1683 Record[6 + HasTag], Flags, AlignInBits)),
1689 if (Record.
size() != 5)
1690 return error(
"Invalid record");
1692 IsDistinct = Record[0] & 1;
1693 MetadataList.assignValue(
1695 (Context, getMDOrNull(Record[1]),
1696 getMDString(Record[2]),
1697 getMDOrNull(Record[3]), Record[4])),
1703 if (Record.
size() < 1)
1704 return error(
"Invalid record");
1706 IsDistinct = Record[0] & 1;
1707 uint64_t
Version = Record[0] >> 1;
1711 if (
Error Err = upgradeDIExpression(Version, Elts, Buffer))
1714 MetadataList.assignValue(
1720 if (Record.
size() != 3)
1721 return error(
"Invalid record");
1723 IsDistinct = Record[0];
1724 Metadata *Expr = getMDOrNull(Record[2]);
1727 MetadataList.assignValue(
1729 (Context, getMDOrNull(Record[1]), Expr)),
1735 if (Record.
size() != 8)
1736 return error(
"Invalid record");
1738 IsDistinct = Record[0];
1739 MetadataList.assignValue(
1741 (Context, getMDString(Record[1]),
1742 getMDOrNull(Record[2]), Record[3],
1743 getMDString(Record[4]), getMDString(Record[5]),
1744 Record[6], getDITypeRefOrNull(Record[7]))),
1750 if (Record.
size() != 6 && Record.
size() != 7)
1751 return error(
"Invalid record");
1753 IsDistinct = Record[0];
1754 bool HasFile = (Record.
size() == 7);
1755 MetadataList.assignValue(
1757 (Context, Record[1], getMDOrNull(Record[2]),
1758 getDITypeRefOrNull(Record[3]),
1759 HasFile ? getMDOrNull(Record[6]) :
nullptr,
1760 HasFile ? Record[4] : 0, getMDString(Record[5]))),
1770 ++NumMDStringLoaded;
1772 MetadataList.assignValue(MD, NextMetadataNo);
1777 auto CreateNextMDString = [&](
StringRef Str) {
1778 ++NumMDStringLoaded;
1779 MetadataList.assignValue(
MDString::get(Context, Str), NextMetadataNo);
1782 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
1787 if (Record.
size() % 2 == 0)
1788 return error(
"Invalid record");
1789 unsigned ValueID = Record[0];
1790 if (ValueID >= ValueList.
size())
1791 return error(
"Invalid record");
1792 if (
auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1793 if (
Error Err = parseGlobalObjectAttachment(
1801 if (
Error Err = parseMetadataKindRecord(Record))
1807 #undef GET_OR_DISTINCT 1810 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
1816 if (Record.
size() != 2)
1817 return error(
"Invalid record: metadata strings layout");
1819 unsigned NumStrings = Record[0];
1820 unsigned StringsOffset = Record[1];
1822 return error(
"Invalid record: metadata strings with no strings");
1823 if (StringsOffset > Blob.
size())
1824 return error(
"Invalid record: metadata strings corrupt offset");
1832 return error(
"Invalid record: metadata strings bad length");
1836 return error(
"Invalid record: metadata strings truncated chars");
1838 CallBack(Strings.
slice(0, Size));
1840 }
while (--NumStrings);
1845 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1848 for (
unsigned I = 0,
E = Record.
size(); I !=
E; I += 2) {
1849 auto K = MDKindMap.
find(Record[I]);
1850 if (K == MDKindMap.
end())
1851 return error(
"Invalid ID");
1852 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1854 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
1864 return error(
"Invalid record");
1867 PlaceholderQueue Placeholders;
1872 switch (Entry.
Kind) {
1875 return error(
"Malformed block");
1877 resolveForwardRefsAndPlaceholders(Placeholders);
1886 ++NumMDRecordLoaded;
1891 unsigned RecordLength = Record.
size();
1893 return error(
"Invalid record");
1894 if (RecordLength % 2 == 0) {
1896 if (
Error Err = parseGlobalObjectAttachment(F, Record))
1903 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
1904 unsigned Kind = Record[i];
1906 if (I == MDKindMap.
end())
1907 return error(
"Invalid ID");
1911 auto Idx = Record[i + 1];
1912 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
1913 !MetadataList.lookup(Idx)) {
1916 lazyLoadOneMetadata(Idx, Placeholders);
1917 resolveForwardRefsAndPlaceholders(Placeholders);
1920 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
1921 if (isa<LocalAsMetadata>(Node))
1925 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1927 return error(
"Invalid metadata attachment");
1945 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1947 if (Record.
size() < 2)
1948 return error(
"Invalid record");
1950 unsigned Kind = Record[0];
1954 if (!MDKindMap.
insert(std::make_pair(Kind, NewKind)).second)
1955 return error(
"Conflicting METADATA_KIND records");
1962 return error(
"Invalid record");
1970 switch (Entry.
Kind) {
1973 return error(
"Malformed block");
1983 ++NumMDRecordLoaded;
1989 if (
Error Err = parseMetadataKindRecord(Record))
1998 Pimpl = std::move(RHS.Pimpl);
2002 : Pimpl(
std::move(RHS.Pimpl)) {}
2010 Stream, TheModule, ValueList,
std::move(getTypeByID), IsImporting)) {}
2012 Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2013 return Pimpl->parseMetadata(ModuleLevel);
2021 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2025 return Pimpl->lookupSubprogramForFunction(F);
2030 return Pimpl->parseMetadataAttachment(F, InstructionList);
2034 return Pimpl->parseMetadataKinds();
2038 return Pimpl->setStripTBAA(StripTBAA);
2047 return Pimpl->upgradeDebugIntrinsics(F);
bool mayBeOldLoopAttachmentTag(StringRef Name)
Check whether a string looks like an old loop attachment tag.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Atomic ordering constants.
bool isMetadataTy() const
Return true if this is 'metadata'.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
A Module instance is used to store all the information related to an LLVM module. ...
Tracking metadata reference.
static MDString * get(LLVMContext &Context, StringRef Str)
void push_back(const T &Elt)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
void addOperand(MDNode *M)
void emplace(ArgTypes &&... Args)
Create a new object by constructing it in place with the given arguments.
An efficient, type-erasing, non-owning reference to a callable.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
bool erase(const ValueT &V)
STATISTIC(NumFunctions, "Total number of functions")
block Block Frequency true
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
void reserve(size_type N)
bool isForwardDecl() const
Value * getValueFwdRef(unsigned Idx, Type *Ty)
#define LLVM_UNLIKELY(EXPR)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
amdgpu Simplify well known AMD library false Value Value const Twine & Name
MDNode * upgradeInstructionLoopAttachment(MDNode &N)
Upgrade the loop attachment metadata node.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The access may reference the value stored in memory.
std::error_code make_error_code(BitcodeError E)
This file contains the simple types necessary to represent the attributes associated with functions a...
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Placeholder metadata for operands of distinct MDNodes.
Only used in LLVM metadata.
Tagged union holding either a T or a Error.
static const uint16_t * lookup(unsigned opcode, unsigned domain, ArrayRef< uint16_t[3]> Table)
This file implements a class to represent arbitrary precision integral constant values and operations...
uint32_t ReadVBR(unsigned NumBits)
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
BitstreamEntry advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
iterator find(const_arg_type_t< KeyT > Val)
bool isVoidTy() const
Return true if this is 'void'.
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Return a temporary node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual)
initializer< Ty > init(const Ty &Val)
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
enum llvm::BitstreamEntry::@149 Kind
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata *> MDs)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(const ValueT &V)
A pair of DIGlobalVariable and DIExpression.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
bool isMaterializable() const
void JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
bool SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block...
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
An imported module (C++ using directive or similar).
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
static ErrorSuccess success()
Create a success value.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
unsigned readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Implements a dense probed hash-table based set with some number of buckets stored inline...
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
unsigned skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
A (clang) module that has been imported by the compile unit.
Generic tagged DWARF-like metadata node.
static void clear(coro::Shape &Shape)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Type array for a subprogram.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
MDString * getRawIdentifier() const
void emplace_back(ArgTypes &&... Args)
bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true if the block has an error...
LLVM_NODISCARD bool empty() const
DISPFlags
Debug info subprogram flags.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator)
Build a DICompositeType with the given ODR identifier.
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Lightweight error class with error context and mandatory checking.
#define LLVM_LIKELY(EXPR)
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
print Print MemDeps of function
iterator_range< global_iterator > globals()
StringRef - Represent a constant reference to a string, i.e.
If this flag is used, the advance() method does not automatically pop the block scope when the end of...
This represents a position within a bitstream.
Function Alias Analysis false
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Basic type, like 'int' or 'float'.