62 "Allow incomplete IR on a best effort basis (references to unknown "
63 "metadata will be dropped)"));
86 "Can't read textual IR with a Context that discards named Values");
89 if (parseTargetDefinitions(DataLayoutCallback))
99 restoreParsingState(Slots);
103 if (parseType(Ty) || parseConstantValue(Ty,
C))
106 return error(Lex.
getLoc(),
"expected end of string");
112 restoreParsingState(Slots);
121 Read =
End.getPointer() - Start.getPointer();
126void LLParser::restoreParsingState(
const SlotMapping *Slots) {
133 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
134 for (
const auto &
I : Slots->
Types)
135 NumberedTypes.insert(
136 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
141 if (!isa<DbgInfoIntrinsic>(II) &&
142 II->
getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
147 if (
auto *MV = dyn_cast<MetadataAsValue>(V))
148 if (
auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
149 if (MD->isTemporary())
163void LLParser::dropUnknownMetadataReferences() {
164 auto Pred = [](
unsigned MDKind,
MDNode *
Node) {
return Node->isTemporary(); };
166 F.eraseMetadataIf(Pred);
168 I.eraseMetadataIf(Pred);
170 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
176 GV.eraseMetadataIf(Pred);
181 if (
Info.first->getNumTemporaryUses() == 1) {
182 NumberedMetadata.erase(
ID);
183 ForwardRefMDNodes.erase(
ID);
196 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
197 "Mixed debug intrinsics/records seen without a parsing error?");
202 M->setNewDbgInfoFormatFlag(SeenNewDbgInfoFormat);
206 for (
const auto &RAG : ForwardRefAttrGroups) {
208 const std::vector<unsigned> &
Attrs = RAG.second;
211 for (
const auto &Attr : Attrs) {
212 auto R = NumberedAttrBuilders.find(Attr);
213 if (R != NumberedAttrBuilders.end())
217 if (
Function *Fn = dyn_cast<Function>(V)) {
227 Fn->setAlignment(*
A);
232 Fn->setAttributes(AS);
233 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
239 CI->setAttributes(AS);
240 }
else if (
InvokeInst *II = dyn_cast<InvokeInst>(V)) {
246 II->setAttributes(AS);
247 }
else if (
CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
253 CBI->setAttributes(AS);
254 }
else if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
265 if (!ForwardRefBlockAddresses.empty())
266 return error(ForwardRefBlockAddresses.begin()->first.Loc,
267 "expected function name in blockaddress");
269 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
273 GV =
M->getNamedValue(GVRef.
StrVal);
275 GV = NumberedVals.get(GVRef.
UIntVal);
280 "' referenced by dso_local_equivalent");
284 "expected a function, alias to function, or ifunc "
285 "in dso_local_equivalent");
288 FwdRef->replaceAllUsesWith(Equiv);
289 FwdRef->eraseFromParent();
296 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
297 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
300 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
301 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
304 ForwardRefDSOLocalEquivalentIDs.clear();
305 ForwardRefDSOLocalEquivalentNames.clear();
307 for (
const auto &NT : NumberedTypes)
308 if (
NT.second.second.isValid())
310 "use of undefined type '%" +
Twine(
NT.first) +
"'");
312 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
313 NamedTypes.begin(), E = NamedTypes.end();
I != E; ++
I)
314 if (
I->second.second.isValid())
315 return error(
I->second.second,
316 "use of undefined type named '" +
I->getKey() +
"'");
318 if (!ForwardRefComdats.empty())
319 return error(ForwardRefComdats.begin()->second,
320 "use of undefined comdat '$" +
321 ForwardRefComdats.begin()->first +
"'");
338 auto *CB = dyn_cast<CallBase>(
U.getUser());
339 if (!CB || !CB->isCallee(&U))
340 return error(
Info.second,
"intrinsic can only be used as callee");
345 return error(
Info.second,
"invalid intrinsic signature");
350 Info.first->eraseFromParent();
351 ForwardRefVals.erase(
Name);
362 for (
Use &U :
V->uses()) {
363 auto *CB = dyn_cast<CallBase>(
U.getUser());
364 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
366 FTy = CB->getFunctionType();
374 Type *Ty = GetCommonFunctionType(
Info.first);
379 if (
auto *FTy = dyn_cast<FunctionType>(Ty))
385 Info.first->replaceAllUsesWith(GV);
386 Info.first->eraseFromParent();
387 ForwardRefVals.erase(
Name);
390 if (!ForwardRefVals.empty())
391 return error(ForwardRefVals.begin()->second.second,
392 "use of undefined value '@" + ForwardRefVals.begin()->first +
395 if (!ForwardRefValIDs.empty())
396 return error(ForwardRefValIDs.begin()->second.second,
397 "use of undefined value '@" +
398 Twine(ForwardRefValIDs.begin()->first) +
"'");
401 dropUnknownMetadataReferences();
403 if (!ForwardRefMDNodes.empty())
404 return error(ForwardRefMDNodes.begin()->second.second,
405 "use of undefined metadata '!" +
406 Twine(ForwardRefMDNodes.begin()->first) +
"'");
409 for (
auto &
N : NumberedMetadata) {
410 if (
N.second && !
N.second->isResolved())
411 N.second->resolveCycles();
414 for (
auto *Inst : InstsWithTBAATag) {
415 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
418 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
421 if (MD != UpgradedMD)
422 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
431 if (UpgradeDebugInfo)
447 for (
const auto &
I : NamedTypes)
448 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
449 for (
const auto &
I : NumberedTypes)
450 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
456bool LLParser::validateEndOfIndex() {
460 if (!ForwardRefValueInfos.empty())
461 return error(ForwardRefValueInfos.begin()->second.front().second,
462 "use of undefined summary '^" +
463 Twine(ForwardRefValueInfos.begin()->first) +
"'");
465 if (!ForwardRefAliasees.empty())
466 return error(ForwardRefAliasees.begin()->second.front().second,
467 "use of undefined summary '^" +
468 Twine(ForwardRefAliasees.begin()->first) +
"'");
470 if (!ForwardRefTypeIds.empty())
471 return error(ForwardRefTypeIds.begin()->second.front().second,
472 "use of undefined type id summary '^" +
473 Twine(ForwardRefTypeIds.begin()->first) +
"'");
487 std::string TentativeDLStr =
M->getDataLayoutStr();
494 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
498 if (parseSourceFileName())
507 if (
auto LayoutOverride =
508 DataLayoutCallback(
M->getTargetTriple(), TentativeDLStr)) {
509 TentativeDLStr = *LayoutOverride;
515 M->setDataLayout(MaybeDL.
get());
519bool LLParser::parseTopLevelEntities() {
527 if (parseSummaryEntry())
531 if (parseSourceFileName())
543 return tokError(
"expected top-level entity");
554 if (parseModuleAsm())
558 if (parseUnnamedType())
562 if (parseNamedType())
566 if (parseUnnamedGlobal())
570 if (parseNamedGlobal())
575 if (parseStandaloneMetadata())
579 if (parseSummaryEntry())
583 if (parseNamedMetadata())
587 if (parseUnnamedAttrGrp())
591 if (parseUseListOrder())
595 if (parseUseListOrderBB())
604bool LLParser::parseModuleAsm() {
610 parseStringConstant(AsmStr))
613 M->appendModuleInlineAsm(AsmStr);
620bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
626 return tokError(
"unknown target property");
629 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
630 parseStringConstant(Str))
632 M->setTargetTriple(Str);
636 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
639 if (parseStringConstant(TentativeDLStr))
647bool LLParser::parseSourceFileName() {
650 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
651 parseStringConstant(SourceFileName))
654 M->setSourceFileName(SourceFileName);
660bool LLParser::parseUnnamedType() {
665 if (parseToken(
lltok::equal,
"expected '=' after name") ||
670 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
673 if (!isa<StructType>(Result)) {
674 std::pair<Type*, LocTy> &Entry = NumberedTypes[
TypeID];
676 return error(TypeLoc,
"non-struct types may not be recursive");
678 Entry.second =
SMLoc();
686bool LLParser::parseNamedType() {
691 if (parseToken(
lltok::equal,
"expected '=' after name") ||
696 if (parseStructDefinition(NameLoc,
Name, NamedTypes[
Name], Result))
699 if (!isa<StructType>(Result)) {
700 std::pair<Type*, LocTy> &Entry = NamedTypes[
Name];
702 return error(NameLoc,
"non-struct types may not be recursive");
704 Entry.second =
SMLoc();
712bool LLParser::parseDeclare() {
716 std::vector<std::pair<unsigned, MDNode *>> MDs;
720 if (parseMetadataAttachment(MDK,
N))
722 MDs.push_back({MDK,
N});
726 unsigned FunctionNumber = -1;
728 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
731 F->addMetadata(MD.first, *MD.second);
737bool LLParser::parseDefine() {
742 unsigned FunctionNumber = -1;
744 return parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
745 parseOptionalFunctionMetadata(*
F) ||
746 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
752bool LLParser::parseGlobalType(
bool &IsConstant) {
759 return tokError(
"expected 'global' or 'constant'");
765bool LLParser::parseOptionalUnnamedAddr(
786bool LLParser::parseUnnamedGlobal() {
794 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(), VarID))
798 if (parseToken(
lltok::equal,
"expected '=' after name"))
801 VarID = NumberedVals.getNext();
805 unsigned Linkage, Visibility, DLLStorageClass;
809 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
811 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
816 return parseGlobal(
Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
817 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
820 return parseAliasOrIFunc(
Name, VarID, NameLoc, Linkage, Visibility,
821 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
830bool LLParser::parseNamedGlobal() {
837 unsigned Linkage, Visibility, DLLStorageClass;
841 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
842 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
844 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
849 return parseGlobal(
Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
850 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
853 return parseAliasOrIFunc(
Name, -1, NameLoc, Linkage, Visibility,
854 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
858bool LLParser::parseComdat() {
868 return tokError(
"expected comdat type");
873 return tokError(
"unknown selection kind");
895 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(
Name))
896 return error(NameLoc,
"redefinition of comdat '$" +
Name +
"'");
899 if (
I != ComdatSymTab.
end())
902 C =
M->getOrInsertComdat(
Name);
903 C->setSelectionKind(SK);
910bool LLParser::parseMDString(
MDString *&Result) {
912 if (parseStringConstant(Str))
920bool LLParser::parseMDNodeID(
MDNode *&Result) {
924 if (parseUInt32(MID))
928 if (NumberedMetadata.count(MID)) {
929 Result = NumberedMetadata[MID];
934 auto &FwdRef = ForwardRefMDNodes[MID];
937 Result = FwdRef.first.get();
938 NumberedMetadata[MID].reset(Result);
944bool LLParser::parseNamedMetadata() {
963 if (parseDIExpression(
N,
false))
969 return tokError(
"found DIArgList outside of function");
977 return parseToken(
lltok::rbrace,
"expected end of metadata node");
982bool LLParser::parseStandaloneMetadata() {
985 unsigned MetadataID = 0;
988 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
993 return tokError(
"unexpected type in metadata definition");
997 if (parseSpecializedMDNode(
Init, IsDistinct))
1000 parseMDTuple(
Init, IsDistinct))
1004 auto FI = ForwardRefMDNodes.find(MetadataID);
1005 if (FI != ForwardRefMDNodes.end()) {
1006 auto *ToReplace = FI->second.first.get();
1009 if (isa<DIAssignID>(
Init)) {
1010 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1011 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1012 "Inst unexpectedly already has DIAssignID attachment");
1013 Inst->setMetadata(LLVMContext::MD_DIAssignID,
Init);
1017 ToReplace->replaceAllUsesWith(
Init);
1018 ForwardRefMDNodes.erase(FI);
1020 assert(NumberedMetadata[MetadataID] ==
Init &&
"Tracking VH didn't work");
1022 if (NumberedMetadata.count(MetadataID))
1023 return tokError(
"Metadata id is already used");
1024 NumberedMetadata[MetadataID].reset(
Init);
1031bool LLParser::skipModuleSummaryEntry() {
1041 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1042 "start of summary entry");
1044 return parseSummaryIndexFlags();
1046 return parseBlockCount();
1048 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1049 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1053 unsigned NumOpenParen = 1;
1063 return tokError(
"found end of file while parsing summary entry");
1069 }
while (NumOpenParen > 0);
1075bool LLParser::parseSummaryEntry() {
1089 return skipModuleSummaryEntry();
1091 bool result =
false;
1094 result = parseGVEntry(SummaryID);
1097 result = parseModuleEntry(SummaryID);
1100 result = parseTypeIdEntry(SummaryID);
1103 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1106 result = parseSummaryIndexFlags();
1109 result = parseBlockCount();
1112 result =
error(Lex.
getLoc(),
"unexpected summary kind");
1149bool LLParser::parseAliasOrIFunc(
const std::string &
Name,
unsigned NameID,
1150 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1151 unsigned DLLStorageClass,
bool DSOLocal,
1166 return error(NameLoc,
"invalid linkage type for alias");
1169 return error(NameLoc,
1170 "symbol with local linkage must have default visibility");
1173 return error(NameLoc,
1174 "symbol with local linkage cannot have a DLL storage class");
1178 if (parseType(Ty) ||
1179 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1188 if (parseGlobalTypeAndValue(Aliasee))
1193 if (parseValID(
ID,
nullptr))
1196 return error(AliaseeLoc,
"invalid aliasee");
1197 Aliasee =
ID.ConstantVal;
1201 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1203 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1204 unsigned AddrSpace = PTy->getAddressSpace();
1210 if (!
Name.empty()) {
1211 auto I = ForwardRefVals.find(
Name);
1212 if (
I != ForwardRefVals.end()) {
1213 GVal =
I->second.first;
1214 ForwardRefVals.erase(
Name);
1215 }
else if (
M->getNamedValue(
Name)) {
1216 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1219 auto I = ForwardRefValIDs.find(NameID);
1220 if (
I != ForwardRefValIDs.end()) {
1221 GVal =
I->second.first;
1222 ForwardRefValIDs.erase(
I);
1227 std::unique_ptr<GlobalAlias> GA;
1228 std::unique_ptr<GlobalIFunc> GI;
1258 return tokError(
"unknown alias or ifunc property!");
1263 NumberedVals.add(NameID, GV);
1270 "forward reference and definition of alias have different types");
1280 M->insertAlias(GA.release());
1282 M->insertIFunc(GI.release());
1292 case lltok::kw_sanitize_memtag:
1308 Meta.NoAddress =
true;
1311 Meta.NoHWAddress =
true;
1313 case lltok::kw_sanitize_memtag:
1317 Meta.IsDynInit =
true;
1320 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1340bool LLParser::parseGlobal(
const std::string &
Name,
unsigned NameID,
1341 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1342 unsigned Visibility,
unsigned DLLStorageClass,
1346 return error(NameLoc,
1347 "symbol with local linkage must have default visibility");
1350 return error(NameLoc,
1351 "symbol with local linkage cannot have a DLL storage class");
1355 LocTy IsExternallyInitializedLoc;
1359 if (parseOptionalAddrSpace(AddrSpace) ||
1361 IsExternallyInitialized,
1362 &IsExternallyInitializedLoc) ||
1363 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1372 if (parseGlobalValue(Ty,
Init))
1377 return error(TyLoc,
"invalid type for global variable");
1382 if (!
Name.empty()) {
1383 auto I = ForwardRefVals.find(
Name);
1384 if (
I != ForwardRefVals.end()) {
1385 GVal =
I->second.first;
1386 ForwardRefVals.erase(
I);
1387 }
else if (
M->getNamedValue(
Name)) {
1388 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1393 if (NameID == (
unsigned)-1)
1394 NameID = NumberedVals.getNext();
1396 auto I = ForwardRefValIDs.find(NameID);
1397 if (
I != ForwardRefValIDs.end()) {
1398 GVal =
I->second.first;
1399 ForwardRefValIDs.erase(
I);
1408 NumberedVals.add(NameID, GV);
1426 "forward reference and definition of global have different types");
1446 }
else if (Lex.
getKind() == lltok::kw_align) {
1448 if (parseOptionalAlignment(Alignment))
1454 if (parseOptionalCodeModel(CodeModel))
1458 if (parseGlobalObjectMetadataAttachment(*GV))
1461 if (parseSanitizer(GV))
1465 if (parseOptionalComdat(
Name,
C))
1470 return tokError(
"unknown global variable property!");
1476 std::vector<unsigned> FwdRefAttrGrps;
1477 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1479 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1481 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1489bool LLParser::parseUnnamedAttrGrp() {
1495 return tokError(
"expected attribute group id");
1498 std::vector<unsigned> unused;
1506 auto R = NumberedAttrBuilders.find(VarID);
1507 if (R == NumberedAttrBuilders.end())
1508 R = NumberedAttrBuilders.emplace(VarID,
AttrBuilder(
M->getContext())).first;
1510 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1511 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1514 if (!
R->second.hasAttributes())
1515 return error(AttrGrpLoc,
"attribute group has no attributes");
1522#define GET_ATTR_NAMES
1523#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1524 case lltok::kw_##DISPLAY_NAME: \
1525 return Attribute::ENUM_NAME;
1526#include "llvm/IR/Attributes.inc"
1535 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1538 case Attribute::Alignment: {
1547 if (parseOptionalAlignment(Alignment,
true))
1550 B.addAlignmentAttr(Alignment);
1553 case Attribute::StackAlignment: {
1558 parseUInt32(Alignment))
1561 if (parseOptionalStackAlignment(Alignment))
1564 B.addStackAlignmentAttr(Alignment);
1567 case Attribute::AllocSize: {
1568 unsigned ElemSizeArg;
1569 std::optional<unsigned> NumElemsArg;
1570 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1572 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1575 case Attribute::VScaleRange: {
1576 unsigned MinValue, MaxValue;
1577 if (parseVScaleRangeArguments(MinValue, MaxValue))
1579 B.addVScaleRangeAttr(MinValue,
1580 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1583 case Attribute::Dereferenceable: {
1585 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1587 B.addDereferenceableAttr(Bytes);
1590 case Attribute::DereferenceableOrNull: {
1592 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1594 B.addDereferenceableOrNullAttr(Bytes);
1597 case Attribute::UWTable: {
1599 if (parseOptionalUWTableKind(Kind))
1601 B.addUWTableAttr(Kind);
1604 case Attribute::AllocKind: {
1606 if (parseAllocKind(Kind))
1608 B.addAllocKindAttr(Kind);
1611 case Attribute::Memory: {
1612 std::optional<MemoryEffects> ME = parseMemoryAttr();
1615 B.addMemoryAttr(*ME);
1618 case Attribute::NoFPClass: {
1621 B.addNoFPClassAttr(NoFPClass);
1627 case Attribute::Range:
1628 return parseRangeAttr(
B);
1630 B.addAttribute(Attr);
1638 case lltok::kw_readnone:
1641 case lltok::kw_readonly:
1644 case lltok::kw_writeonly:
1663bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1664 std::vector<unsigned> &FwdRefAttrGrps,
1665 bool InAttrGrp, LocTy &BuiltinLoc) {
1666 bool HaveError =
false;
1677 if (parseStringAttribute(
B))
1689 "cannot have an attribute group reference in an attribute group");
1699 if (Token == lltok::kw_builtin)
1711 return error(Lex.
getLoc(),
"unterminated attribute group");
1714 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1721 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1725 B.addMemoryAttr(ME);
1739 PTy->getAddressSpace());
1748 error(Loc,
"'" +
Name +
"' is not a basic block");
1750 error(Loc,
"'" +
Name +
"' defined with type '" +
1763 error(Loc,
"global variable reference must have pointer type");
1769 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1774 auto I = ForwardRefVals.find(
Name);
1775 if (
I != ForwardRefVals.end())
1776 Val =
I->second.first;
1781 return cast_or_null<GlobalValue>(
1782 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1786 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1793 error(Loc,
"global variable reference must have pointer type");
1802 auto I = ForwardRefValIDs.find(
ID);
1803 if (
I != ForwardRefValIDs.end())
1804 Val =
I->second.first;
1809 return cast_or_null<GlobalValue>(
1810 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1814 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1822Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1826 if (
I != ComdatSymTab.
end())
1831 ForwardRefComdats[
Name] = Loc;
1841bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1843 return tokError(ErrMsg);
1850bool LLParser::parseStringConstant(std::string &Result) {
1852 return tokError(
"expected string constant");
1860bool LLParser::parseUInt32(
uint32_t &Val) {
1862 return tokError(
"expected integer");
1864 if (Val64 !=
unsigned(Val64))
1865 return tokError(
"expected 32-bit integer (too large)");
1873bool LLParser::parseUInt64(
uint64_t &Val) {
1875 return tokError(
"expected integer");
1888 return tokError(
"expected localdynamic, initialexec or localexec");
1916 return parseTLSModel(TLM) ||
1917 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1925bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1926 AddrSpace = DefaultAS;
1930 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1933 if (AddrSpaceStr ==
"A") {
1934 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1935 }
else if (AddrSpaceStr ==
"G") {
1936 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1937 }
else if (AddrSpaceStr ==
"P") {
1938 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1940 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1946 return tokError(
"expected integer or string constant");
1948 if (parseUInt32(AddrSpace))
1950 if (!isUInt<24>(AddrSpace))
1951 return error(Loc,
"invalid address space, must be a 24-bit integer");
1955 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1956 ParseAddrspaceValue(AddrSpace) ||
1967 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1969 B.addAttribute(Attr, Val);
1974bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1975 bool HaveError =
false;
1982 if (parseStringAttribute(
B))
1992 if (parseEnumAttribute(Attr,
B,
false))
1996 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
1998 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2046bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2047 unsigned &Visibility,
2048 unsigned &DLLStorageClass,
bool &DSOLocal) {
2052 parseOptionalDSOLocal(DSOLocal);
2053 parseOptionalVisibility(Visibility);
2054 parseOptionalDLLStorageClass(DLLStorageClass);
2057 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2063void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2085void LLParser::parseOptionalVisibility(
unsigned &Res) {
2103bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2107 return tokError(
"unknown import kind. Expect definition or declaration.");
2122void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2191bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2264 return parseUInt32(
CC);
2274bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2281 return parseMDNode(MD);
2286bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2289 return tokError(
"expected metadata after comma");
2293 if (parseMetadataAttachment(MDK,
N))
2296 if (MDK == LLVMContext::MD_DIAssignID)
2297 TempDIAssignIDAttachments[
N].push_back(&Inst);
2301 if (MDK == LLVMContext::MD_tbaa)
2302 InstsWithTBAATag.push_back(&Inst);
2311bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2314 if (parseMetadataAttachment(MDK,
N))
2323bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2325 if (parseGlobalObjectMetadataAttachment(
F))
2333bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2334 Alignment = std::nullopt;
2335 if (!EatIfPresent(lltok::kw_align))
2341 bool HaveParens =
false;
2347 if (parseUInt64(
Value))
2351 return error(ParenLoc,
"expected ')'");
2354 return error(AlignLoc,
"alignment is not a power of two");
2356 return error(AlignLoc,
"huge alignments are not supported yet");
2367 auto ErrMsg =
"expected global code model string";
2368 if (StrVal ==
"tiny")
2370 else if (StrVal ==
"small")
2372 else if (StrVal ==
"kernel")
2374 else if (StrVal ==
"medium")
2376 else if (StrVal ==
"large")
2379 return tokError(ErrMsg);
2390bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2392 assert((AttrKind == lltok::kw_dereferenceable ||
2393 AttrKind == lltok::kw_dereferenceable_or_null) &&
2397 if (!EatIfPresent(AttrKind))
2401 return error(ParenLoc,
"expected '('");
2403 if (parseUInt64(Bytes))
2407 return error(ParenLoc,
"expected ')'");
2409 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2413bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2424 return error(KindLoc,
"expected unwind table kind");
2433 return error(ParenLoc,
"expected '('");
2436 if (parseStringConstant(Arg))
2437 return error(KindLoc,
"expected allockind value");
2441 }
else if (
A ==
"realloc") {
2443 }
else if (
A ==
"free") {
2445 }
else if (
A ==
"uninitialized") {
2447 }
else if (
A ==
"zeroed") {
2449 }
else if (
A ==
"aligned") {
2452 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2457 return error(ParenLoc,
"expected ')'");
2459 return error(KindLoc,
"expected allockind value");
2470 return std::nullopt;
2485 return std::nullopt;
2489std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2499 tokError(
"expected '('");
2500 return std::nullopt;
2503 bool SeenLoc =
false;
2509 tokError(
"expected ':' after location");
2510 return std::nullopt;
2517 tokError(
"expected memory location (argmem, inaccessiblemem) "
2518 "or access kind (none, read, write, readwrite)");
2520 tokError(
"expected access kind (none, read, write, readwrite)");
2521 return std::nullopt;
2530 tokError(
"default access kind must be specified first");
2531 return std::nullopt;
2540 tokError(
"unterminated memory attribute");
2541 return std::nullopt;
2583unsigned LLParser::parseNoFPClassAttr() {
2588 tokError(
"expected '('");
2595 if (TestMask != 0) {
2599 !parseUInt64(
Value)) {
2601 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2612 error(Lex.
getLoc(),
"expected nofpclass test mask");
2630bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2631 bool &AteExtraComma) {
2632 AteExtraComma =
false;
2636 AteExtraComma =
true;
2640 if (Lex.
getKind() != lltok::kw_align)
2641 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2643 if (parseOptionalAlignment(Alignment))
2656bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2657 bool &AteExtraComma) {
2658 AteExtraComma =
false;
2662 AteExtraComma =
true;
2668 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2670 if (parseOptionalAddrSpace(AddrSpace))
2677bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2678 std::optional<unsigned> &HowManyArg) {
2681 auto StartParen = Lex.
getLoc();
2683 return error(StartParen,
"expected '('");
2685 if (parseUInt32(BaseSizeArg))
2689 auto HowManyAt = Lex.
getLoc();
2691 if (parseUInt32(HowMany))
2693 if (HowMany == BaseSizeArg)
2694 return error(HowManyAt,
2695 "'allocsize' indices can't refer to the same parameter");
2696 HowManyArg = HowMany;
2698 HowManyArg = std::nullopt;
2700 auto EndParen = Lex.
getLoc();
2702 return error(EndParen,
"expected ')'");
2706bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2707 unsigned &MaxValue) {
2710 auto StartParen = Lex.
getLoc();
2712 return error(StartParen,
"expected '('");
2714 if (parseUInt32(MinValue))
2718 if (parseUInt32(MaxValue))
2721 MaxValue = MinValue;
2723 auto EndParen = Lex.
getLoc();
2725 return error(EndParen,
"expected ')'");
2734bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2739 return parseScope(SSID) || parseOrdering(Ordering);
2749 auto StartParenAt = Lex.
getLoc();
2751 return error(StartParenAt,
"Expected '(' in syncscope");
2754 auto SSNAt = Lex.
getLoc();
2755 if (parseStringConstant(SSN))
2756 return error(SSNAt,
"Expected synchronization scope name");
2758 auto EndParenAt = Lex.
getLoc();
2760 return error(EndParenAt,
"Expected ')' in syncscope");
2775 return tokError(
"Expected ordering on atomic instruction");
2794bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2796 if (!EatIfPresent(lltok::kw_alignstack))
2800 return error(ParenLoc,
"expected '('");
2802 if (parseUInt32(Alignment))
2806 return error(ParenLoc,
"expected ')'");
2808 return error(AlignLoc,
"stack alignment is not a power of two");
2822 bool &AteExtraComma) {
2823 AteExtraComma =
false;
2826 return tokError(
"expected ',' as start of index list");
2830 if (Indices.
empty())
2831 return tokError(
"expected index");
2832 AteExtraComma =
true;
2836 if (parseUInt32(
Idx))
2849bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2853 return tokError(Msg);
2862 if (
Result->isPointerTy()) {
2864 if (parseOptionalAddrSpace(AddrSpace))
2870 return tokError(
"ptr* is invalid - use ptr instead");
2881 if (parseTargetExtType(Result))
2887 if (parseAnonStructType(Result,
false))
2893 if (parseArrayVectorType(Result,
false))
2900 if (parseAnonStructType(Result,
true) ||
2901 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2903 }
else if (parseArrayVectorType(Result,
true))
2908 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.
getStrVal()];
2914 Entry.second = Lex.
getLoc();
2923 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.
getUIntVal()];
2929 Entry.second = Lex.
getLoc();
2942 if (!AllowVoid &&
Result->isVoidTy())
2943 return error(TypeLoc,
"void type only allowed for function results");
2949 return tokError(
"basic block pointers are invalid");
2951 return tokError(
"pointers to void are invalid - use i8* instead");
2953 return tokError(
"pointer to this type is invalid");
2961 return tokError(
"basic block pointers are invalid");
2963 return tokError(
"pointers to void are invalid; use i8* instead");
2965 return tokError(
"pointer to this type is invalid");
2967 if (parseOptionalAddrSpace(AddrSpace) ||
2968 parseToken(
lltok::star,
"expected '*' in address space"))
2977 if (parseFunctionType(Result))
2990 PerFunctionState &PFS,
bool IsMustTailCall,
2991 bool InVarArgsFunc) {
2997 if (!ArgList.
empty() &&
2998 parseToken(
lltok::comma,
"expected ',' in argument list"))
3003 const char *
Msg =
"unexpected ellipsis in argument list for ";
3004 if (!IsMustTailCall)
3005 return tokError(
Twine(Msg) +
"non-musttail call");
3007 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
3009 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3014 Type *ArgTy =
nullptr;
3016 if (parseType(ArgTy, ArgLoc))
3022 if (parseMetadataAsValue(V, PFS))
3026 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3033 if (IsMustTailCall && InVarArgsFunc)
3034 return tokError(
"expected '...' at end of argument list for musttail call "
3035 "in varargs function");
3046 if (!EatIfPresent(AttrToken))
3055 B.addTypeAttr(AttrKind, Ty);
3071 return tokError(
"expected integer");
3074 "integer is too large for the bit width of specified type");
3080 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3083 return error(TyLoc,
"the range must have integer type!");
3091 return tokError(
"the range should not represent the full or empty set!");
3109bool LLParser::parseOptionalOperandBundles(
3117 if (!BundleList.
empty() &&
3118 parseToken(
lltok::comma,
"expected ',' in input list"))
3122 if (parseStringConstant(
Tag))
3125 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3128 std::vector<Value *> Inputs;
3131 if (!Inputs.empty() &&
3132 parseToken(
lltok::comma,
"expected ',' in input list"))
3136 Value *Input =
nullptr;
3137 if (parseType(Ty) || parseValue(Ty, Input, PFS))
3139 Inputs.push_back(Input);
3147 if (BundleList.
empty())
3148 return error(BeginLoc,
"operand bundle set must not be empty");
3155 unsigned NextID,
unsigned ID)
const {
3157 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3158 Twine(NextID) +
"' or greater");
3175 unsigned CurValID = 0;
3190 Type *ArgTy =
nullptr;
3192 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3196 return error(TypeLoc,
"argument can not have void type");
3206 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3213 CurValID = ArgID + 1;
3217 return error(TypeLoc,
"invalid type for function argument");
3225 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3230bool LLParser::parseFunctionType(
Type *&Result) {
3234 return tokError(
"invalid function return type");
3239 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3243 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
3244 if (!ArgList[i].
Name.empty())
3245 return error(ArgList[i].Loc,
"argument name invalid in function type");
3246 if (ArgList[i].
Attrs.hasAttributes())
3247 return error(ArgList[i].Loc,
3248 "argument attributes invalid in function type");
3252 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
3261bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3263 if (parseStructBody(Elts))
3272 std::pair<Type *, LocTy> &Entry,
3275 if (Entry.first && !Entry.second.isValid())
3276 return error(TypeLoc,
"redefinition of type");
3282 Entry.second =
SMLoc();
3287 ResultTy = Entry.first;
3299 return error(TypeLoc,
"forward references to non-struct type");
3303 return parseArrayVectorType(ResultTy,
true);
3304 return parseType(ResultTy);
3308 Entry.second =
SMLoc();
3314 StructType *STy = cast<StructType>(Entry.first);
3317 if (parseStructBody(Body) ||
3318 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3347 return error(EltTyLoc,
"invalid element type for struct");
3355 return error(EltTyLoc,
"invalid element type for struct");
3360 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3369bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3370 bool Scalable =
false;
3374 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3382 return tokError(
"expected number in address space");
3388 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3392 Type *EltTy =
nullptr;
3393 if (parseType(EltTy))
3397 "expected end of sequential type"))
3402 return error(SizeLoc,
"zero element vector is illegal");
3404 return error(SizeLoc,
"size too large for vector");
3406 return error(TypeLoc,
"invalid vector element type");
3410 return error(TypeLoc,
"invalid array element type");
3427bool LLParser::parseTargetExtType(
Type *&Result) {
3432 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3433 parseStringConstant(TypeName))
3441 bool SeenInt =
false;
3448 if (parseUInt32(IntVal))
3451 }
else if (SeenInt) {
3454 return tokError(
"expected uint32 param");
3457 if (parseType(TypeParam,
true))
3463 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3477 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3480 auto It = UnnamedArgNums.
begin();
3483 unsigned ArgNum = *It++;
3484 NumberedVals.add(ArgNum, &
A);
3489LLParser::PerFunctionState::~PerFunctionState() {
3492 for (
const auto &
P : ForwardRefVals) {
3493 if (isa<BasicBlock>(
P.second.first))
3495 P.second.first->replaceAllUsesWith(
3497 P.second.first->deleteValue();
3500 for (
const auto &
P : ForwardRefValIDs) {
3501 if (isa<BasicBlock>(
P.second.first))
3503 P.second.first->replaceAllUsesWith(
3505 P.second.first->deleteValue();
3509bool LLParser::PerFunctionState::finishFunction() {
3510 if (!ForwardRefVals.empty())
3511 return P.error(ForwardRefVals.begin()->second.second,
3512 "use of undefined value '%" + ForwardRefVals.begin()->first +
3514 if (!ForwardRefValIDs.empty())
3515 return P.error(ForwardRefValIDs.begin()->second.second,
3516 "use of undefined value '%" +
3517 Twine(ForwardRefValIDs.begin()->first) +
"'");
3524Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3527 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3532 auto I = ForwardRefVals.find(
Name);
3533 if (
I != ForwardRefVals.end())
3534 Val =
I->second.first;
3539 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3543 P.error(Loc,
"invalid use of a non-first-class type");
3555 P.error(Loc,
"name is too long which can result in name collisions, "
3556 "consider making the name shorter or "
3557 "increasing -non-global-value-max-name-size");
3561 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3565Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3567 Value *Val = NumberedVals.get(
ID);
3572 auto I = ForwardRefValIDs.find(
ID);
3573 if (
I != ForwardRefValIDs.end())
3574 Val =
I->second.first;
3579 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3582 P.error(Loc,
"invalid use of a non-first-class type");
3594 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3600bool LLParser::PerFunctionState::setInstName(
int NameID,
3601 const std::string &NameStr,
3605 if (NameID != -1 || !NameStr.empty())
3606 return P.error(NameLoc,
"instructions returning void cannot have a name");
3612 if (NameStr.empty()) {
3615 NameID = NumberedVals.getNext();
3617 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3621 auto FI = ForwardRefValIDs.find(NameID);
3622 if (FI != ForwardRefValIDs.end()) {
3625 return P.error(NameLoc,
"instruction forward referenced with type '" +
3629 Sentinel->replaceAllUsesWith(Inst);
3631 ForwardRefValIDs.erase(FI);
3634 NumberedVals.add(NameID, Inst);
3639 auto FI = ForwardRefVals.find(NameStr);
3640 if (FI != ForwardRefVals.end()) {
3643 return P.error(NameLoc,
"instruction forward referenced with type '" +
3647 Sentinel->replaceAllUsesWith(Inst);
3649 ForwardRefVals.erase(FI);
3655 if (Inst->
getName() != NameStr)
3656 return P.error(NameLoc,
"multiple definition of local value named '" +
3663BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3665 return dyn_cast_or_null<BasicBlock>(
3669BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3670 return dyn_cast_or_null<BasicBlock>(
3677BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3678 int NameID, LocTy Loc) {
3682 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3685 NameID = NumberedVals.getNext();
3687 BB = getBB(NameID, Loc);
3689 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3693 BB = getBB(
Name, Loc);
3695 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3706 ForwardRefValIDs.erase(NameID);
3707 NumberedVals.add(NameID, BB);
3710 ForwardRefVals.erase(
Name);
3727bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3731 return tokError(
"expected value token");
3774 if (parseGlobalValueVector(Elts) ||
3775 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3778 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3779 ID.UIntVal = Elts.
size();
3780 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3781 Elts.
size() *
sizeof(Elts[0]));
3793 if (parseGlobalValueVector(Elts) ||
3795 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3799 if (isPackedStruct) {
3800 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3801 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3802 Elts.
size() *
sizeof(Elts[0]));
3803 ID.UIntVal = Elts.
size();
3809 return error(
ID.Loc,
"constant vector must not be empty");
3811 if (!Elts[0]->
getType()->isIntegerTy() &&
3812 !Elts[0]->
getType()->isFloatingPointTy() &&
3816 "vector elements must have integer, pointer or floating point type");
3819 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3821 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3822 " is not of type '" +
3833 if (parseGlobalValueVector(Elts) ||
3845 if (!Elts[0]->
getType()->isFirstClassType())
3846 return error(FirstEltLoc,
"invalid array element type: " +
3852 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3854 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3855 " is not of type '" +
3875 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3878 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3881 parseStringConstant(
ID.StrVal) ||
3882 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3887 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
3898 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3899 parseValID(Fn, PFS) ||
3901 "expected comma in block address expression") ||
3902 parseValID(Label, PFS) ||
3903 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
3907 return error(Fn.
Loc,
"expected function name in blockaddress");
3909 return error(
Label.Loc,
"expected basic block name in blockaddress");
3914 GV = NumberedVals.get(Fn.
UIntVal);
3915 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3916 GV =
M->getNamedValue(Fn.
StrVal);
3921 if (!isa<Function>(GV))
3922 return error(Fn.
Loc,
"expected function name in blockaddress");
3923 F = cast<Function>(GV);
3924 if (
F->isDeclaration())
3925 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
3931 ForwardRefBlockAddresses.insert(std::make_pair(
3933 std::map<ValID, GlobalValue *>()))
3934 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
3943 "type of blockaddress must be a pointer and not '" +
3948 FwdDeclAS = PFS->getFunction().getAddressSpace();
3957 ID.ConstantVal = FwdRef;
3965 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
3967 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
3969 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
3971 return error(
Label.Loc,
"referenced value is not a basic block");
3974 return error(
Label.Loc,
"cannot take address of numeric label after "
3975 "the function is defined");
3976 BB = dyn_cast_or_null<BasicBlock>(
3977 F->getValueSymbolTable()->lookup(
Label.StrVal));
3979 return error(
Label.Loc,
"referenced value is not a basic block");
3993 if (parseValID(Fn, PFS))
3998 "expected global value name in dso_local_equivalent");
4003 GV = NumberedVals.get(Fn.
UIntVal);
4004 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4005 GV =
M->getNamedValue(Fn.
StrVal);
4011 ? ForwardRefDSOLocalEquivalentIDs
4012 : ForwardRefDSOLocalEquivalentNames;
4013 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn,
nullptr).first->second;
4020 ID.ConstantVal = FwdRef;
4026 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4027 "in dso_local_equivalent");
4038 if (parseValID(
ID, PFS))
4042 return error(
ID.Loc,
"expected global value name in no_cfi");
4054 Type *DestTy =
nullptr;
4057 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4058 parseGlobalTypeAndValue(SrcVal) ||
4059 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4060 parseType(DestTy) ||
4061 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4064 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4073 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4075 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4077 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4079 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4081 return error(
ID.Loc,
"urem constexprs are no longer supported");
4083 return error(
ID.Loc,
"srem constexprs are no longer supported");
4085 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4087 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4089 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4091 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4093 return error(
ID.Loc,
"frem constexprs are no longer supported");
4095 return error(
ID.Loc,
"and constexprs are no longer supported");
4097 return error(
ID.Loc,
"or constexprs are no longer supported");
4099 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4101 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4103 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4105 return error(
ID.Loc,
"select constexprs are no longer supported");
4107 return error(
ID.Loc,
"zext constexprs are no longer supported");
4109 return error(
ID.Loc,
"sext constexprs are no longer supported");
4111 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4113 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4115 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4117 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4119 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4121 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4127 if (parseCmpPredicate(PredVal, Opc) ||
4128 parseToken(
lltok::lparen,
"expected '(' in compare constantexpr") ||
4129 parseGlobalTypeAndValue(Val0) ||
4130 parseToken(
lltok::comma,
"expected comma in compare constantexpr") ||
4131 parseGlobalTypeAndValue(Val1) ||
4132 parseToken(
lltok::rparen,
"expected ')' in compare constantexpr"))
4136 return error(
ID.Loc,
"compare operands must have the same type");
4140 if (Opc == Instruction::FCmp) {
4142 return error(
ID.Loc,
"fcmp requires floating point operands");
4145 assert(Opc == Instruction::ICmp &&
"Unexpected opcode for CmpInst!");
4148 return error(
ID.Loc,
"icmp requires pointer or integer operands");
4166 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4167 Opc == Instruction::Mul || Opc == Instruction::Shl) {
4176 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4177 parseGlobalTypeAndValue(Val0) ||
4178 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4179 parseGlobalTypeAndValue(Val1) ||
4180 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4183 return error(
ID.Loc,
"operands of constexpr must have same type");
4187 "constexpr requires integer or integer vector operands");
4198 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4201 if (parseGlobalTypeAndValue(
C))
4203 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4217 bool InBounds =
false;
4218 bool HasInRange =
false;
4224 if (Opc == Instruction::GetElementPtr) {
4230 return tokError(
"expected integer");
4236 return tokError(
"expected integer");
4245 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4248 if (Opc == Instruction::GetElementPtr) {
4249 if (parseType(Ty) ||
4250 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4254 if (parseGlobalValueVector(Elts) ||
4258 if (Opc == Instruction::GetElementPtr) {
4259 if (Elts.
size() == 0 ||
4260 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4261 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4264 std::optional<ConstantRange>
InRange;
4266 unsigned IndexWidth =
4267 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4268 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4269 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4270 if (InRangeStart.
sge(InRangeEnd))
4271 return error(
ID.Loc,
"expected end to be larger than start");
4277 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4284 return error(
ID.Loc,
"getelementptr index must be an integer");
4285 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4286 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4287 if (GEPWidth && (ValNumEl != GEPWidth))
4290 "getelementptr vector index has a wrong number of elements");
4293 GEPWidth = ValNumEl;
4298 if (!Indices.empty() && !Ty->
isSized(&Visited))
4299 return error(
ID.Loc,
"base element of getelementptr must be sized");
4302 return error(
ID.Loc,
"invalid getelementptr indices");
4306 }
else if (Opc == Instruction::ShuffleVector) {
4307 if (Elts.
size() != 3)
4308 return error(
ID.Loc,
"expected three operands to shufflevector");
4310 return error(
ID.Loc,
"invalid operands to shufflevector");
4314 }
else if (Opc == Instruction::ExtractElement) {
4315 if (Elts.
size() != 2)
4316 return error(
ID.Loc,
"expected two operands to extractelement");
4318 return error(
ID.Loc,
"invalid extractelement operands");
4321 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4322 if (Elts.
size() != 3)
4323 return error(
ID.Loc,
"expected three operands to insertelement");
4325 return error(
ID.Loc,
"invalid insertelement operands");
4344 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4345 convertValIDToValue(Ty,
ID, V,
nullptr);
4346 if (V && !(
C = dyn_cast<Constant>(V)))
4347 return error(
ID.Loc,
"global values must be constants");
4351bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4353 return parseType(Ty) || parseGlobalValue(Ty, V);
4365 return tokError(
"expected comdat variable");
4368 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4371 if (GlobalName.
empty())
4372 return tokError(
"comdat cannot be unnamed");
4373 C = getComdat(std::string(GlobalName), KwLoc);
4396 if (parseGlobalTypeAndValue(
C))
4404bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4406 if (parseMDNodeVector(Elts))
4417bool LLParser::parseMDNode(
MDNode *&
N) {
4419 return parseSpecializedMDNode(
N);
4421 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4424bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4427 return parseMDTuple(
N);
4430 return parseMDNodeID(
N);
4436template <
class FieldTy>
struct MDFieldImpl {
4437 typedef MDFieldImpl ImplTy;
4441 void assign(FieldTy Val) {
4443 this->Val = std::move(Val);
4446 explicit MDFieldImpl(FieldTy
Default)
4454template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4455 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4466 void assign(FieldTypeA
A) {
4468 this->A = std::move(
A);
4472 void assign(FieldTypeB
B) {
4474 this->B = std::move(
B);
4478 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4480 WhatIs(IsInvalid) {}
4483struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4490struct LineField :
public MDUnsignedField {
4491 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4494struct ColumnField :
public MDUnsignedField {
4495 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4498struct DwarfTagField :
public MDUnsignedField {
4504struct DwarfMacinfoTypeField :
public MDUnsignedField {
4510struct DwarfAttEncodingField :
public MDUnsignedField {
4511 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4514struct DwarfVirtualityField :
public MDUnsignedField {
4518struct DwarfLangField :
public MDUnsignedField {
4522struct DwarfCCField :
public MDUnsignedField {
4523 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4526struct EmissionKindField :
public MDUnsignedField {
4527 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4530struct NameTableKindField :
public MDUnsignedField {
4531 NameTableKindField()
4534 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4537struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4538 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4541struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4542 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4545struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4546 MDAPSIntField() : ImplTy(
APSInt()) {}
4549struct MDSignedField :
public MDFieldImpl<int64_t> {
4553 MDSignedField(int64_t
Default = 0)
4555 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4559struct MDBoolField :
public MDFieldImpl<bool> {
4563struct MDField :
public MDFieldImpl<Metadata *> {
4566 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4569struct MDStringField :
public MDFieldImpl<MDString *> {
4571 MDStringField(
bool AllowEmpty =
true)
4572 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4575struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4579struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4583struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4584 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4585 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4587 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4588 bool AllowNull =
true)
4589 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4591 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4592 bool isMDField()
const {
return WhatIs == IsTypeB; }
4593 int64_t getMDSignedValue()
const {
4594 assert(isMDSignedField() &&
"Wrong field type");
4597 Metadata *getMDFieldValue()
const {
4598 assert(isMDField() &&
"Wrong field type");
4610 return tokError(
"expected integer");
4619 MDUnsignedField &Result) {
4621 return tokError(
"expected unsigned integer");
4624 if (U.ugt(Result.Max))
4625 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4627 Result.assign(U.getZExtValue());
4628 assert(Result.Val <= Result.Max &&
"Expected value in range");
4635 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4639 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4645 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4648 return tokError(
"expected DWARF tag");
4652 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4653 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4662 DwarfMacinfoTypeField &Result) {
4664 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4667 return tokError(
"expected DWARF macinfo type");
4671 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4673 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4675 Result.assign(Macinfo);
4682 DwarfVirtualityField &Result) {
4684 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4687 return tokError(
"expected DWARF virtuality code");
4691 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4693 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4694 Result.assign(Virtuality);
4702 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4705 return tokError(
"expected DWARF language");
4709 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4711 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4712 Result.assign(Lang);
4720 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4723 return tokError(
"expected DWARF calling convention");
4727 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4729 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4737 EmissionKindField &Result) {
4739 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4742 return tokError(
"expected emission kind");
4746 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4748 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4749 Result.assign(*Kind);
4756 NameTableKindField &Result) {
4758 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4761 return tokError(
"expected nameTable kind");
4765 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4767 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4768 Result.assign((
unsigned)*Kind);
4775 DwarfAttEncodingField &Result) {
4777 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4780 return tokError(
"expected DWARF type attribute encoding");
4784 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
4786 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
4787 Result.assign(Encoding);
4803 bool Res = parseUInt32(TempVal);
4809 return tokError(
"expected debug info flag");
4813 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
4828 Result.assign(Combined);
4843 bool Res = parseUInt32(TempVal);
4849 return tokError(
"expected debug info flag");
4853 return tokError(
Twine(
"invalid subprogram debug info flag '") +
4868 Result.assign(Combined);
4875 return tokError(
"expected signed integer");
4879 return tokError(
"value for '" +
Name +
"' too small, limit is " +
4882 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4884 Result.assign(S.getExtValue());
4885 assert(Result.Val >= Result.Min &&
"Expected value in range");
4886 assert(Result.Val <= Result.Max &&
"Expected value in range");
4895 return tokError(
"expected 'true' or 'false'");
4897 Result.assign(
true);
4900 Result.assign(
false);
4910 if (!Result.AllowNull)
4911 return tokError(
"'" +
Name +
"' cannot be null");
4913 Result.assign(
nullptr);
4918 if (parseMetadata(MD,
nullptr))
4927 MDSignedOrMDField &Result) {
4930 MDSignedField Res = Result.A;
4931 if (!parseMDField(Loc,
Name, Res)) {
4939 MDField Res = Result.B;
4940 if (!parseMDField(Loc,
Name, Res)) {
4952 if (parseStringConstant(S))
4955 if (!Result.AllowEmpty && S.empty())
4956 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
4958 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
4965 if (parseMDNodeVector(MDs))
4968 Result.assign(std::move(MDs));
4974 ChecksumKindField &Result) {
4975 std::optional<DIFile::ChecksumKind> CSKind =
4979 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
4982 Result.assign(*CSKind);
4989template <
class ParserTy>
4990bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4993 return tokError(
"expected field label here");
5002template <
class ParserTy>
5003bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5010 if (parseMDFieldsImplBody(ParseField))
5013 ClosingLoc = Lex.
getLoc();
5017template <
class FieldTy>
5018bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5020 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
5024 return parseMDField(Loc,
Name, Result);
5027bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5030#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5031 if (Lex.getStrVal() == #CLASS) \
5032 return parse##CLASS(N, IsDistinct);
5033#include "llvm/IR/Metadata.def"
5035 return tokError(
"expected metadata type");
5038#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5039#define NOP_FIELD(NAME, TYPE, INIT)
5040#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5042 return error(ClosingLoc, "missing required field '" #NAME "'");
5043#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5044 if (Lex.getStrVal() == #NAME) \
5045 return parseMDField(#NAME, NAME);
5046#define PARSE_MD_FIELDS() \
5047 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5050 if (parseMDFieldsImpl( \
5052 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5053 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5058 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5060#define GET_OR_DISTINCT(CLASS, ARGS) \
5061 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5066bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5067#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5068 OPTIONAL(line, LineField, ); \
5069 OPTIONAL(column, ColumnField, ); \
5070 REQUIRED(scope, MDField, ( false)); \
5071 OPTIONAL(inlinedAt, MDField, ); \
5072 OPTIONAL(isImplicitCode, MDBoolField, (false));
5074#undef VISIT_MD_FIELDS
5078 inlinedAt.Val, isImplicitCode.Val));
5084bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5086 return Lex.
Error(
"missing 'distinct', required for !DIAssignID()");
5102bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5103#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5104 REQUIRED(tag, DwarfTagField, ); \
5105 OPTIONAL(header, MDStringField, ); \
5106 OPTIONAL(operands, MDFieldList, );
5108#undef VISIT_MD_FIELDS
5111 (Context, tag.Val, header.Val, operands.Val));
5119bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5120#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5121 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5122 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5123 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5124 OPTIONAL(stride, MDSignedOrMDField, );
5126#undef VISIT_MD_FIELDS
5133 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5134 if (Bound.isMDSignedField())
5137 if (Bound.isMDField())
5138 return Bound.getMDFieldValue();
5142 Count = convToMetadata(
count);
5143 LowerBound = convToMetadata(lowerBound);
5145 Stride = convToMetadata(stride);
5148 (Context, Count, LowerBound, UpperBound, Stride));
5156bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5157#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5158 OPTIONAL(count, MDSignedOrMDField, ); \
5159 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5160 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5161 OPTIONAL(stride, MDSignedOrMDField, );
5163#undef VISIT_MD_FIELDS
5165 auto ConvToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5166 if (Bound.isMDSignedField())
5168 Context, {dwarf::DW_OP_consts,
5169 static_cast<uint64_t>(Bound.getMDSignedValue())});
5170 if (Bound.isMDField())
5171 return Bound.getMDFieldValue();
5176 Metadata *LowerBound = ConvToMetadata(lowerBound);
5178 Metadata *Stride = ConvToMetadata(stride);
5181 (Context, Count, LowerBound, UpperBound, Stride));
5188bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5189#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5190 REQUIRED(name, MDStringField, ); \
5191 REQUIRED(value, MDAPSIntField, ); \
5192 OPTIONAL(isUnsigned, MDBoolField, (false));
5194#undef VISIT_MD_FIELDS
5196 if (isUnsigned.Val &&
value.Val.isNegative())
5197 return tokError(
"unsigned enumerator with negative value");
5202 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())
5214bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5215#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5216 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5217 OPTIONAL(name, MDStringField, ); \
5218 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5219 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5220 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5221 OPTIONAL(flags, DIFlagField, );
5223#undef VISIT_MD_FIELDS
5226 align.Val, encoding.Val, flags.Val));
5232bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5233#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5234 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5235 OPTIONAL(name, MDStringField, ); \
5236 OPTIONAL(stringLength, MDField, ); \
5237 OPTIONAL(stringLengthExpression, MDField, ); \
5238 OPTIONAL(stringLocationExpression, MDField, ); \
5239 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5240 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5241 OPTIONAL(encoding, DwarfAttEncodingField, );
5243#undef VISIT_MD_FIELDS
5247 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5248 stringLocationExpression.Val,
size.Val, align.Val, encoding.Val));
5261bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5262#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5263 REQUIRED(tag, DwarfTagField, ); \
5264 OPTIONAL(name, MDStringField, ); \
5265 OPTIONAL(file, MDField, ); \
5266 OPTIONAL(line, LineField, ); \
5267 OPTIONAL(scope, MDField, ); \
5268 REQUIRED(baseType, MDField, ); \
5269 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5270 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5271 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5272 OPTIONAL(flags, DIFlagField, ); \
5273 OPTIONAL(extraData, MDField, ); \
5274 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5275 OPTIONAL(annotations, MDField, ); \
5276 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5277 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5278 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5279 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5280 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5282#undef VISIT_MD_FIELDS
5284 std::optional<unsigned> DWARFAddressSpace;
5285 if (dwarfAddressSpace.Val != UINT32_MAX)
5286 DWARFAddressSpace = dwarfAddressSpace.Val;
5287 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5289 PtrAuthData.emplace(
5290 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5291 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5292 ptrAuthAuthenticatesNullValues.Val);
5295 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5296 scope.Val, baseType.Val,
size.Val, align.Val,
5297 offset.Val, DWARFAddressSpace, PtrAuthData,
5298 flags.Val, extraData.Val, annotations.Val));
5302bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5303#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5304 REQUIRED(tag, DwarfTagField, ); \
5305 OPTIONAL(name, MDStringField, ); \
5306 OPTIONAL(file, MDField, ); \
5307 OPTIONAL(line, LineField, ); \
5308 OPTIONAL(scope, MDField, ); \
5309 OPTIONAL(baseType, MDField, ); \
5310 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5311 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5312 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5313 OPTIONAL(flags, DIFlagField, ); \
5314 OPTIONAL(elements, MDField, ); \
5315 OPTIONAL(runtimeLang, DwarfLangField, ); \
5316 OPTIONAL(vtableHolder, MDField, ); \
5317 OPTIONAL(templateParams, MDField, ); \
5318 OPTIONAL(identifier, MDStringField, ); \
5319 OPTIONAL(discriminator, MDField, ); \
5320 OPTIONAL(dataLocation, MDField, ); \
5321 OPTIONAL(associated, MDField, ); \
5322 OPTIONAL(allocated, MDField, ); \
5323 OPTIONAL(rank, MDSignedOrMDField, ); \
5324 OPTIONAL(annotations, MDField, );
5326#undef VISIT_MD_FIELDS
5329 if (
rank.isMDSignedField())
5332 else if (
rank.isMDField())
5333 Rank =
rank.getMDFieldValue();
5338 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5339 scope.Val, baseType.Val,
size.Val, align.Val, offset.Val, flags.Val,
5340 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5341 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5342 Rank, annotations.Val)) {
5351 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5352 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5353 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5354 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5359bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5360#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5361 OPTIONAL(flags, DIFlagField, ); \
5362 OPTIONAL(cc, DwarfCCField, ); \
5363 REQUIRED(types, MDField, );
5365#undef VISIT_MD_FIELDS
5368 (Context, flags.Val, cc.Val, types.Val));
5377bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5381#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5382 REQUIRED(filename, MDStringField, ); \
5383 REQUIRED(directory, MDStringField, ); \
5384 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5385 OPTIONAL(checksum, MDStringField, ); \
5386 OPTIONAL(source, MDStringField, );
5388#undef VISIT_MD_FIELDS
5390 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5391 if (checksumkind.Seen && checksum.Seen)
5392 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5393 else if (checksumkind.Seen || checksum.Seen)
5394 return Lex.
Error(
"'checksumkind' and 'checksum' must be provided together");
5400 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5411bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5413 return Lex.
Error(
"missing 'distinct', required for !DICompileUnit");
5415#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5416 REQUIRED(language, DwarfLangField, ); \
5417 REQUIRED(file, MDField, ( false)); \
5418 OPTIONAL(producer, MDStringField, ); \
5419 OPTIONAL(isOptimized, MDBoolField, ); \
5420 OPTIONAL(flags, MDStringField, ); \
5421 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5422 OPTIONAL(splitDebugFilename, MDStringField, ); \
5423 OPTIONAL(emissionKind, EmissionKindField, ); \
5424 OPTIONAL(enums, MDField, ); \
5425 OPTIONAL(retainedTypes, MDField, ); \
5426 OPTIONAL(globals, MDField, ); \
5427 OPTIONAL(imports, MDField, ); \
5428 OPTIONAL(macros, MDField, ); \
5429 OPTIONAL(dwoId, MDUnsignedField, ); \
5430 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5431 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5432 OPTIONAL(nameTableKind, NameTableKindField, ); \
5433 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5434 OPTIONAL(sysroot, MDStringField, ); \
5435 OPTIONAL(sdk, MDStringField, );
5437#undef VISIT_MD_FIELDS
5440 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5441 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5442 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5443 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5444 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5457bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5459#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5460 OPTIONAL(scope, MDField, ); \
5461 OPTIONAL(name, MDStringField, ); \
5462 OPTIONAL(linkageName, MDStringField, ); \
5463 OPTIONAL(file, MDField, ); \
5464 OPTIONAL(line, LineField, ); \
5465 OPTIONAL(type, MDField, ); \
5466 OPTIONAL(isLocal, MDBoolField, ); \
5467 OPTIONAL(isDefinition, MDBoolField, (true)); \
5468 OPTIONAL(scopeLine, LineField, ); \
5469 OPTIONAL(containingType, MDField, ); \
5470 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5471 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5472 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5473 OPTIONAL(flags, DIFlagField, ); \
5474 OPTIONAL(spFlags, DISPFlagField, ); \
5475 OPTIONAL(isOptimized, MDBoolField, ); \
5476 OPTIONAL(unit, MDField, ); \
5477 OPTIONAL(templateParams, MDField, ); \
5478 OPTIONAL(declaration, MDField, ); \
5479 OPTIONAL(retainedNodes, MDField, ); \
5480 OPTIONAL(thrownTypes, MDField, ); \
5481 OPTIONAL(annotations, MDField, ); \
5482 OPTIONAL(targetFuncName, MDStringField, );
5484#undef VISIT_MD_FIELDS
5489 spFlags.Seen ? spFlags.Val
5491 isOptimized.Val, virtuality.Val);
5492 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5495 "missing 'distinct', required for !DISubprogram that is a Definition");
5498 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5499 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5500 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5501 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5502 targetFuncName.Val));
5508bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5509#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5510 REQUIRED(scope, MDField, ( false)); \
5511 OPTIONAL(file, MDField, ); \
5512 OPTIONAL(line, LineField, ); \
5513 OPTIONAL(column, ColumnField, );
5515#undef VISIT_MD_FIELDS
5524bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5525#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5526 REQUIRED(scope, MDField, ( false)); \
5527 OPTIONAL(file, MDField, ); \
5528 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5530#undef VISIT_MD_FIELDS
5533 (Context, scope.Val,
file.Val, discriminator.Val));
5539bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5540#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5541 REQUIRED(scope, MDField, ); \
5542 OPTIONAL(declaration, MDField, ); \
5543 OPTIONAL(name, MDStringField, ); \
5544 OPTIONAL(file, MDField, ); \
5545 OPTIONAL(line, LineField, );
5547#undef VISIT_MD_FIELDS
5550 (Context, scope.Val, declaration.Val,
name.Val,
5551 file.Val, line.Val));
5557bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5558#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5559 REQUIRED(scope, MDField, ); \
5560 OPTIONAL(name, MDStringField, ); \
5561 OPTIONAL(exportSymbols, MDBoolField, );
5563#undef VISIT_MD_FIELDS
5566 (Context, scope.Val,
name.Val, exportSymbols.Val));
5573bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5574#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5575 REQUIRED(type, DwarfMacinfoTypeField, ); \
5576 OPTIONAL(line, LineField, ); \
5577 REQUIRED(name, MDStringField, ); \
5578 OPTIONAL(value, MDStringField, );
5580#undef VISIT_MD_FIELDS
5583 (Context, type.Val, line.Val,
name.Val,
value.Val));
5589bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
5590#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5591 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5592 OPTIONAL(line, LineField, ); \
5593 REQUIRED(file, MDField, ); \
5594 OPTIONAL(nodes, MDField, );
5596#undef VISIT_MD_FIELDS
5599 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
5607bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
5608#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5609 REQUIRED(scope, MDField, ); \
5610 REQUIRED(name, MDStringField, ); \
5611 OPTIONAL(configMacros, MDStringField, ); \
5612 OPTIONAL(includePath, MDStringField, ); \
5613 OPTIONAL(apinotes, MDStringField, ); \
5614 OPTIONAL(file, MDField, ); \
5615 OPTIONAL(line, LineField, ); \
5616 OPTIONAL(isDecl, MDBoolField, );
5618#undef VISIT_MD_FIELDS
5621 configMacros.Val, includePath.Val,
5622 apinotes.Val, line.Val, isDecl.Val));
5628bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
5629#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5630 OPTIONAL(name, MDStringField, ); \
5631 REQUIRED(type, MDField, ); \
5632 OPTIONAL(defaulted, MDBoolField, );
5634#undef VISIT_MD_FIELDS
5637 (Context,
name.Val, type.Val, defaulted.Val));
5645bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
5646#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5647 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5648 OPTIONAL(name, MDStringField, ); \
5649 OPTIONAL(type, MDField, ); \
5650 OPTIONAL(defaulted, MDBoolField, ); \
5651 REQUIRED(value, MDField, );
5654#undef VISIT_MD_FIELDS
5658 (Context, tag.Val,
name.Val, type.Val, defaulted.Val,
value.Val));
5667bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
5668#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5669 OPTIONAL(name, MDStringField, ( false)); \
5670 OPTIONAL(scope, MDField, ); \
5671 OPTIONAL(linkageName, MDStringField, ); \
5672 OPTIONAL(file, MDField, ); \
5673 OPTIONAL(line, LineField, ); \
5674 OPTIONAL(type, MDField, ); \
5675 OPTIONAL(isLocal, MDBoolField, ); \
5676 OPTIONAL(isDefinition, MDBoolField, (true)); \
5677 OPTIONAL(templateParams, MDField, ); \
5678 OPTIONAL(declaration, MDField, ); \
5679 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5680 OPTIONAL(annotations, MDField, );
5682#undef VISIT_MD_FIELDS
5686 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
5687 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5688 declaration.Val, templateParams.Val, align.Val,
5700bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
5701#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5702 REQUIRED(scope, MDField, ( false)); \
5703 OPTIONAL(name, MDStringField, ); \
5704 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5705 OPTIONAL(file, MDField, ); \
5706 OPTIONAL(line, LineField, ); \
5707 OPTIONAL(type, MDField, ); \
5708 OPTIONAL(flags, DIFlagField, ); \
5709 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5710 OPTIONAL(annotations, MDField, );
5712#undef VISIT_MD_FIELDS
5715 (Context, scope.Val,
name.Val,
file.Val, line.Val,
5716 type.Val, arg.Val, flags.Val, align.Val,
5723bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
5724#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5725 REQUIRED(scope, MDField, ( false)); \
5726 REQUIRED(name, MDStringField, ); \
5727 REQUIRED(file, MDField, ); \
5728 REQUIRED(line, LineField, );
5730#undef VISIT_MD_FIELDS
5733 (Context, scope.Val,
name.Val,
file.Val, line.Val));
5739bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
5755 return tokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
5764 return tokError(
Twine(
"invalid DWARF attribute encoding '") +
5769 return tokError(
"expected unsigned integer");
5787bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
5788 assert(PFS &&
"Expected valid function state");
5799 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
5801 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5813bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
5815#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5816 REQUIRED(var, MDField, ); \
5817 REQUIRED(expr, MDField, );
5819#undef VISIT_MD_FIELDS
5829bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
5830#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5831 OPTIONAL(name, MDStringField, ); \
5832 OPTIONAL(file, MDField, ); \
5833 OPTIONAL(line, LineField, ); \
5834 OPTIONAL(setter, MDStringField, ); \
5835 OPTIONAL(getter, MDStringField, ); \
5836 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5837 OPTIONAL(type, MDField, );
5839#undef VISIT_MD_FIELDS
5842 (Context,
name.Val,
file.Val, line.Val, setter.Val,
5843 getter.Val, attributes.Val, type.Val));
5850bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
5851#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5852 REQUIRED(tag, DwarfTagField, ); \
5853 REQUIRED(scope, MDField, ); \
5854 OPTIONAL(entity, MDField, ); \
5855 OPTIONAL(file, MDField, ); \
5856 OPTIONAL(line, LineField, ); \
5857 OPTIONAL(name, MDStringField, ); \
5858 OPTIONAL(elements, MDField, );
5860#undef VISIT_MD_FIELDS
5863 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
5864 line.Val,
name.Val, elements.Val));
5868#undef PARSE_MD_FIELD
5880bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
5883 if (parseMetadata(MD, &PFS))
5894bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
5895 PerFunctionState *PFS) {
5898 if (parseType(Ty, TypeMsg, Loc))
5901 return error(Loc,
"invalid metadata-value-metadata roundtrip");
5904 if (parseValue(Ty, V, PFS))
5919bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
5925 if (parseDIArgList(AL, PFS))
5931 if (parseSpecializedMDNode(
N)) {
5941 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
5951 if (parseMDString(S))
5961 if (parseMDNodeTail(
N))
5972 PerFunctionState *PFS) {
5974 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
5979 return error(
ID.Loc,
"invalid use of function-local name");
5980 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
5981 return V ==
nullptr;
5984 return error(
ID.Loc,
"invalid use of function-local name");
5985 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
5986 return V ==
nullptr;
5989 return error(
ID.Loc,
"invalid type for inline asm constraint string");
5993 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
5998 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6001 return V ==
nullptr;
6003 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6006 return V ==
nullptr;
6009 return error(
ID.Loc,
"integer constant must have integer type");
6011 V = ConstantInt::get(Context,
ID.APSIntVal);
6016 return error(
ID.Loc,
"floating point constant invalid for type");
6022 bool IsSNAN =
ID.APFloatVal.isSignaling();
6037 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6039 ID.APFloatVal.isNegative(), &Payload);
6042 V = ConstantFP::get(Context,
ID.APFloatVal);
6044 if (
V->getType() != Ty)
6045 return error(
ID.Loc,
"floating point constant does not have type '" +
6051 return error(
ID.Loc,
"null must be a pointer type");
6057 return error(
ID.Loc,
"invalid type for undef constant");
6061 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6062 return error(
ID.Loc,
"invalid empty array initializer");
6068 return error(
ID.Loc,
"invalid type for null constant");
6069 if (
auto *TETy = dyn_cast<TargetExtType>(Ty))
6071 return error(
ID.Loc,
"invalid type for null constant");
6076 return error(
ID.Loc,
"invalid type for none constant");
6082 return error(
ID.Loc,
"invalid type for poison constant");
6086 if (
ID.ConstantVal->getType() != Ty)
6087 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6094 return error(
ID.Loc,
"vector constant must have vector type");
6096 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6098 "' but expected '" +
6105 if (
StructType *ST = dyn_cast<StructType>(Ty)) {
6106 if (
ST->getNumElements() !=
ID.UIntVal)
6108 "initializer with struct type has wrong # elements");
6110 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6113 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6114 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6117 "element " +
Twine(i) +
6118 " of struct initializer doesn't match struct element type");
6121 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6123 return error(
ID.Loc,
"constant expression type mismatch");
6133 if (parseValID(
ID,
nullptr))
6144 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6146 assert(isa<Constant>(V) &&
"Expected a constant value");
6147 C = cast<Constant>(V);
6154 return error(Loc,
"expected a constant value");
6158bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6161 return parseValID(
ID, PFS, Ty) ||
6162 convertValIDToValue(Ty,
ID, V, PFS);
6165bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6167 return parseType(Ty) || parseValue(Ty, V, PFS);
6170bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
6171 PerFunctionState &PFS) {
6174 if (parseTypeAndValue(V, PFS))
6176 if (!isa<BasicBlock>(V))
6177 return error(Loc,
"expected a basic block");
6178 BB = cast<BasicBlock>(V);
6186 if (!
Name.starts_with(
"llvm.dbg."))
6189 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6190 FnID == Intrinsic::dbg_assign;
6198bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6199 unsigned &FunctionNumber,
6204 unsigned Visibility;
6205 unsigned DLLStorageClass;
6210 Type *RetType =
nullptr;
6212 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6214 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
6215 parseType(RetType, RetTypeLoc,
true ))
6224 return error(LinkageLoc,
"invalid linkage for function definition");
6234 return error(LinkageLoc,
"invalid linkage for function declaration");
6238 return error(LinkageLoc,
"invalid function linkage type");
6242 return error(LinkageLoc,
6243 "symbol with local linkage must have default visibility");
6246 return error(LinkageLoc,
6247 "symbol with local linkage cannot have a DLL storage class");
6250 return error(RetTypeLoc,
"invalid function return type");
6254 std::string FunctionName;
6259 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6263 return tokError(
"expected function name");
6269 return tokError(
"expected '(' in function argument list");
6274 std::vector<unsigned> FwdRefAttrGrps;
6277 std::string Partition;
6281 unsigned AddrSpace = 0;
6287 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6288 parseOptionalUnnamedAddr(UnnamedAddr) ||
6289 parseOptionalProgramAddrSpace(AddrSpace) ||
6290 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6294 parseOptionalComdat(FunctionName,
C) ||
6295 parseOptionalAlignment(Alignment) ||
6296 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6300 parseGlobalTypeAndValue(PersonalityFn)))
6303 if (FuncAttrs.contains(Attribute::Builtin))
6304 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6309 FuncAttrs.removeAttribute(Attribute::Alignment);
6314 std::vector<Type*> ParamTypeList;
6317 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
6318 ParamTypeList.push_back(ArgList[i].Ty);
6319 Attrs.push_back(ArgList[i].Attrs);
6327 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6334 if (!FunctionName.empty()) {
6337 auto FRVI = ForwardRefVals.find(FunctionName);
6338 if (FRVI != ForwardRefVals.end()) {
6339 FwdFn = FRVI->second.first;
6341 return error(FRVI->second.second,
6342 "invalid forward reference to "
6345 "' with wrong type: "
6349 ForwardRefVals.erase(FRVI);
6350 }
else if ((Fn =
M->getFunction(FunctionName))) {
6352 return error(NameLoc,
6353 "invalid redefinition of function '" + FunctionName +
"'");
6354 }
else if (
M->getNamedValue(FunctionName)) {
6355 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6361 if (FunctionNumber == (
unsigned)-1)
6362 FunctionNumber = NumberedVals.getNext();
6366 auto I = ForwardRefValIDs.find(FunctionNumber);
6367 if (
I != ForwardRefValIDs.end()) {
6368 FwdFn =
I->second.first;
6370 return error(NameLoc,
"type of definition and forward reference of '@" +
6371 Twine(FunctionNumber) +
6376 ForwardRefValIDs.erase(
I);
6385 if (FunctionName.empty())
6386 NumberedVals.add(FunctionNumber, Fn);
6401 if (!
GC.empty()) Fn->
setGC(GC);
6404 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6408 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i, ++ArgIt) {
6410 if (ArgList[i].
Name.empty())
continue;
6415 if (ArgIt->
getName() != ArgList[i].Name)
6416 return error(ArgList[i].Loc,
6417 "redefinition of argument '%" + ArgList[i].
Name +
"'");
6430 if (FunctionName.empty()) {
6432 ID.UIntVal = FunctionNumber;
6435 ID.StrVal = FunctionName;
6437 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6438 if (
Blocks != ForwardRefBlockAddresses.end())
6440 "cannot take blockaddress inside a declaration");
6444bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6446 if (FunctionNumber == -1) {
6448 ID.StrVal = std::string(
F.getName());
6451 ID.UIntVal = FunctionNumber;
6454 auto Blocks =
P.ForwardRefBlockAddresses.find(
ID);
6455 if (
Blocks ==
P.ForwardRefBlockAddresses.end())
6458 for (
const auto &
I :
Blocks->second) {
6459 const ValID &BBID =
I.first;
6463 "Expected local id or name");
6470 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6481 P.ForwardRefBlockAddresses.erase(
Blocks);
6487bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
6490 return tokError(
"expected '{' in function body");
6493 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6497 if (PFS.resolveForwardRefBlockAddresses())
6503 return tokError(
"function body requires at least one basic block");
6507 if (parseBasicBlock(PFS))
6511 if (parseUseListOrder(&PFS))
6518 return PFS.finishFunction();
6523bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6540 std::string NameStr;
6545 auto DeleteDbgRecord = [](
DbgRecord *DR) { DR->deleteRecord(); };
6546 using DbgRecordPtr = std::unique_ptr<
DbgRecord,
decltype(DeleteDbgRecord)>;
6553 if (SeenOldDbgInfoFormat)
6554 return error(Lex.
getLoc(),
"debug record should not appear in a module "
6555 "containing debug info intrinsics");
6556 if (!SeenNewDbgInfoFormat)
6557 M->setNewDbgInfoFormatFlag(
true);
6558 SeenNewDbgInfoFormat =
true;
6562 if (parseDebugRecord(DR, PFS))
6564 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6576 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
6581 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
6585 switch (parseInstruction(Inst, BB, PFS)) {
6588 case InstError:
return true;
6595 if (parseInstructionMetadata(*Inst))
6598 case InstExtraComma:
6603 if (parseInstructionMetadata(*Inst))
6609 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6613 for (DbgRecordPtr &DR : TrailingDbgRecord)
6615 TrailingDbgRecord.clear();
6618 assert(TrailingDbgRecord.empty() &&
6619 "All debug values should have been attached to an instruction.");
6628bool LLParser::parseDebugRecord(
DbgRecord *&DR, PerFunctionState &PFS) {
6633 return error(DVRLoc,
"expected debug record type here");
6635 .
Case(
"declare", RecordKind::ValueKind)
6636 .
Case(
"value", RecordKind::ValueKind)
6637 .
Case(
"assign", RecordKind::ValueKind)
6638 .
Case(
"label", RecordKind::LabelKind);
6647 if (parseMDNode(Label))
6652 if (parseMDNode(DbgLoc))
6661 .
Case(
"declare", LocType::Declare)
6662 .
Case(
"value", LocType::Value)
6663 .
Case(
"assign", LocType::Assign);
6671 if (parseMetadata(ValLocMD, &PFS))
6678 if (parseMDNode(Variable))
6691 MDNode *AssignID =
nullptr;
6692 Metadata *AddressLocation =
nullptr;
6693 MDNode *AddressExpression =
nullptr;
6696 if (parseMDNode(AssignID))
6702 if (parseMetadata(AddressLocation, &PFS))
6708 if (parseMDNode(AddressExpression))
6733 PerFunctionState &PFS) {
6736 return tokError(
"found end of file when expecting more instructions");
6743 return error(Loc,
"expected instruction opcode");
6747 return parseRet(Inst, BB, PFS);
6749 return parseBr(Inst, PFS);
6751 return parseSwitch(Inst, PFS);
6753 return parseIndirectBr(Inst, PFS);
6755 return parseInvoke(Inst, PFS);
6757 return parseResume(Inst, PFS);
6759 return parseCleanupRet(Inst, PFS);
6761 return parseCatchRet(Inst, PFS);
6763 return parseCatchSwitch(Inst, PFS);
6765 return parseCatchPad(Inst, PFS);
6767 return parseCleanupPad(Inst, PFS);
6769 return parseCallBr(Inst, PFS);
6773 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
6789 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6792 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
6793 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
6802 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
6816 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6818 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
6824 return parseArithmetic(Inst, PFS, KeywordVal,
6828 if (parseLogical(Inst, PFS, KeywordVal))
6831 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(
true);
6836 return parseLogical(Inst, PFS, KeywordVal);
6838 return parseCompare(Inst, PFS, KeywordVal);
6841 int Res = parseCompare(Inst, PFS, KeywordVal);
6853 bool Res = parseCast(Inst, PFS, KeywordVal);
6865 if (parseCast(Inst, PFS, KeywordVal))
6868 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(
true);
6870 cast<TruncInst>(Inst)->setHasNoSignedWrap(
true);
6883 return parseCast(Inst, PFS, KeywordVal);
6887 int Res = parseSelect(Inst, PFS);
6891 if (!isa<FPMathOperator>(Inst))
6892 return error(Loc,
"fast-math-flags specified for select without "
6893 "floating-point scalar or vector return type");
6899 return parseVAArg(Inst, PFS);
6901 return parseExtractElement(Inst, PFS);
6903 return parseInsertElement(Inst, PFS);
6905 return parseShuffleVector(Inst, PFS);
6908 int Res = parsePHI(Inst, PFS);
6912 if (!isa<FPMathOperator>(Inst))
6913 return error(Loc,
"fast-math-flags specified for phi without "
6914 "floating-point scalar or vector return type");
6920 return parseLandingPad(Inst, PFS);
6922 return parseFreeze(Inst, PFS);
6934 return parseAlloc(Inst, PFS);
6936 return parseLoad(Inst, PFS);
6938 return parseStore(Inst, PFS);
6940 return parseCmpXchg(Inst, PFS);
6942 return parseAtomicRMW(Inst, PFS);
6944 return parseFence(Inst, PFS);
6946 return parseGetElementPtr(Inst, PFS);
6948 return parseExtractValue(Inst, PFS);
6950 return parseInsertValue(Inst, PFS);
6955bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
6956 if (Opc == Instruction::FCmp) {
6959 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
6980 return tokError(
"expected icmp predicate (e.g. 'eq')");
7005 PerFunctionState &PFS) {
7008 if (parseType(Ty,
true ))
7011 Type *ResType = PFS.getFunction().getReturnType();
7015 return error(TypeLoc,
"value doesn't match function result type '" +
7023 if (parseValue(Ty, RV, PFS))
7027 return error(TypeLoc,
"value doesn't match function result type '" +
7037bool LLParser::parseBr(
Instruction *&Inst, PerFunctionState &PFS) {
7041 if (parseTypeAndValue(Op0, Loc, PFS))
7044 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7050 return error(Loc,
"branch condition must have 'i1' type");
7052 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7053 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7054 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7055 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7067bool LLParser::parseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7068 LocTy CondLoc, BBLoc;
7071 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7072 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7073 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7077 if (!
Cond->getType()->isIntegerTy())
7078 return error(CondLoc,
"switch condition must have integer type");
7087 if (parseTypeAndValue(
Constant, CondLoc, PFS) ||
7088 parseToken(
lltok::comma,
"expected ',' after case value") ||
7089 parseTypeAndBasicBlock(DestBB, PFS))
7093 return error(CondLoc,
"duplicate case value in switch");
7095 return error(CondLoc,
"case value is not a constant integer");
7103 for (
unsigned i = 0, e = Table.
size(); i != e; ++i)
7104 SI->addCase(Table[i].first, Table[i].second);
7112bool LLParser::parseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
7115 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7116 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7120 if (!
Address->getType()->isPointerTy())
7121 return error(AddrLoc,
"indirectbr address must have pointer type");
7128 if (parseTypeAndBasicBlock(DestBB, PFS))
7133 if (parseTypeAndBasicBlock(DestBB, PFS))
7139 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7143 for (
unsigned i = 0, e = DestList.
size(); i != e; ++i)
7152bool LLParser::resolveFunctionType(
Type *RetType,
7155 FuncTy = dyn_cast<FunctionType>(RetType);
7158 std::vector<Type*> ParamTypes;
7159 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
7160 ParamTypes.push_back(ArgList[i].
V->getType());
7173bool LLParser::parseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
7175 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7176 std::vector<unsigned> FwdRefAttrGrps;
7179 unsigned InvokeAddrSpace;
7180 Type *RetType =
nullptr;
7187 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7188 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7189 parseType(RetType, RetTypeLoc,
true ) ||
7190 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7191 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7193 parseOptionalOperandBundles(BundleList, PFS) ||
7195 parseTypeAndBasicBlock(NormalBB, PFS) ||
7197 parseTypeAndBasicBlock(UnwindBB, PFS))
7204 if (resolveFunctionType(RetType, ArgList, Ty))
7205 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7223 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7224 Type *ExpectedTy =
nullptr;
7227 }
else if (!Ty->isVarArg()) {
7228 return error(ArgList[i].Loc,
"too many arguments specified");
7231 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7232 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7234 Args.push_back(ArgList[i].V);
7239 return error(CallLoc,
"not enough parameters specified for call");
7250 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7257bool LLParser::parseResume(
Instruction *&Inst, PerFunctionState &PFS) {
7259 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7268 PerFunctionState &PFS) {
7269 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7274 if (!
Args.empty() &&
7275 parseToken(
lltok::comma,
"expected ',' in argument list"))
7280 Type *ArgTy =
nullptr;
7281 if (parseType(ArgTy, ArgLoc))
7286 if (parseMetadataAsValue(V, PFS))
7289 if (parseValue(ArgTy, V, PFS))
7301bool LLParser::parseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
7302 Value *CleanupPad =
nullptr;
7304 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7319 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7330bool LLParser::parseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
7331 Value *CatchPad =
nullptr;
7333 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7340 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7341 parseTypeAndBasicBlock(BB, PFS))
7350bool LLParser::parseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7358 return tokError(
"expected scope value for catchswitch");
7363 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7369 if (parseTypeAndBasicBlock(DestBB, PFS))
7374 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7377 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7385 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7392 CatchSwitch->addHandler(DestBB);
7399bool LLParser::parseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
7400 Value *CatchSwitch =
nullptr;
7406 return tokError(
"expected scope value for catchpad");
7412 if (parseExceptionArgs(Args, PFS))
7421bool LLParser::parseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
7422 Value *ParentPad =
nullptr;
7429 return tokError(
"expected scope value for cleanuppad");
7435 if (parseExceptionArgs(Args, PFS))
7451bool LLParser::parseUnaryOp(
Instruction *&Inst, PerFunctionState &PFS,
7452 unsigned Opc,
bool IsFP) {
7454 if (parseTypeAndValue(LHS, Loc, PFS))
7461 return error(Loc,
"invalid operand type for instruction");
7471bool LLParser::parseCallBr(
Instruction *&Inst, PerFunctionState &PFS) {
7473 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7474 std::vector<unsigned> FwdRefAttrGrps;
7477 Type *RetType =
nullptr;
7484 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7485 parseType(RetType, RetTypeLoc,
true ) ||
7486 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7487 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7489 parseOptionalOperandBundles(BundleList, PFS) ||
7491 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7500 if (parseTypeAndBasicBlock(DestBB, PFS))
7505 if (parseTypeAndBasicBlock(DestBB, PFS))
7511 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7518 if (resolveFunctionType(RetType, ArgList, Ty))
7519 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7536 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7537 Type *ExpectedTy =
nullptr;
7540 }
else if (!Ty->isVarArg()) {
7541 return error(ArgList[i].Loc,
"too many arguments specified");
7544 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7545 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7547 Args.push_back(ArgList[i].V);
7552 return error(CallLoc,
"not enough parameters specified for call");
7564 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7578bool LLParser::parseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
7579 unsigned Opc,
bool IsFP) {
7581 if (parseTypeAndValue(LHS, Loc, PFS) ||
7582 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
7590 return error(Loc,
"invalid operand type for instruction");
7598bool LLParser::parseLogical(
Instruction *&Inst, PerFunctionState &PFS,
7601 if (parseTypeAndValue(LHS, Loc, PFS) ||
7602 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
7608 "instruction requires integer or integer vector operands");
7617bool LLParser::parseCompare(
Instruction *&Inst, PerFunctionState &PFS,
7623 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7624 parseToken(
lltok::comma,
"expected ',' after compare value") ||
7628 if (Opc == Instruction::FCmp) {
7630 return error(Loc,
"fcmp requires floating point operands");
7633 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
7636 return error(Loc,
"icmp requires integer operands");
7648bool LLParser::parseCast(
Instruction *&Inst, PerFunctionState &PFS,
7652 Type *DestTy =
nullptr;
7653 if (parseTypeAndValue(
Op, Loc, PFS) ||
7654 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
7660 return error(Loc,
"invalid cast opcode for cast from '" +
7670bool LLParser::parseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
7672 Value *Op0, *Op1, *Op2;
7673 if (parseTypeAndValue(Op0, Loc, PFS) ||
7674 parseToken(
lltok::comma,
"expected ',' after select condition") ||
7675 parseTypeAndValue(Op1, PFS) ||
7676 parseToken(
lltok::comma,
"expected ',' after select value") ||
7677 parseTypeAndValue(Op2, PFS))
7681 return error(Loc, Reason);
7689bool LLParser::parseVAArg(
Instruction *&Inst, PerFunctionState &PFS) {
7691 Type *EltTy =
nullptr;
7693 if (parseTypeAndValue(
Op, PFS) ||
7694 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
7695 parseType(EltTy, TypeLoc))
7699 return error(TypeLoc,
"va_arg requires operand with first class type");
7707bool LLParser::parseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
7710 if (parseTypeAndValue(Op0, Loc, PFS) ||
7711 parseToken(
lltok::comma,
"expected ',' after extract value") ||
7712 parseTypeAndValue(Op1, PFS))
7716 return error(Loc,
"invalid extractelement operands");
7724bool LLParser::parseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
7726 Value *Op0, *Op1, *Op2;
7727 if (parseTypeAndValue(Op0, Loc, PFS) ||
7728 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7729 parseTypeAndValue(Op1, PFS) ||
7730 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7731 parseTypeAndValue(Op2, PFS))
7735 return error(Loc,
"invalid insertelement operands");
7743bool LLParser::parseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
7745 Value *Op0, *Op1, *Op2;
7746 if (parseTypeAndValue(Op0, Loc, PFS) ||
7747 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
7748 parseTypeAndValue(Op1, PFS) ||
7749 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
7750 parseTypeAndValue(Op2, PFS))
7754 return error(Loc,
"invalid shufflevector operands");
7762int LLParser::parsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
7766 if (parseType(Ty, TypeLoc))
7770 return error(TypeLoc,
"phi node must have first class type");
7773 bool AteExtraComma =
false;
7785 AteExtraComma =
true;
7789 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
7790 parseValue(Ty, Op0, PFS) ||
7791 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7796 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7800 for (
unsigned i = 0, e = PHIVals.
size(); i != e; ++i)
7801 PN->
addIncoming(PHIVals[i].first, PHIVals[i].second);
7803 return AteExtraComma ? InstExtraComma : InstNormal;
7812bool LLParser::parseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
7815 if (parseType(Ty, TyLoc))
7828 return tokError(
"expected 'catch' or 'filter' clause type");
7832 if (parseTypeAndValue(V, VLoc, PFS))
7838 if (isa<ArrayType>(
V->getType()))
7839 error(VLoc,
"'catch' clause has an invalid type");
7841 if (!isa<ArrayType>(
V->getType()))
7842 error(VLoc,
"'filter' clause has an invalid type");
7845 Constant *CV = dyn_cast<Constant>(V);
7847 return error(VLoc,
"clause argument must be a constant");
7851 Inst = LP.release();
7857bool LLParser::parseFreeze(
Instruction *&Inst, PerFunctionState &PFS) {
7860 if (parseTypeAndValue(
Op, Loc, PFS))
7876bool LLParser::parseCall(
Instruction *&Inst, PerFunctionState &PFS,
7878 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7879 std::vector<unsigned> FwdRefAttrGrps;
7881 unsigned CallAddrSpace;
7883 Type *RetType =
nullptr;
7892 "expected 'tail call', 'musttail call', or 'notail call'"))
7897 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7898 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7899 parseType(RetType, RetTypeLoc,
true ) ||
7900 parseValID(CalleeID, &PFS) ||
7902 PFS.getFunction().isVarArg()) ||
7903 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
7904 parseOptionalOperandBundles(BundleList, PFS))
7911 if (resolveFunctionType(RetType, ArgList, Ty))
7912 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7918 if (convertValIDToValue(
PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7931 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7932 Type *ExpectedTy =
nullptr;
7935 }
else if (!Ty->isVarArg()) {
7936 return error(ArgList[i].Loc,
"too many arguments specified");
7939 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7940 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7942 Args.push_back(ArgList[i].V);
7943 Attrs.push_back(ArgList[i].Attrs);
7947 return error(CallLoc,
"not enough parameters specified for call");
7958 if (!isa<FPMathOperator>(CI)) {
7960 return error(CallLoc,
"fast-math-flags specified for call without "
7961 "floating-point scalar or vector return type");
7968 if (SeenNewDbgInfoFormat) {
7970 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
7971 "using non-intrinsic debug info");
7973 if (!SeenOldDbgInfoFormat)
7974 M->setNewDbgInfoFormatFlag(
false);
7975 SeenOldDbgInfoFormat =
true;
7978 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7990int LLParser::parseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
7992 LocTy SizeLoc, TyLoc, ASLoc;
7994 unsigned AddrSpace = 0;
7997 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7998 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8000 if (parseType(Ty, TyLoc))
8004 return error(TyLoc,
"invalid type for alloca");
8006 bool AteExtraComma =
false;
8008 if (Lex.
getKind() == lltok::kw_align) {
8009 if (parseOptionalAlignment(Alignment))
8011 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8015 if (parseOptionalAddrSpace(AddrSpace))
8018 AteExtraComma =
true;
8020 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8023 if (Lex.
getKind() == lltok::kw_align) {
8024 if (parseOptionalAlignment(Alignment))
8026 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8030 if (parseOptionalAddrSpace(AddrSpace))
8033 AteExtraComma =
true;
8039 if (
Size && !
Size->getType()->isIntegerTy())
8040 return error(SizeLoc,
"element count must have integer type");
8043 if (!Alignment && !Ty->
isSized(&Visited))
8044 return error(TyLoc,
"Cannot allocate unsized type");
8046 Alignment =
M->getDataLayout().getPrefTypeAlign(Ty);
8051 return AteExtraComma ? InstExtraComma : InstNormal;
8058int LLParser::parseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
8061 bool AteExtraComma =
false;
8062 bool isAtomic =
false;
8071 bool isVolatile =
false;
8079 if (parseType(Ty) ||
8080 parseToken(
lltok::comma,
"expected comma after load's type") ||
8081 parseTypeAndValue(Val, Loc, PFS) ||
8082 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8083 parseOptionalCommaAlign(Alignment, AteExtraComma))
8087 return error(Loc,
"load operand must be a pointer to a first class type");
8088 if (isAtomic && !Alignment)
8089 return error(Loc,
"atomic load must have explicit non-zero alignment");
8092 return error(Loc,
"atomic load cannot use Release ordering");
8095 if (!Alignment && !Ty->
isSized(&Visited))
8096 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8098 Alignment =
M->getDataLayout().getABITypeAlign(Ty);
8099 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8100 return AteExtraComma ? InstExtraComma : InstNormal;
8108int LLParser::parseStore(
Instruction *&Inst, PerFunctionState &PFS) {
8111 bool AteExtraComma =
false;
8112 bool isAtomic =
false;
8121 bool isVolatile =
false;
8127 if (parseTypeAndValue(Val, Loc, PFS) ||
8128 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8129 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8130 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8131 parseOptionalCommaAlign(Alignment, AteExtraComma))
8134 if (!
Ptr->getType()->isPointerTy())
8135 return error(PtrLoc,
"store operand must be a pointer");
8137 return error(Loc,
"store operand must be a first class value");
8138 if (isAtomic && !Alignment)
8139 return error(Loc,
"atomic store must have explicit non-zero alignment");
8142 return error(Loc,
"atomic store cannot use Acquire ordering");
8145 return error(Loc,
"storing unsized types is not allowed");
8147 Alignment =
M->getDataLayout().getABITypeAlign(Val->
getType());
8149 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8150 return AteExtraComma ? InstExtraComma : InstNormal;
8157int LLParser::parseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
8159 bool AteExtraComma =
false;
8163 bool isVolatile =
false;
8164 bool isWeak =
false;
8173 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8174 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8175 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8176 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8177 parseTypeAndValue(New, NewLoc, PFS) ||
8178 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8179 parseOrdering(FailureOrdering) ||
8180 parseOptionalCommaAlign(Alignment, AteExtraComma))
8184 return tokError(
"invalid cmpxchg success ordering");
8186 return tokError(
"invalid cmpxchg failure ordering");
8187 if (!
Ptr->getType()->isPointerTy())
8188 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8189 if (
Cmp->getType() !=
New->getType())
8190 return error(NewLoc,
"compare value and new value type do not match");
8191 if (!
New->getType()->isFirstClassType())
8192 return error(NewLoc,
"cmpxchg operand must be a first class value");
8194 const Align DefaultAlignment(
8195 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8200 SuccessOrdering, FailureOrdering, SSID);
8205 return AteExtraComma ? InstExtraComma : InstNormal;
8211int LLParser::parseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
8213 bool AteExtraComma =
false;
8216 bool isVolatile =
false;
8226 return tokError(
"expected binary operation in atomicrmw");
8263 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8264 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8265 parseTypeAndValue(Val, ValLoc, PFS) ||
8266 parseScopeAndOrdering(
true , SSID, Ordering) ||
8267 parseOptionalCommaAlign(Alignment, AteExtraComma))
8271 return tokError(
"atomicrmw cannot be unordered");
8272 if (!
Ptr->getType()->isPointerTy())
8273 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8275 return error(ValLoc,
"atomicrmw operand may not be scalable");
8284 " operand must be an integer, floating point, or pointer type");
8288 return error(ValLoc,
"atomicrmw " +
8290 " operand must be a floating point type");
8294 return error(ValLoc,
"atomicrmw " +
8296 " operand must be an integer");
8301 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
8304 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8306 const Align DefaultAlignment(
8307 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8311 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8314 return AteExtraComma ? InstExtraComma : InstNormal;
8319int LLParser::parseFence(
Instruction *&Inst, PerFunctionState &PFS) {
8322 if (parseScopeAndOrdering(
true , SSID, Ordering))
8326 return tokError(
"fence cannot be unordered");
8328 return tokError(
"fence cannot be monotonic");
8330 Inst =
new FenceInst(Context, Ordering, SSID);
8336int LLParser::parseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
8338 Value *Val =
nullptr;
8344 if (parseType(Ty) ||
8345 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8346 parseTypeAndValue(
Ptr, Loc, PFS))
8351 if (!BasePointerType)
8352 return error(Loc,
"base of getelementptr must be a pointer");
8355 bool AteExtraComma =
false;
8359 ? cast<VectorType>(
BaseType)->getElementCount()
8364 AteExtraComma =
true;
8367 if (parseTypeAndValue(Val, EltLoc, PFS))
8370 return error(EltLoc,
"getelementptr index must be an integer");
8372 if (
auto *ValVTy = dyn_cast<VectorType>(Val->
getType())) {
8377 "getelementptr vector index has a wrong number of elements");
8378 GEPWidth = ValNumEl;
8385 return error(Loc,
"base element of getelementptr must be sized");
8387 auto *STy = dyn_cast<StructType>(Ty);
8389 return error(Loc,
"getelementptr cannot target structure that contains "
8390 "scalable vector type");
8393 return error(Loc,
"invalid getelementptr indices");
8396 cast<GetElementPtrInst>(Inst)->setIsInBounds(
true);
8397 return AteExtraComma ? InstExtraComma : InstNormal;
8402int LLParser::parseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
8406 if (parseTypeAndValue(Val, Loc, PFS) ||
8407 parseIndexList(Indices, AteExtraComma))
8411 return error(Loc,
"extractvalue operand must be aggregate type");
8414 return error(Loc,
"invalid indices for extractvalue");
8416 return AteExtraComma ? InstExtraComma : InstNormal;
8421int LLParser::parseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
8425 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8426 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8427 parseTypeAndValue(Val1, Loc1, PFS) ||
8428 parseIndexList(Indices, AteExtraComma))
8432 return error(Loc0,
"insertvalue operand must be aggregate type");
8436 return error(Loc0,
"invalid indices for insertvalue");
8437 if (IndexedType != Val1->
getType())
8438 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8442 return AteExtraComma ? InstExtraComma : InstNormal;
8468 if (parseMetadata(MD,
nullptr))
8473 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8482 return error(Loc,
"value has no uses");
8484 unsigned NumUses = 0;
8486 for (
const Use &U :
V->uses()) {
8487 if (++NumUses > Indexes.
size())
8489 Order[&
U] = Indexes[NumUses - 1];
8492 return error(Loc,
"value only has one use");
8493 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8495 "wrong number of indexes, expected " +
Twine(
V->getNumUses()));
8497 V->sortUseList([&](
const Use &L,
const Use &R) {
8510 return Lex.
Error(
"expected non-empty list of uselistorder indexes");
8517 bool IsOrdered =
true;
8518 assert(Indexes.
empty() &&
"Expected empty order vector");
8521 if (parseUInt32(
Index))
8535 if (Indexes.
size() < 2)
8536 return error(Loc,
"expected >= 2 uselistorder indexes");
8539 "expected distinct uselistorder indexes in range [0, size)");
8541 return error(Loc,
"expected uselistorder indexes to change the order");
8548bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8555 if (parseTypeAndValue(V, PFS) ||
8556 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
8557 parseUseListOrderIndexes(Indexes))
8560 return sortUseListOrder(V, Indexes, Loc);
8565bool LLParser::parseUseListOrderBB() {
8572 if (parseValID(Fn,
nullptr) ||
8573 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8574 parseValID(Label,
nullptr) ||
8575 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8576 parseUseListOrderIndexes(Indexes))
8582 GV =
M->getNamedValue(Fn.
StrVal);
8584 GV = NumberedVals.get(Fn.
UIntVal);
8586 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8589 "invalid function forward reference in uselistorder_bb");
8590 auto *
F = dyn_cast<Function>(GV);
8592 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8593 if (
F->isDeclaration())
8594 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
8598 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
8600 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
8601 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
8603 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
8604 if (!isa<BasicBlock>(V))
8605 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
8607 return sortUseListOrder(V, Indexes, Loc);
8613bool LLParser::parseModuleEntry(
unsigned ID) {
8622 parseStringConstant(Path) ||
8630 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
8631 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
8632 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
8633 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
8634 parseUInt32(Hash[4]))
8641 auto ModuleEntry =
Index->addModule(Path, Hash);
8642 ModuleIdMap[
ID] = ModuleEntry->first();
8649bool LLParser::parseTypeIdEntry(
unsigned ID) {
8658 parseStringConstant(
Name))
8663 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
8668 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8669 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8670 for (
auto TIDRef : FwdRefTIDs->second) {
8672 "Forward referenced type id GUID expected to be 0");
8675 ForwardRefTypeIds.erase(FwdRefTIDs);
8687 parseTypeTestResolution(TIS.
TTRes))
8692 if (parseOptionalWpdResolutions(TIS.
WPDRes))
8703 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
8709bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
8718 parseStringConstant(
Name))
8722 Index->getOrInsertTypeIdCompatibleVtableSummary(
Name);
8729 IdToIndexMapType IdToIndexMap;
8742 if (parseGVReference(VI, GVId))
8749 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8750 TI.push_back({
Offset, VI});
8758 for (
auto I : IdToIndexMap) {
8759 auto &Infos = ForwardRefValueInfos[
I.first];
8760 for (
auto P :
I.second) {
8762 "Forward referenced ValueInfo expected to be empty");
8763 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
8773 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8774 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8775 for (
auto TIDRef : FwdRefTIDs->second) {
8777 "Forward referenced type id GUID expected to be 0");
8780 ForwardRefTypeIds.erase(FwdRefTIDs);
8820 return error(Lex.
getLoc(),
"unexpected TypeTestResolution kind");
8847 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
8860 return error(Lex.
getLoc(),
"expected optional TypeTestResolution field");
8873bool LLParser::parseOptionalWpdResolutions(
8874 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8886 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
8889 WPDResMap[
Offset] = WPDRes;
8925 return error(Lex.
getLoc(),
"unexpected WholeProgramDevirtResolution kind");
8939 if (parseOptionalResByArg(WPDRes.
ResByArg))
8944 "expected optional WholeProgramDevirtResolution field");
8961bool LLParser::parseOptionalResByArg(
8970 std::vector<uint64_t>
Args;
8971 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
8995 "unexpected WholeProgramDevirtResolution::ByArg kind");
9005 parseUInt64(ByArg.
Info))
9011 parseUInt32(ByArg.
Byte))
9017 parseUInt32(ByArg.
Bit))
9022 "expected optional whole program devirt field");
9029 ResByArg[
Args] = ByArg;
9040bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9048 if (parseUInt64(Val))
9050 Args.push_back(Val);
9059static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9064 assert(!(ReadOnly && WriteOnly));
9074bool LLParser::addGlobalValueToIndex(
9076 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9081 VI =
Index->getOrInsertValueInfo(GUID);
9085 auto *GV =
M->getNamedValue(
Name);
9087 return error(Loc,
"Reference to undefined global \"" +
Name +
"\"");
9089 VI =
Index->getOrInsertValueInfo(GV);
9093 "Need a source_filename to compute GUID for local");
9101 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9102 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9103 for (
auto VIRef : FwdRefVIs->second) {
9105 "Forward referenced ValueInfo expected to be empty");
9108 ForwardRefValueInfos.erase(FwdRefVIs);
9112 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9113 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9114 for (
auto AliaseeRef : FwdRefAliasees->second) {
9115 assert(!AliaseeRef.first->hasAliasee() &&
9116 "Forward referencing alias already has aliasee");
9117 assert(Summary &&
"Aliasee must be a definition");
9118 AliaseeRef.first->setAliasee(VI,
Summary.get());
9120 ForwardRefAliasees.erase(FwdRefAliasees);
9125 Index->addGlobalValueSummary(VI, std::move(Summary));
9128 if (
ID == NumberedValueInfos.size())
9129 NumberedValueInfos.push_back(VI);
9132 if (
ID > NumberedValueInfos.size())
9133 NumberedValueInfos.resize(
ID + 1);
9134 NumberedValueInfos[
ID] =
VI;
9142bool LLParser::parseSummaryIndexFlags() {
9149 if (parseUInt64(Flags))
9152 Index->setFlags(Flags);
9158bool LLParser::parseBlockCount() {
9165 if (parseUInt64(BlockCount))
9168 Index->setBlockCount(BlockCount);
9176bool LLParser::parseGVEntry(
unsigned ID) {
9191 parseStringConstant(
Name))
9197 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9201 return error(Lex.
getLoc(),
"expected name or guid tag");
9226 if (parseFunctionSummary(
Name, GUID,
ID))
9230 if (parseVariableSummary(
Name, GUID,
ID))
9234 if (parseAliasSummary(
Name, GUID,
ID))
9238 return error(Lex.
getLoc(),
"expected summary type");
9264 false,
false,
false,
9267 std::vector<FunctionSummary::EdgeTy> Calls;
9269 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9270 std::vector<ValueInfo> Refs;
9271 std::vector<CallsiteInfo> Callsites;
9272 std::vector<AllocInfo> Allocs;
9277 parseModuleReference(ModulePath) ||
9278 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9281 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9288 if (parseOptionalFFlags(FFlags))
9292 if (parseOptionalCalls(Calls))
9296 if (parseOptionalTypeIdInfo(TypeIdInfo))
9300 if (parseOptionalRefs(Refs))
9304 if (parseOptionalParamAccesses(ParamAccesses))
9308 if (parseOptionalAllocs(Allocs))
9312 if (parseOptionalCallsites(Callsites))
9316 return error(Lex.
getLoc(),
"expected optional function summary field");
9323 auto FS = std::make_unique<FunctionSummary>(
9324 GVFlags, InstCount, FFlags, 0, std::move(Refs),
9325 std::move(Calls), std::move(TypeIdInfo.
TypeTests),
9330 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9332 FS->setModulePath(ModulePath);
9334 return addGlobalValueToIndex(
Name, GUID,
9336 std::move(FS), Loc);
9352 false,
false,
false,
9358 std::vector<ValueInfo> Refs;
9362 parseModuleReference(ModulePath) ||
9363 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9365 parseGVarFlags(GVarFlags))
9372 if (parseOptionalVTableFuncs(VTableFuncs))
9376 if (parseOptionalRefs(Refs))
9380 return error(Lex.
getLoc(),
"expected optional variable summary field");
9388 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9390 GS->setModulePath(ModulePath);
9391 GS->setVTableFuncs(std::move(VTableFuncs));
9393 return addGlobalValueToIndex(
Name, GUID,
9395 std::move(GS), Loc);
9411 false,
false,
false,
9415 parseModuleReference(ModulePath) ||
9416 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9424 if (parseGVReference(AliaseeVI, GVId))
9430 auto AS = std::make_unique<AliasSummary>(GVFlags);
9432 AS->setModulePath(ModulePath);
9436 ForwardRefAliasees[GVId].emplace_back(AS.
get(), Loc);
9438 auto Summary =
Index->findSummaryInModule(AliaseeVI, ModulePath);
9439 assert(Summary &&
"Aliasee must be a definition");
9440 AS->setAliasee(AliaseeVI, Summary);
9443 return addGlobalValueToIndex(
Name, GUID,
9445 std::move(AS), Loc);
9450bool LLParser::parseFlag(
unsigned &Val) {
9452 return tokError(
"expected integer");
9473 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9482 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9488 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9494 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9500 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9506 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9512 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9518 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9524 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9530 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9536 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9541 return error(Lex.
getLoc(),
"expected function flag type");
9556bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9560 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
9564 IdToIndexMapType IdToIndexMap;
9575 if (parseGVReference(VI, GVId))
9580 unsigned HasTailCall =
false;
9587 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
9592 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
9597 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
9601 return error(Lex.
getLoc(),
"expected hotness, relbf, or tail");
9605 return tokError(
"Expected only one of hotness or relbf");
9610 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9620 for (
auto I : IdToIndexMap) {
9621 auto &Infos = ForwardRefValueInfos[
I.first];
9622 for (
auto P :
I.second) {
9624 "Forward referenced ValueInfo expected to be empty");
9625 Infos.emplace_back(&Calls[
P.first].first,
P.second);
9642 case lltok::kw_cold:
9655 return error(Lex.
getLoc(),
"invalid call edge hotness");
9664bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
9668 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
9672 IdToIndexMapType IdToIndexMap;
9676 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
9683 if (parseGVReference(VI, GVId))
9696 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9697 VTableFuncs.push_back({
VI,
Offset});
9699 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
9705 for (
auto I : IdToIndexMap) {
9706 auto &Infos = ForwardRefValueInfos[
I.first];
9707 for (
auto P :
I.second) {
9709 "Forward referenced ValueInfo expected to be empty");
9710 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
9714 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
9721bool LLParser::parseParamNo(
uint64_t &ParamNo) {
9723 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
9729bool LLParser::parseParamAccessOffset(
ConstantRange &Range) {
9732 auto ParseAPSInt = [&](
APSInt &Val) {
9734 return tokError(
"expected integer");
9737 Val.setIsSigned(
true);
9760 IdLocListType &IdLocList) {
9769 if (parseGVReference(VI, GVId))
9773 IdLocList.emplace_back(GVId, Loc);
9776 parseParamNo(
Call.ParamNo) ||
9778 parseParamAccessOffset(
Call.Offsets))
9791 IdLocListType &IdLocList) {
9793 parseParamNo(
Param.ParamNo) ||
9795 parseParamAccessOffset(
Param.Use))
9805 if (parseParamAccessCall(Call, IdLocList))
9807 Param.Calls.push_back(Call);
9822bool LLParser::parseOptionalParamAccesses(
9823 std::vector<FunctionSummary::ParamAccess> &Params) {
9831 IdLocListType VContexts;
9832 size_t CallsNum = 0;
9835 if (parseParamAccess(ParamAccess, VContexts))
9837 CallsNum += ParamAccess.
Calls.size();
9838 assert(VContexts.size() == CallsNum);
9840 Params.emplace_back(std::move(ParamAccess));
9848 IdLocListType::const_iterator ItContext = VContexts.begin();
9849 for (
auto &PA : Params) {
9850 for (
auto &
C : PA.Calls) {
9852 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
9857 assert(ItContext == VContexts.end());
9864bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9868 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
9872 struct ValueContext {
9877 std::vector<ValueContext> VContexts;
9882 if (parseGVReference(
VC.VI,
VC.GVId))
9884 VContexts.push_back(VC);
9890 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
9891 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9894 IdToIndexMapType IdToIndexMap;
9895 for (
auto &VC : VContexts) {
9900 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.size(),
VC.Loc));
9901 Refs.push_back(
VC.VI);
9906 for (
auto I : IdToIndexMap) {
9907 auto &Infos = ForwardRefValueInfos[
I.first];
9908 for (
auto P :
I.second) {
9910 "Forward referenced ValueInfo expected to be empty");
9911 Infos.emplace_back(&Refs[
P.first],
P.second);
9925bool LLParser::parseOptionalTypeIdInfo(
9937 if (parseTypeTests(TypeIdInfo.
TypeTests))
9961 return error(Lex.
getLoc(),
"invalid typeIdInfo list type");
9965 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
9974bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9982 IdToIndexMapType IdToIndexMap;
9991 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
9993 }
else if (parseUInt64(GUID))
9995 TypeTests.push_back(GUID);
10000 for (
auto I : IdToIndexMap) {
10001 auto &Ids = ForwardRefTypeIds[
I.first];
10002 for (
auto P :
I.second) {
10003 assert(TypeTests[
P.first] == 0 &&
10004 "Forward referenced type id GUID expected to be 0");
10005 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10009 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10017bool LLParser::parseVFuncIdList(
10018 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10026 IdToIndexMapType IdToIndexMap;
10029 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10031 VFuncIdList.push_back(VFuncId);
10039 for (
auto I : IdToIndexMap) {
10040 auto &Ids = ForwardRefTypeIds[
I.first];
10041 for (
auto P :
I.second) {
10042 assert(VFuncIdList[
P.first].GUID == 0 &&
10043 "Forward referenced type id GUID expected to be 0");
10044 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10053bool LLParser::parseConstVCallList(
10055 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10063 IdToIndexMapType IdToIndexMap;
10066 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10068 ConstVCallList.push_back(ConstVCall);
10076 for (
auto I : IdToIndexMap) {
10077 auto &Ids = ForwardRefTypeIds[
I.first];
10078 for (
auto P :
I.second) {
10079 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10080 "Forward referenced type id GUID expected to be 0");
10081 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10091 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10093 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap,
Index))
10097 if (parseArgs(ConstVCall.
Args))
10110 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10125 IdToIndexMap[
ID].push_back(std::make_pair(
Index, Loc));
10127 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10129 parseUInt64(VFuncId.
GUID))
10135 parseUInt64(VFuncId.
Offset) ||
10164 assert(HasLinkage &&
"Linkage not optional in summary entry");
10171 parseOptionalVisibility(Flag);
10176 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10182 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10188 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10194 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10203 if (parseOptionalImportType(Lex.
getKind(), IK))
10205 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10209 return error(Lex.
getLoc(),
"expected gv flag type");
10231 auto ParseRest = [
this](
unsigned int &Val) {
10235 return parseFlag(Val);
10241 case lltok::kw_readonly:
10242 if (ParseRest(Flag))
10246 case lltok::kw_writeonly:
10247 if (ParseRest(Flag))
10252 if (ParseRest(Flag))
10257 if (ParseRest(Flag))
10262 return error(Lex.
getLoc(),
"expected gvar flag type");
10270bool LLParser::parseModuleReference(
StringRef &ModulePath) {
10278 auto I = ModuleIdMap.find(ModuleID);
10280 assert(
I != ModuleIdMap.end());
10281 ModulePath =
I->second;
10287bool LLParser::parseGVReference(
ValueInfo &VI,
unsigned &GVId) {
10290 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10296 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10298 VI = NumberedValueInfos[GVId];
10315bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10319 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10334 if (parseAllocType(V))
10339 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10343 std::vector<MIBInfo> MIBs;
10344 if (parseMemProfs(MIBs))
10347 Allocs.push_back({Versions, MIBs});
10364bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10368 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10374 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10383 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10392 if (parseUInt64(StackId))
10414bool LLParser::parseAllocType(uint8_t &
AllocType) {
10422 case lltok::kw_cold:
10425 case lltok::kw_hot:
10429 return error(Lex.
getLoc(),
"invalid alloc type");
10442bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10446 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10450 IdToIndexMapType IdToIndexMap;
10453 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10462 if (parseGVReference(VI, GVId))
10466 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10475 if (parseUInt32(V))
10481 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10490 if (parseUInt64(StackId))
10502 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10503 Callsites.push_back({
VI, Clones, StackIdIndices});
10511 for (
auto I : IdToIndexMap) {
10512 auto &Infos = ForwardRefValueInfos[
I.first];
10513 for (
auto P :
I.second) {
10515 "Forward referenced ValueInfo expected to be empty");
10516 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10520 if (parseToken(
lltok::rparen,
"expected ')' in callsites"))
static int64_t upperBound(StackOffset Size)
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Expand Atomic instructions
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live value
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
DenseMap< Block *, BlockRelaxAux > Blocks
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
cl::opt< bool > WriteNewDbgInfoFormat
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
bool WriteNewDbgInfoFormatToBitcode
static unsigned keywordToFPClassTest(lltok::Kind Tok)
llvm::cl::opt< bool > UseNewDbgInfoFormat
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Module.h This file contains the declarations for the Module class.
PowerPC Reduce CR logical Operation
llvm::cl::opt< bool > UseNewDbgInfoFormat
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
static SymbolRef::Type getType(const Symbol *Sym)
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Class for arbitrary precision integers.
uint64_t getZExtValue() const
Get zero extended value.
unsigned getBitWidth() const
Return the number of bits in the APInt.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
bool getBoolValue() const
Convert APInt to a boolean value.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
An arbitrary precision integer that knows its signedness.
APSInt extOrTrunc(uint32_t width) const
APSInt extend(uint32_t width) const
an instruction to allocate memory on the stack
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
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.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
An instruction that atomically checks whether a specified value is in a memory location,...
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
an instruction that atomically reads a memory location, combines it with another value,...
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Min
*p = old <signed v ? old : v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
static StringRef getOperationName(BinOp Op)
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeList removeAttribute(LLVMContext &C, unsigned Index, StringRef Kind) const
AttributeList addFnAttributes(LLVMContext &C, const AttrBuilder &B) const
Add function attribute to the list.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
AttributeList removeFnAttributes(LLVMContext &C, const AttributeMask &AttrsToRemove) const
Remove the specified attribute at the function index from this attribute list.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a binary instruction, given the opcode and the two operands.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, BasicBlock::iterator InsertBefore)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr, BasicBlock::iterator InsertBefore)
void setTailCallKind(TailCallKind TCK)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, BasicBlock::iterator InsertBefore)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB, BasicBlock::iterator InsertBefore)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static ConstantInt * getFalse(LLVMContext &Context)
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents a range of values.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
Basic type, like 'int' or 'float'.
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
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, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations)
Build a DICompositeType with the given ODR identifier.
static std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Tagged DWARF-like metadata node.
static DIFlags getFlag(StringRef Flag)
String type, Fortran CHARACTER(n)
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
Type array for a subprogram.
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
This class represents an Operation in the Expression.
static Expected< DataLayout > parse(StringRef LayoutDescription)
Parse a data layout string and return the layout.
static DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Base class for non-instruction debug metadata records that have positions within IR.
Kind
Subclass discriminator.
static DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
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 constexpr ElementCount getFixed(ScalarTy MinVal)
Lightweight error class with error context and mandatory checking.
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.
Class representing an expression and its matching format.
This instruction compares its operands according to the predicate given to the constructor.
Convenience struct for specifying and reasoning about fast-math flags.
An instruction for ordering other memory operations.
This class represents a freeze function that returns random concrete value if an operand is either a ...
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
Type::subtype_iterator param_iterator
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setPrefixData(Constant *PrefixData)
static Intrinsic::ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Generic tagged DWARF-like metadata node.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
void setComdat(Comdat *C)
void setSection(StringRef S)
Change the section for this global.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
void setDSOLocal(bool Local)
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
void setVisibility(VisibilityTypes V)
void setSanitizerMetadata(SanitizerMetadata Meta)
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e....
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
void setPartition(StringRef Part)
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, BasicBlock::iterator InsertBefore)
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
static Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr, BasicBlock::iterator InsertBefore)
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
unsigned getUIntVal() const
lltok::Kind getKind() const
bool Error(LocTy ErrorLoc, const Twine &Msg) const
const std::string & getStrVal() const
const APSInt & getAPSIntVal() const
void setIgnoreColonInIdentifiers(bool val)
const APFloat & getAPFloatVal() const
LLVMContext & getContext()
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr, BasicBlock::iterator InsertBefore)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
An instruction for reading from memory.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
static MemoryEffectsBase readOnly()
Create MemoryEffectsBase that can read any memory.
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access argument memory.
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible memory.
static MemoryEffectsBase writeOnly()
Create MemoryEffectsBase that can write any memory.
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible or argument memory.
static MemoryEffectsBase none()
Create MemoryEffectsBase that cannot read or write any memory.
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
A Module instance is used to store all the information related to an LLVM module.
void addOperand(MDNode *M)
static NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, BasicBlock::iterator InsertBefore)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Resume the propagation of an exception.
static ResumeInst * Create(Value *Exn, BasicBlock::iterator InsertBefore)
static ReturnInst * Create(LLVMContext &C, Value *retVal, BasicBlock::iterator InsertBefore)
Represents a location in source code.
static const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr, BasicBlock::iterator InsertBefore, Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
ArrayRef< int > getShuffleMask() const
static bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
iterator find(StringRef Key)
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Class to represent struct types.
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
bool containsScalableVectorType(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, BasicBlock::iterator InsertBefore)
static TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types=std::nullopt, ArrayRef< unsigned > Ints=std::nullopt)
Return a target extension type having the specified name and optional type and integer parameters.
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
static IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
TypeID
Definitions of all of the base types for the Type system.
static Type * getLabelTy(LLVMContext &C)
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isAggregateType() const
Return true if the type is an aggregate type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static IntegerType * getInt8Ty(LLVMContext &C)
static Type * getTokenTy(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVoidTy() const
Return true if this is 'void'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a unary instruction, given the opcode and an operand.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
void setName(const Twine &Name)
Change the name of the value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void deleteValue()
Delete a pointer to a generic Value.
StringRef getName() const
Return a constant reference to the value's name.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
unsigned getOperationEncoding(StringRef OperationEncodingString)
unsigned getAttributeEncoding(StringRef EncodingString)
unsigned getTag(StringRef TagString)
unsigned getCallingConvention(StringRef LanguageString)
unsigned getLanguage(StringRef LanguageString)
unsigned getVirtuality(StringRef VirtualityString)
unsigned getMacinfo(StringRef MacinfoString)
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
const CustomOperand< const MCSubtargetInfo & > Msg[]
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CXX_FAST_TLS
Used for access functions.
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
@ X86_StdCall
stdcall is mostly used by the Win32 API.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
@ X86_FastCall
'fast' analog of X86_StdCall.
bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
initializer< Ty > init(const Ty &Val)
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Linkage
Describes symbol linkage. This can be used to resolve definition clashes.
@ kw_no_sanitize_hwaddress
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_dso_local_equivalent
@ kw_aarch64_sme_preservemost_from_x2
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
void UpgradeSectionAttributes(Module &M)
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.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
bool isPointerTy(const Type *T)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
@ ArgMem
Access to memory via argument pointers.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
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.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
Implement std::hash so that hash_code can be used in STL containers.
static const fltSemantics & IEEEsingle() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToEven
static const fltSemantics & IEEEdouble() LLVM_READNONE
static const fltSemantics & IEEEhalf() LLVM_READNONE
static const fltSemantics & BFloat() LLVM_READNONE
This struct is a compact representation of a valid (non-zero power of two) alignment.
Class to accumulate and hold information about a callee.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
A specification for a virtual function call with all constant integer arguments.
std::vector< uint64_t > Args
Flags specific to function summaries.
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
Describes the use of a value in a call instruction, specifying the call's target, the value's paramet...
Describes the uses of a parameter by the function.
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
All type identifier related information.
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
An "identifier" for a virtual function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
A utility class that uses RAII to save and restore the value of a variable.
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
std::map< unsigned, Type * > Types
StringMap< Type * > NamedTypes
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
NumberedValues< GlobalValue * > GlobalValues
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
enum llvm::ValID::@36 Kind
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
Utility type to build an inheritance chain that makes it easy to rank overload candidates.