64 "Allow incomplete IR on a best effort basis (references to unknown "
65 "metadata will be dropped)"));
83 "Can't read textual IR with a Context that discards named Values");
86 if (parseTargetDefinitions(DataLayoutCallback))
96 restoreParsingState(Slots);
100 if (parseType(Ty) || parseConstantValue(Ty,
C))
103 return error(Lex.
getLoc(),
"expected end of string");
109 restoreParsingState(Slots);
118 Read =
End.getPointer() - Start.getPointer();
125 restoreParsingState(Slots);
131 bool Status = parseDIExpressionBody(Result,
false);
133 Read =
End.getPointer() - Start.getPointer();
138void LLParser::restoreParsingState(
const SlotMapping *Slots) {
145 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
146 for (
const auto &
I : Slots->
Types)
147 NumberedTypes.insert(
148 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
153 if (!isa<DbgInfoIntrinsic>(
II) &&
154 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
159 if (
auto *MV = dyn_cast<MetadataAsValue>(V))
160 if (
auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
161 if (MD->isTemporary())
165 assert(
II->use_empty() &&
"Cannot have uses");
166 II->eraseFromParent();
175void LLParser::dropUnknownMetadataReferences() {
176 auto Pred = [](
unsigned MDKind,
MDNode *
Node) {
return Node->isTemporary(); };
178 F.eraseMetadataIf(Pred);
180 I.eraseMetadataIf(Pred);
182 if (
auto *
II = dyn_cast<IntrinsicInst>(&
I))
188 GV.eraseMetadataIf(Pred);
193 if (
Info.first->getNumTemporaryUses() == 1) {
194 NumberedMetadata.erase(
ID);
195 ForwardRefMDNodes.erase(
ID);
208 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
209 "Mixed debug intrinsics/records seen without a parsing error?");
212 for (
const auto &RAG : ForwardRefAttrGroups) {
214 const std::vector<unsigned> &
Attrs = RAG.second;
217 for (
const auto &Attr : Attrs) {
218 auto R = NumberedAttrBuilders.find(Attr);
219 if (R != NumberedAttrBuilders.end())
223 if (
Function *Fn = dyn_cast<Function>(V)) {
233 Fn->setAlignment(*
A);
238 Fn->setAttributes(AS);
239 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
245 CI->setAttributes(AS);
252 II->setAttributes(AS);
253 }
else if (
CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
259 CBI->setAttributes(AS);
260 }
else if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
271 if (!ForwardRefBlockAddresses.empty())
272 return error(ForwardRefBlockAddresses.begin()->first.Loc,
273 "expected function name in blockaddress");
275 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
279 GV =
M->getNamedValue(GVRef.
StrVal);
281 GV = NumberedVals.get(GVRef.
UIntVal);
286 "' referenced by dso_local_equivalent");
290 "expected a function, alias to function, or ifunc "
291 "in dso_local_equivalent");
294 FwdRef->replaceAllUsesWith(Equiv);
295 FwdRef->eraseFromParent();
302 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
303 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
306 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
307 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
310 ForwardRefDSOLocalEquivalentIDs.clear();
311 ForwardRefDSOLocalEquivalentNames.clear();
313 for (
const auto &NT : NumberedTypes)
314 if (
NT.second.second.isValid())
316 "use of undefined type '%" +
Twine(
NT.first) +
"'");
318 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
319 NamedTypes.begin(), E = NamedTypes.end();
I != E; ++
I)
320 if (
I->second.second.isValid())
321 return error(
I->second.second,
322 "use of undefined type named '" +
I->getKey() +
"'");
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first +
"'");
344 auto *CB = dyn_cast<CallBase>(
U.getUser());
345 if (!CB || !CB->isCallee(&U))
346 return error(
Info.second,
"intrinsic can only be used as callee");
351 return error(
Info.second,
"invalid intrinsic signature");
356 Info.first->eraseFromParent();
357 ForwardRefVals.erase(
Name);
368 for (
Use &U :
V->uses()) {
369 auto *CB = dyn_cast<CallBase>(
U.getUser());
370 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
372 FTy = CB->getFunctionType();
380 Type *Ty = GetCommonFunctionType(
Info.first);
385 if (
auto *FTy = dyn_cast<FunctionType>(Ty))
391 Info.first->replaceAllUsesWith(GV);
392 Info.first->eraseFromParent();
393 ForwardRefVals.erase(
Name);
396 if (!ForwardRefVals.empty())
397 return error(ForwardRefVals.begin()->second.second,
398 "use of undefined value '@" + ForwardRefVals.begin()->first +
401 if (!ForwardRefValIDs.empty())
402 return error(ForwardRefValIDs.begin()->second.second,
403 "use of undefined value '@" +
404 Twine(ForwardRefValIDs.begin()->first) +
"'");
407 dropUnknownMetadataReferences();
409 if (!ForwardRefMDNodes.empty())
410 return error(ForwardRefMDNodes.begin()->second.second,
411 "use of undefined metadata '!" +
412 Twine(ForwardRefMDNodes.begin()->first) +
"'");
415 for (
auto &
N : NumberedMetadata) {
416 if (
N.second && !
N.second->isResolved())
417 N.second->resolveCycles();
420 for (
auto *Inst : InstsWithTBAATag) {
421 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
424 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
427 if (MD != UpgradedMD)
428 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
437 if (UpgradeDebugInfo)
451 for (
const auto &
I : NamedTypes)
452 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
453 for (
const auto &
I : NumberedTypes)
454 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
460bool LLParser::validateEndOfIndex() {
464 if (!ForwardRefValueInfos.empty())
465 return error(ForwardRefValueInfos.begin()->second.front().second,
466 "use of undefined summary '^" +
467 Twine(ForwardRefValueInfos.begin()->first) +
"'");
469 if (!ForwardRefAliasees.empty())
470 return error(ForwardRefAliasees.begin()->second.front().second,
471 "use of undefined summary '^" +
472 Twine(ForwardRefAliasees.begin()->first) +
"'");
474 if (!ForwardRefTypeIds.empty())
475 return error(ForwardRefTypeIds.begin()->second.front().second,
476 "use of undefined type id summary '^" +
477 Twine(ForwardRefTypeIds.begin()->first) +
"'");
491 std::string TentativeDLStr =
M->getDataLayoutStr();
498 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
502 if (parseSourceFileName())
511 if (
auto LayoutOverride =
512 DataLayoutCallback(
M->getTargetTriple().str(), TentativeDLStr)) {
513 TentativeDLStr = *LayoutOverride;
519 M->setDataLayout(MaybeDL.
get());
523bool LLParser::parseTopLevelEntities() {
531 if (parseSummaryEntry())
535 if (parseSourceFileName())
547 return tokError(
"expected top-level entity");
558 if (parseModuleAsm())
562 if (parseUnnamedType())
566 if (parseNamedType())
570 if (parseUnnamedGlobal())
574 if (parseNamedGlobal())
579 if (parseStandaloneMetadata())
583 if (parseSummaryEntry())
587 if (parseNamedMetadata())
591 if (parseUnnamedAttrGrp())
595 if (parseUseListOrder())
599 if (parseUseListOrderBB())
608bool LLParser::parseModuleAsm() {
614 parseStringConstant(AsmStr))
617 M->appendModuleInlineAsm(AsmStr);
624bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
630 return tokError(
"unknown target property");
633 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
634 parseStringConstant(Str))
636 M->setTargetTriple(
Triple(std::move(Str)));
640 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
643 if (parseStringConstant(TentativeDLStr))
651bool LLParser::parseSourceFileName() {
654 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
655 parseStringConstant(SourceFileName))
658 M->setSourceFileName(SourceFileName);
664bool LLParser::parseUnnamedType() {
669 if (parseToken(
lltok::equal,
"expected '=' after name") ||
674 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
677 if (!isa<StructType>(Result)) {
678 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
680 return error(TypeLoc,
"non-struct types may not be recursive");
690bool LLParser::parseNamedType() {
695 if (parseToken(
lltok::equal,
"expected '=' after name") ||
700 if (parseStructDefinition(NameLoc,
Name, NamedTypes[
Name], Result))
703 if (!isa<StructType>(Result)) {
704 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
706 return error(NameLoc,
"non-struct types may not be recursive");
716bool LLParser::parseDeclare() {
720 std::vector<std::pair<unsigned, MDNode *>> MDs;
724 if (parseMetadataAttachment(MDK,
N))
726 MDs.push_back({MDK,
N});
730 unsigned FunctionNumber = -1;
732 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
735 F->addMetadata(MD.first, *MD.second);
741bool LLParser::parseDefine() {
746 unsigned FunctionNumber = -1;
748 return parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
749 parseOptionalFunctionMetadata(*
F) ||
750 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
756bool LLParser::parseGlobalType(
bool &IsConstant) {
763 return tokError(
"expected 'global' or 'constant'");
769bool LLParser::parseOptionalUnnamedAddr(
790bool LLParser::parseUnnamedGlobal() {
798 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
802 if (parseToken(
lltok::equal,
"expected '=' after name"))
805 VarID = NumberedVals.getNext();
809 unsigned Linkage, Visibility, DLLStorageClass;
813 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
815 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
820 return parseGlobal(
Name,
VarID, NameLoc, Linkage, HasLinkage, Visibility,
821 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
824 return parseAliasOrIFunc(
Name,
VarID, NameLoc, Linkage, Visibility,
825 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
834bool LLParser::parseNamedGlobal() {
841 unsigned Linkage, Visibility, DLLStorageClass;
845 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
846 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
848 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
853 return parseGlobal(
Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
854 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
857 return parseAliasOrIFunc(
Name, -1, NameLoc, Linkage, Visibility,
858 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
862bool LLParser::parseComdat() {
872 return tokError(
"expected comdat type");
877 return tokError(
"unknown selection kind");
899 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(
Name))
900 return error(NameLoc,
"redefinition of comdat '$" +
Name +
"'");
903 if (
I != ComdatSymTab.
end())
906 C =
M->getOrInsertComdat(
Name);
907 C->setSelectionKind(SK);
914bool LLParser::parseMDString(
MDString *&Result) {
916 if (parseStringConstant(Str))
924bool LLParser::parseMDNodeID(
MDNode *&Result) {
928 if (parseUInt32(MID))
932 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
939 auto &FwdRef = ForwardRefMDNodes[MID];
942 Result = FwdRef.first.get();
943 It->second.reset(Result);
949bool LLParser::parseNamedMetadata() {
968 if (parseDIExpression(
N,
false))
974 return tokError(
"found DIArgList outside of function");
982 return parseToken(
lltok::rbrace,
"expected end of metadata node");
987bool LLParser::parseStandaloneMetadata() {
990 unsigned MetadataID = 0;
993 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
998 return tokError(
"unexpected type in metadata definition");
1002 if (parseSpecializedMDNode(
Init, IsDistinct))
1005 parseMDTuple(
Init, IsDistinct))
1009 auto FI = ForwardRefMDNodes.find(MetadataID);
1010 if (FI != ForwardRefMDNodes.end()) {
1011 auto *ToReplace = FI->second.first.get();
1014 if (isa<DIAssignID>(
Init)) {
1015 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1016 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1017 "Inst unexpectedly already has DIAssignID attachment");
1018 Inst->setMetadata(LLVMContext::MD_DIAssignID,
Init);
1022 ToReplace->replaceAllUsesWith(
Init);
1023 ForwardRefMDNodes.erase(FI);
1025 assert(NumberedMetadata[MetadataID] ==
Init &&
"Tracking VH didn't work");
1027 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1029 return tokError(
"Metadata id is already used");
1030 It->second.reset(
Init);
1037bool LLParser::skipModuleSummaryEntry() {
1047 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1048 "start of summary entry");
1050 return parseSummaryIndexFlags();
1052 return parseBlockCount();
1054 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1055 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1059 unsigned NumOpenParen = 1;
1069 return tokError(
"found end of file while parsing summary entry");
1075 }
while (NumOpenParen > 0);
1081bool LLParser::parseSummaryEntry() {
1095 return skipModuleSummaryEntry();
1097 bool result =
false;
1100 result = parseGVEntry(SummaryID);
1103 result = parseModuleEntry(SummaryID);
1106 result = parseTypeIdEntry(SummaryID);
1109 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1112 result = parseSummaryIndexFlags();
1115 result = parseBlockCount();
1118 result =
error(Lex.
getLoc(),
"unexpected summary kind");
1155bool LLParser::parseAliasOrIFunc(
const std::string &
Name,
unsigned NameID,
1156 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1157 unsigned DLLStorageClass,
bool DSOLocal,
1172 return error(NameLoc,
"invalid linkage type for alias");
1175 return error(NameLoc,
1176 "symbol with local linkage must have default visibility");
1179 return error(NameLoc,
1180 "symbol with local linkage cannot have a DLL storage class");
1184 if (parseType(Ty) ||
1185 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1194 if (parseGlobalTypeAndValue(Aliasee))
1199 if (parseValID(
ID,
nullptr))
1202 return error(AliaseeLoc,
"invalid aliasee");
1203 Aliasee =
ID.ConstantVal;
1207 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1209 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1210 unsigned AddrSpace = PTy->getAddressSpace();
1216 if (!
Name.empty()) {
1217 auto I = ForwardRefVals.find(
Name);
1218 if (
I != ForwardRefVals.end()) {
1219 GVal =
I->second.first;
1220 ForwardRefVals.erase(
Name);
1221 }
else if (
M->getNamedValue(
Name)) {
1222 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1225 auto I = ForwardRefValIDs.find(NameID);
1226 if (
I != ForwardRefValIDs.end()) {
1227 GVal =
I->second.first;
1228 ForwardRefValIDs.erase(
I);
1233 std::unique_ptr<GlobalAlias> GA;
1234 std::unique_ptr<GlobalIFunc> GI;
1262 return tokError(
"unknown alias or ifunc property!");
1267 NumberedVals.add(NameID, GV);
1274 "forward reference and definition of alias have different types");
1284 M->insertAlias(GA.release());
1286 M->insertIFunc(GI.release());
1296 case lltok::kw_sanitize_memtag:
1312 Meta.NoAddress =
true;
1315 Meta.NoHWAddress =
true;
1317 case lltok::kw_sanitize_memtag:
1321 Meta.IsDynInit =
true;
1324 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1344bool LLParser::parseGlobal(
const std::string &
Name,
unsigned NameID,
1345 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1346 unsigned Visibility,
unsigned DLLStorageClass,
1350 return error(NameLoc,
1351 "symbol with local linkage must have default visibility");
1354 return error(NameLoc,
1355 "symbol with local linkage cannot have a DLL storage class");
1359 LocTy IsExternallyInitializedLoc;
1363 if (parseOptionalAddrSpace(AddrSpace) ||
1365 IsExternallyInitialized,
1366 &IsExternallyInitializedLoc) ||
1367 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1376 if (parseGlobalValue(Ty,
Init))
1381 return error(TyLoc,
"invalid type for global variable");
1386 if (!
Name.empty()) {
1387 auto I = ForwardRefVals.find(
Name);
1388 if (
I != ForwardRefVals.end()) {
1389 GVal =
I->second.first;
1390 ForwardRefVals.erase(
I);
1391 }
else if (
M->getNamedValue(
Name)) {
1392 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1397 if (NameID == (
unsigned)-1)
1398 NameID = NumberedVals.getNext();
1400 auto I = ForwardRefValIDs.find(NameID);
1401 if (
I != ForwardRefValIDs.end()) {
1402 GVal =
I->second.first;
1403 ForwardRefValIDs.erase(
I);
1412 NumberedVals.add(NameID, GV);
1430 "forward reference and definition of global have different types");
1450 }
else if (Lex.
getKind() == lltok::kw_align) {
1452 if (parseOptionalAlignment(Alignment))
1458 if (parseOptionalCodeModel(CodeModel))
1462 if (parseGlobalObjectMetadataAttachment(*GV))
1465 if (parseSanitizer(GV))
1469 if (parseOptionalComdat(
Name,
C))
1474 return tokError(
"unknown global variable property!");
1480 std::vector<unsigned> FwdRefAttrGrps;
1481 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1483 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1485 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1493bool LLParser::parseUnnamedAttrGrp() {
1499 return tokError(
"expected attribute group id");
1502 std::vector<unsigned> unused;
1510 auto R = NumberedAttrBuilders.find(
VarID);
1511 if (R == NumberedAttrBuilders.end())
1514 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1515 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1518 if (!
R->second.hasAttributes())
1519 return error(AttrGrpLoc,
"attribute group has no attributes");
1526#define GET_ATTR_NAMES
1527#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1528 case lltok::kw_##DISPLAY_NAME: \
1529 return Attribute::ENUM_NAME;
1530#include "llvm/IR/Attributes.inc"
1539 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1542 case Attribute::Alignment: {
1551 if (parseOptionalAlignment(Alignment,
true))
1554 B.addAlignmentAttr(Alignment);
1557 case Attribute::StackAlignment: {
1562 parseUInt32(Alignment))
1565 if (parseOptionalStackAlignment(Alignment))
1568 B.addStackAlignmentAttr(Alignment);
1571 case Attribute::AllocSize: {
1572 unsigned ElemSizeArg;
1573 std::optional<unsigned> NumElemsArg;
1574 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1576 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1579 case Attribute::VScaleRange: {
1580 unsigned MinValue, MaxValue;
1581 if (parseVScaleRangeArguments(MinValue, MaxValue))
1583 B.addVScaleRangeAttr(MinValue,
1584 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1587 case Attribute::Dereferenceable: {
1589 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1591 B.addDereferenceableAttr(Bytes);
1594 case Attribute::DereferenceableOrNull: {
1596 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1598 B.addDereferenceableOrNullAttr(Bytes);
1601 case Attribute::UWTable: {
1603 if (parseOptionalUWTableKind(Kind))
1605 B.addUWTableAttr(Kind);
1608 case Attribute::AllocKind: {
1610 if (parseAllocKind(Kind))
1612 B.addAllocKindAttr(Kind);
1615 case Attribute::Memory: {
1616 std::optional<MemoryEffects> ME = parseMemoryAttr();
1619 B.addMemoryAttr(*ME);
1622 case Attribute::NoFPClass: {
1625 B.addNoFPClassAttr(NoFPClass);
1631 case Attribute::Range:
1632 return parseRangeAttr(
B);
1633 case Attribute::Initializes:
1634 return parseInitializesAttr(
B);
1635 case Attribute::Captures:
1636 return parseCapturesAttr(
B);
1638 B.addAttribute(Attr);
1646 case lltok::kw_readnone:
1649 case lltok::kw_readonly:
1652 case lltok::kw_writeonly:
1671bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1672 std::vector<unsigned> &FwdRefAttrGrps,
1673 bool InAttrGrp, LocTy &BuiltinLoc) {
1674 bool HaveError =
false;
1685 if (parseStringAttribute(
B))
1697 "cannot have an attribute group reference in an attribute group");
1707 if (Token == lltok::kw_builtin)
1719 return error(Lex.
getLoc(),
"unterminated attribute group");
1722 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1729 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1733 B.addMemoryAttr(ME);
1747 PTy->getAddressSpace());
1756 error(Loc,
"'" +
Name +
"' is not a basic block");
1758 error(Loc,
"'" +
Name +
"' defined with type '" +
1771 error(Loc,
"global variable reference must have pointer type");
1777 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1782 auto I = ForwardRefVals.find(
Name);
1783 if (
I != ForwardRefVals.end())
1784 Val =
I->second.first;
1789 return cast_or_null<GlobalValue>(
1790 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1794 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1801 error(Loc,
"global variable reference must have pointer type");
1810 auto I = ForwardRefValIDs.find(
ID);
1811 if (
I != ForwardRefValIDs.end())
1812 Val =
I->second.first;
1817 return cast_or_null<GlobalValue>(
1818 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1822 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1830Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1834 if (
I != ComdatSymTab.
end())
1839 ForwardRefComdats[
Name] = Loc;
1849bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1851 return tokError(ErrMsg);
1858bool LLParser::parseStringConstant(std::string &Result) {
1860 return tokError(
"expected string constant");
1868bool LLParser::parseUInt32(
uint32_t &Val) {
1870 return tokError(
"expected integer");
1872 if (Val64 !=
unsigned(Val64))
1873 return tokError(
"expected 32-bit integer (too large)");
1881bool LLParser::parseUInt64(
uint64_t &Val) {
1883 return tokError(
"expected integer");
1896 return tokError(
"expected localdynamic, initialexec or localexec");
1924 return parseTLSModel(TLM) ||
1925 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1933bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1934 AddrSpace = DefaultAS;
1938 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1941 if (AddrSpaceStr ==
"A") {
1942 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1943 }
else if (AddrSpaceStr ==
"G") {
1944 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1945 }
else if (AddrSpaceStr ==
"P") {
1946 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1948 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1954 return tokError(
"expected integer or string constant");
1956 if (parseUInt32(AddrSpace))
1958 if (!isUInt<24>(AddrSpace))
1959 return error(Loc,
"invalid address space, must be a 24-bit integer");
1963 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1964 ParseAddrspaceValue(AddrSpace) ||
1975 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1977 B.addAttribute(Attr, Val);
1982bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1983 bool HaveError =
false;
1990 if (parseStringAttribute(
B))
2006 if (parseEnumAttribute(Attr,
B,
false))
2010 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2012 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2060bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2061 unsigned &Visibility,
2062 unsigned &DLLStorageClass,
bool &DSOLocal) {
2066 parseOptionalDSOLocal(DSOLocal);
2067 parseOptionalVisibility(Visibility);
2068 parseOptionalDLLStorageClass(DLLStorageClass);
2071 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2077void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2099void LLParser::parseOptionalVisibility(
unsigned &Res) {
2117bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2121 return tokError(
"unknown import kind. Expect definition or declaration.");
2136void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2207bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2295 return tokError(
"unknown RISC-V ABI VLEN");
2296#define CC_VLS_CASE(ABIVlen) \
2298 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2317 return parseUInt32(CC);
2327bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2334 return parseMDNode(MD);
2339bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2342 return tokError(
"expected metadata after comma");
2346 if (parseMetadataAttachment(MDK,
N))
2349 if (MDK == LLVMContext::MD_DIAssignID)
2350 TempDIAssignIDAttachments[
N].push_back(&Inst);
2354 if (MDK == LLVMContext::MD_tbaa)
2355 InstsWithTBAATag.push_back(&Inst);
2364bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2367 if (parseMetadataAttachment(MDK,
N))
2376bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2378 if (parseGlobalObjectMetadataAttachment(
F))
2386bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2387 Alignment = std::nullopt;
2388 if (!EatIfPresent(lltok::kw_align))
2394 bool HaveParens =
false;
2400 if (parseUInt64(
Value))
2404 return error(ParenLoc,
"expected ')'");
2407 return error(AlignLoc,
"alignment is not a power of two");
2409 return error(AlignLoc,
"huge alignments are not supported yet");
2420 auto ErrMsg =
"expected global code model string";
2421 if (StrVal ==
"tiny")
2423 else if (StrVal ==
"small")
2425 else if (StrVal ==
"kernel")
2427 else if (StrVal ==
"medium")
2429 else if (StrVal ==
"large")
2432 return tokError(ErrMsg);
2443bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2445 assert((AttrKind == lltok::kw_dereferenceable ||
2446 AttrKind == lltok::kw_dereferenceable_or_null) &&
2450 if (!EatIfPresent(AttrKind))
2454 return error(ParenLoc,
"expected '('");
2456 if (parseUInt64(Bytes))
2460 return error(ParenLoc,
"expected ')'");
2462 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2466bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2477 return error(KindLoc,
"expected unwind table kind");
2486 return error(ParenLoc,
"expected '('");
2489 if (parseStringConstant(Arg))
2490 return error(KindLoc,
"expected allockind value");
2494 }
else if (
A ==
"realloc") {
2496 }
else if (
A ==
"free") {
2498 }
else if (
A ==
"uninitialized") {
2500 }
else if (
A ==
"zeroed") {
2502 }
else if (
A ==
"aligned") {
2505 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2510 return error(ParenLoc,
"expected ')'");
2512 return error(KindLoc,
"expected allockind value");
2525 return std::nullopt;
2540 return std::nullopt;
2544std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2554 tokError(
"expected '('");
2555 return std::nullopt;
2558 bool SeenLoc =
false;
2564 tokError(
"expected ':' after location");
2565 return std::nullopt;
2572 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2573 "or access kind (none, read, write, readwrite)");
2575 tokError(
"expected access kind (none, read, write, readwrite)");
2576 return std::nullopt;
2585 tokError(
"default access kind must be specified first");
2586 return std::nullopt;
2595 tokError(
"unterminated memory attribute");
2596 return std::nullopt;
2638unsigned LLParser::parseNoFPClassAttr() {
2643 tokError(
"expected '('");
2650 if (TestMask != 0) {
2654 !parseUInt64(
Value)) {
2656 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2667 error(Lex.
getLoc(),
"expected nofpclass test mask");
2685bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2686 bool &AteExtraComma) {
2687 AteExtraComma =
false;
2691 AteExtraComma =
true;
2695 if (Lex.
getKind() != lltok::kw_align)
2696 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2698 if (parseOptionalAlignment(Alignment))
2711bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2712 bool &AteExtraComma) {
2713 AteExtraComma =
false;
2717 AteExtraComma =
true;
2723 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2725 if (parseOptionalAddrSpace(AddrSpace))
2732bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2733 std::optional<unsigned> &HowManyArg) {
2736 auto StartParen = Lex.
getLoc();
2738 return error(StartParen,
"expected '('");
2740 if (parseUInt32(BaseSizeArg))
2744 auto HowManyAt = Lex.
getLoc();
2746 if (parseUInt32(HowMany))
2748 if (HowMany == BaseSizeArg)
2749 return error(HowManyAt,
2750 "'allocsize' indices can't refer to the same parameter");
2751 HowManyArg = HowMany;
2753 HowManyArg = std::nullopt;
2755 auto EndParen = Lex.
getLoc();
2757 return error(EndParen,
"expected ')'");
2761bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2762 unsigned &MaxValue) {
2765 auto StartParen = Lex.
getLoc();
2767 return error(StartParen,
"expected '('");
2769 if (parseUInt32(MinValue))
2773 if (parseUInt32(MaxValue))
2776 MaxValue = MinValue;
2778 auto EndParen = Lex.
getLoc();
2780 return error(EndParen,
"expected ')'");
2789bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2794 return parseScope(SSID) || parseOrdering(Ordering);
2804 auto StartParenAt = Lex.
getLoc();
2806 return error(StartParenAt,
"Expected '(' in syncscope");
2809 auto SSNAt = Lex.
getLoc();
2810 if (parseStringConstant(SSN))
2811 return error(SSNAt,
"Expected synchronization scope name");
2813 auto EndParenAt = Lex.
getLoc();
2815 return error(EndParenAt,
"Expected ')' in syncscope");
2830 return tokError(
"Expected ordering on atomic instruction");
2849bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2851 if (!EatIfPresent(lltok::kw_alignstack))
2855 return error(ParenLoc,
"expected '('");
2857 if (parseUInt32(Alignment))
2861 return error(ParenLoc,
"expected ')'");
2863 return error(AlignLoc,
"stack alignment is not a power of two");
2877 bool &AteExtraComma) {
2878 AteExtraComma =
false;
2881 return tokError(
"expected ',' as start of index list");
2885 if (Indices.
empty())
2886 return tokError(
"expected index");
2887 AteExtraComma =
true;
2891 if (parseUInt32(
Idx))
2904bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2908 return tokError(Msg);
2917 if (
Result->isPointerTy()) {
2919 if (parseOptionalAddrSpace(AddrSpace))
2925 return tokError(
"ptr* is invalid - use ptr instead");
2936 if (parseTargetExtType(Result))
2942 if (parseAnonStructType(Result,
false))
2948 if (parseArrayVectorType(Result,
false))
2955 if (parseAnonStructType(Result,
true) ||
2956 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2958 }
else if (parseArrayVectorType(Result,
true))
2997 if (!AllowVoid &&
Result->isVoidTy())
2998 return error(TypeLoc,
"void type only allowed for function results");
3004 return tokError(
"basic block pointers are invalid");
3006 return tokError(
"pointers to void are invalid - use i8* instead");
3008 return tokError(
"pointer to this type is invalid");
3016 return tokError(
"basic block pointers are invalid");
3018 return tokError(
"pointers to void are invalid; use i8* instead");
3020 return tokError(
"pointer to this type is invalid");
3022 if (parseOptionalAddrSpace(AddrSpace) ||
3023 parseToken(
lltok::star,
"expected '*' in address space"))
3032 if (parseFunctionType(Result))
3045 PerFunctionState &PFS,
bool IsMustTailCall,
3046 bool InVarArgsFunc) {
3052 if (!ArgList.
empty() &&
3053 parseToken(
lltok::comma,
"expected ',' in argument list"))
3058 const char *Msg =
"unexpected ellipsis in argument list for ";
3059 if (!IsMustTailCall)
3060 return tokError(
Twine(Msg) +
"non-musttail call");
3062 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
3064 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3069 Type *ArgTy =
nullptr;
3071 if (parseType(ArgTy, ArgLoc))
3074 return error(ArgLoc,
"invalid type for function argument");
3079 if (parseMetadataAsValue(V, PFS))
3083 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3090 if (IsMustTailCall && InVarArgsFunc)
3091 return tokError(
"expected '...' at end of argument list for musttail call "
3092 "in varargs function");
3103 if (!EatIfPresent(AttrToken))
3112 B.addTypeAttr(AttrKind, Ty);
3128 return tokError(
"expected integer");
3131 "integer is too large for the bit width of specified type");
3137 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3140 return error(TyLoc,
"the range must have integer type!");
3148 return tokError(
"the range represent the empty set but limits aren't 0!");
3162 auto ParseAPSInt = [&](
APInt &Val) {
3164 return tokError(
"expected integer");
3185 return tokError(
"the range should not represent the full or empty set!");
3197 if (!CRLOrNull.has_value())
3198 return tokError(
"Invalid (unordered or overlapping) range list");
3199 B.addInitializesAttr(*CRLOrNull);
3205 std::optional<CaptureComponents>
Ret;
3217 bool SeenComponent =
false;
3223 return tokError(
"duplicate 'ret' location");
3226 SeenComponent =
false;
3231 return tokError(
"cannot use 'none' with other component");
3235 return tokError(
"cannot use 'none' with other component");
3246 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3247 "'provenance' or 'read_provenance'");
3250 SeenComponent =
true;
3271bool LLParser::parseOptionalOperandBundles(
3279 if (!BundleList.
empty() &&
3280 parseToken(
lltok::comma,
"expected ',' in input list"))
3284 if (parseStringConstant(
Tag))
3287 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3290 std::vector<Value *> Inputs;
3293 if (!Inputs.empty() &&
3294 parseToken(
lltok::comma,
"expected ',' in input list"))
3298 Value *Input =
nullptr;
3302 if (parseMetadataAsValue(Input, PFS))
3304 }
else if (parseValue(Ty, Input, PFS)) {
3307 Inputs.push_back(Input);
3315 if (BundleList.
empty())
3316 return error(BeginLoc,
"operand bundle set must not be empty");
3323 unsigned NextID,
unsigned ID) {
3325 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3326 Twine(NextID) +
"' or greater");
3343 unsigned CurValID = 0;
3358 Type *ArgTy =
nullptr;
3360 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3364 return error(TypeLoc,
"argument can not have void type");
3374 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3381 CurValID = ArgID + 1;
3385 return error(TypeLoc,
"invalid type for function argument");
3393 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3398bool LLParser::parseFunctionType(
Type *&Result) {
3402 return tokError(
"invalid function return type");
3407 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3411 for (
const ArgInfo &Arg : ArgList) {
3412 if (!Arg.Name.empty())
3413 return error(Arg.Loc,
"argument name invalid in function type");
3414 if (Arg.Attrs.hasAttributes())
3415 return error(Arg.Loc,
"argument attributes invalid in function type");
3419 for (
const ArgInfo &Arg : ArgList)
3428bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3430 if (parseStructBody(Elts))
3439 std::pair<Type *, LocTy> &Entry,
3443 return error(TypeLoc,
"redefinition of type");
3454 ResultTy =
Entry.first;
3466 return error(TypeLoc,
"forward references to non-struct type");
3470 return parseArrayVectorType(ResultTy,
true);
3471 return parseType(ResultTy);
3484 if (parseStructBody(Body) ||
3485 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3489 return tokError(
toString(std::move(E)));
3516 return error(EltTyLoc,
"invalid element type for struct");
3524 return error(EltTyLoc,
"invalid element type for struct");
3529 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3538bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3539 bool Scalable =
false;
3543 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3551 return tokError(
"expected number in address space");
3557 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3561 Type *EltTy =
nullptr;
3562 if (parseType(EltTy))
3566 "expected end of sequential type"))
3571 return error(SizeLoc,
"zero element vector is illegal");
3573 return error(SizeLoc,
"size too large for vector");
3575 return error(TypeLoc,
"invalid vector element type");
3579 return error(TypeLoc,
"invalid array element type");
3596bool LLParser::parseTargetExtType(
Type *&Result) {
3601 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3602 parseStringConstant(TypeName))
3610 bool SeenInt =
false;
3617 if (parseUInt32(IntVal))
3620 }
else if (SeenInt) {
3623 return tokError(
"expected uint32 param");
3626 if (parseType(TypeParam,
true))
3632 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3637 if (
auto E = TTy.takeError())
3638 return tokError(
toString(std::move(E)));
3651 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3654 auto It = UnnamedArgNums.
begin();
3657 unsigned ArgNum = *It++;
3658 NumberedVals.add(ArgNum, &
A);
3663LLParser::PerFunctionState::~PerFunctionState() {
3666 for (
const auto &
P : ForwardRefVals) {
3667 if (isa<BasicBlock>(
P.second.first))
3669 P.second.first->replaceAllUsesWith(
3671 P.second.first->deleteValue();
3674 for (
const auto &
P : ForwardRefValIDs) {
3675 if (isa<BasicBlock>(
P.second.first))
3677 P.second.first->replaceAllUsesWith(
3679 P.second.first->deleteValue();
3683bool LLParser::PerFunctionState::finishFunction() {
3684 if (!ForwardRefVals.empty())
3685 return P.error(ForwardRefVals.begin()->second.second,
3686 "use of undefined value '%" + ForwardRefVals.begin()->first +
3688 if (!ForwardRefValIDs.empty())
3689 return P.error(ForwardRefValIDs.begin()->second.second,
3690 "use of undefined value '%" +
3691 Twine(ForwardRefValIDs.begin()->first) +
"'");
3698Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3701 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3706 auto I = ForwardRefVals.find(
Name);
3707 if (
I != ForwardRefVals.end())
3708 Val =
I->second.first;
3713 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3717 P.error(Loc,
"invalid use of a non-first-class type");
3729 P.error(Loc,
"name is too long which can result in name collisions, "
3730 "consider making the name shorter or "
3731 "increasing -non-global-value-max-name-size");
3735 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3739Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3741 Value *Val = NumberedVals.get(
ID);
3746 auto I = ForwardRefValIDs.find(
ID);
3747 if (
I != ForwardRefValIDs.end())
3748 Val =
I->second.first;
3753 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3756 P.error(Loc,
"invalid use of a non-first-class type");
3768 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3774bool LLParser::PerFunctionState::setInstName(
int NameID,
3775 const std::string &NameStr,
3779 if (NameID != -1 || !NameStr.empty())
3780 return P.error(NameLoc,
"instructions returning void cannot have a name");
3786 if (NameStr.empty()) {
3789 NameID = NumberedVals.getNext();
3791 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3795 auto FI = ForwardRefValIDs.find(NameID);
3796 if (FI != ForwardRefValIDs.end()) {
3799 return P.error(NameLoc,
"instruction forward referenced with type '" +
3803 Sentinel->replaceAllUsesWith(Inst);
3805 ForwardRefValIDs.erase(FI);
3808 NumberedVals.add(NameID, Inst);
3813 auto FI = ForwardRefVals.find(NameStr);
3814 if (FI != ForwardRefVals.end()) {
3817 return P.error(NameLoc,
"instruction forward referenced with type '" +
3821 Sentinel->replaceAllUsesWith(Inst);
3823 ForwardRefVals.erase(FI);
3829 if (Inst->
getName() != NameStr)
3830 return P.error(NameLoc,
"multiple definition of local value named '" +
3837BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3839 return dyn_cast_or_null<BasicBlock>(
3843BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3844 return dyn_cast_or_null<BasicBlock>(
3851BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3852 int NameID, LocTy Loc) {
3856 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3859 NameID = NumberedVals.getNext();
3861 BB = getBB(NameID, Loc);
3863 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3867 BB = getBB(
Name, Loc);
3869 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3880 ForwardRefValIDs.erase(NameID);
3881 NumberedVals.add(NameID, BB);
3884 ForwardRefVals.erase(
Name);
3901bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3905 return tokError(
"expected value token");
3948 if (parseGlobalValueVector(Elts) ||
3949 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3952 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3953 ID.UIntVal = Elts.
size();
3954 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3955 Elts.
size() *
sizeof(Elts[0]));
3967 if (parseGlobalValueVector(Elts) ||
3969 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3973 if (isPackedStruct) {
3974 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3975 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3976 Elts.
size() *
sizeof(Elts[0]));
3977 ID.UIntVal = Elts.
size();
3983 return error(
ID.Loc,
"constant vector must not be empty");
3985 if (!Elts[0]->
getType()->isIntegerTy() &&
3986 !Elts[0]->
getType()->isFloatingPointTy() &&
3990 "vector elements must have integer, pointer or floating point type");
3993 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3995 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3996 " is not of type '" +
4007 if (parseGlobalValueVector(Elts) ||
4019 if (!Elts[0]->
getType()->isFirstClassType())
4020 return error(FirstEltLoc,
"invalid array element type: " +
4026 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4028 return error(FirstEltLoc,
"array element #" +
Twine(i) +
4029 " is not of type '" +
4049 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4052 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4055 parseStringConstant(
ID.StrVal) ||
4056 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4061 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
4072 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4073 parseValID(Fn, PFS) ||
4075 "expected comma in block address expression") ||
4076 parseValID(Label, PFS) ||
4077 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4081 return error(Fn.
Loc,
"expected function name in blockaddress");
4083 return error(
Label.Loc,
"expected basic block name in blockaddress");
4088 GV = NumberedVals.get(Fn.
UIntVal);
4089 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4090 GV =
M->getNamedValue(Fn.
StrVal);
4095 if (!isa<Function>(GV))
4096 return error(Fn.
Loc,
"expected function name in blockaddress");
4097 F = cast<Function>(GV);
4098 if (
F->isDeclaration())
4099 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4105 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4113 "type of blockaddress must be a pointer and not '" +
4118 FwdDeclAS = PFS->getFunction().getAddressSpace();
4127 ID.ConstantVal = FwdRef;
4135 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4137 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4139 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4141 return error(
Label.Loc,
"referenced value is not a basic block");
4144 return error(
Label.Loc,
"cannot take address of numeric label after "
4145 "the function is defined");
4146 BB = dyn_cast_or_null<BasicBlock>(
4147 F->getValueSymbolTable()->lookup(
Label.StrVal));
4149 return error(
Label.Loc,
"referenced value is not a basic block");
4163 if (parseValID(Fn, PFS))
4168 "expected global value name in dso_local_equivalent");
4173 GV = NumberedVals.get(Fn.
UIntVal);
4174 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4175 GV =
M->getNamedValue(Fn.
StrVal);
4181 ? ForwardRefDSOLocalEquivalentIDs
4182 : ForwardRefDSOLocalEquivalentNames;
4190 ID.ConstantVal = FwdRef;
4196 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4197 "in dso_local_equivalent");
4208 if (parseValID(
ID, PFS))
4212 return error(
ID.Loc,
"expected global value name in no_cfi");
4223 Constant *Disc =
nullptr, *AddrDisc =
nullptr;
4226 "expected '(' in constant ptrauth expression") ||
4227 parseGlobalTypeAndValue(
Ptr) ||
4229 "expected comma in constant ptrauth expression") ||
4230 parseGlobalTypeAndValue(Key))
4234 if (parseGlobalTypeAndValue(Disc) ||
4235 (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4238 "expected ')' in constant ptrauth expression"))
4241 if (!
Ptr->getType()->isPointerTy())
4242 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4244 auto *KeyC = dyn_cast<ConstantInt>(Key);
4245 if (!KeyC || KeyC->getBitWidth() != 32)
4246 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4250 DiscC = dyn_cast<ConstantInt>(Disc);
4254 "constant ptrauth integer discriminator must be i64 constant");
4260 if (!AddrDisc->getType()->isPointerTy())
4262 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4279 Type *DestTy =
nullptr;
4282 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4283 parseGlobalTypeAndValue(SrcVal) ||
4284 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4285 parseType(DestTy) ||
4286 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4289 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4298 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4300 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4302 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4304 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4306 return error(
ID.Loc,
"urem constexprs are no longer supported");
4308 return error(
ID.Loc,
"srem constexprs are no longer supported");
4310 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4312 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4314 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4316 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4318 return error(
ID.Loc,
"frem constexprs are no longer supported");
4320 return error(
ID.Loc,
"and constexprs are no longer supported");
4322 return error(
ID.Loc,
"or constexprs are no longer supported");
4324 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4326 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4328 return error(
ID.Loc,
"shl constexprs are no longer supported");
4330 return error(
ID.Loc,
"mul constexprs are no longer supported");
4332 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4334 return error(
ID.Loc,
"select constexprs are no longer supported");
4336 return error(
ID.Loc,
"zext constexprs are no longer supported");
4338 return error(
ID.Loc,
"sext constexprs are no longer supported");
4340 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4342 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4344 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4346 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4348 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4350 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4352 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4354 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4365 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4366 Opc == Instruction::Mul) {
4375 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4376 parseGlobalTypeAndValue(Val0) ||
4377 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4378 parseGlobalTypeAndValue(Val1) ||
4379 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4382 return error(
ID.Loc,
"operands of constexpr must have same type");
4386 "constexpr requires integer or integer vector operands");
4397 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4400 if (parseGlobalTypeAndValue(
C))
4402 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4417 bool HasInRange =
false;
4423 if (
Opc == Instruction::GetElementPtr) {
4439 return tokError(
"expected integer");
4445 return tokError(
"expected integer");
4454 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4457 if (
Opc == Instruction::GetElementPtr) {
4458 if (parseType(Ty) ||
4459 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4463 if (parseGlobalValueVector(Elts) ||
4467 if (
Opc == Instruction::GetElementPtr) {
4468 if (Elts.
size() == 0 ||
4469 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4470 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4473 std::optional<ConstantRange>
InRange;
4475 unsigned IndexWidth =
4476 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4477 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4478 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4479 if (InRangeStart.
sge(InRangeEnd))
4480 return error(
ID.Loc,
"expected end to be larger than start");
4486 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4493 return error(
ID.Loc,
"getelementptr index must be an integer");
4494 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4495 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4496 if (GEPWidth && (ValNumEl != GEPWidth))
4499 "getelementptr vector index has a wrong number of elements");
4502 GEPWidth = ValNumEl;
4507 if (!Indices.empty() && !Ty->
isSized(&Visited))
4508 return error(
ID.Loc,
"base element of getelementptr must be sized");
4511 return error(
ID.Loc,
"invalid getelementptr indices");
4515 }
else if (
Opc == Instruction::ShuffleVector) {
4516 if (Elts.
size() != 3)
4517 return error(
ID.Loc,
"expected three operands to shufflevector");
4519 return error(
ID.Loc,
"invalid operands to shufflevector");
4523 }
else if (
Opc == Instruction::ExtractElement) {
4524 if (Elts.
size() != 2)
4525 return error(
ID.Loc,
"expected two operands to extractelement");
4527 return error(
ID.Loc,
"invalid extractelement operands");
4530 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4531 if (Elts.
size() != 3)
4532 return error(
ID.Loc,
"expected three operands to insertelement");
4534 return error(
ID.Loc,
"invalid insertelement operands");
4553 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4554 convertValIDToValue(Ty,
ID, V,
nullptr);
4555 if (V && !(
C = dyn_cast<Constant>(V)))
4556 return error(
ID.Loc,
"global values must be constants");
4560bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4562 return parseType(Ty) || parseGlobalValue(Ty, V);
4574 return tokError(
"expected comdat variable");
4577 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4580 if (GlobalName.
empty())
4581 return tokError(
"comdat cannot be unnamed");
4582 C = getComdat(std::string(GlobalName), KwLoc);
4605 if (parseGlobalTypeAndValue(
C))
4613bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4615 if (parseMDNodeVector(Elts))
4626bool LLParser::parseMDNode(
MDNode *&
N) {
4628 return parseSpecializedMDNode(
N);
4630 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4633bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4636 return parseMDTuple(
N);
4639 return parseMDNodeID(
N);
4645template <
class FieldTy>
struct MDFieldImpl {
4646 typedef MDFieldImpl ImplTy;
4650 void assign(FieldTy Val) {
4652 this->Val = std::move(Val);
4655 explicit MDFieldImpl(FieldTy
Default)
4663template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4664 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4675 void assign(FieldTypeA
A) {
4677 this->A = std::move(
A);
4681 void assign(FieldTypeB
B) {
4683 this->B = std::move(
B);
4687 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4689 WhatIs(IsInvalid) {}
4692struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4699struct LineField :
public MDUnsignedField {
4700 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4703struct ColumnField :
public MDUnsignedField {
4704 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4707struct DwarfTagField :
public MDUnsignedField {
4713struct DwarfMacinfoTypeField :
public MDUnsignedField {
4719struct DwarfAttEncodingField :
public MDUnsignedField {
4720 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4723struct DwarfVirtualityField :
public MDUnsignedField {
4727struct DwarfLangField :
public MDUnsignedField {
4731struct DwarfCCField :
public MDUnsignedField {
4732 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4735struct DwarfEnumKindField :
public MDUnsignedField {
4736 DwarfEnumKindField()
4741struct EmissionKindField :
public MDUnsignedField {
4742 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4745struct FixedPointKindField :
public MDUnsignedField {
4746 FixedPointKindField()
4750struct NameTableKindField :
public MDUnsignedField {
4751 NameTableKindField()
4754 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4757struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4758 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4761struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4762 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4765struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4766 MDAPSIntField() : ImplTy(
APSInt()) {}
4769struct MDSignedField :
public MDFieldImpl<int64_t> {
4773 MDSignedField(int64_t
Default = 0)
4775 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4779struct MDBoolField :
public MDFieldImpl<bool> {
4783struct MDField :
public MDFieldImpl<Metadata *> {
4786 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4789struct MDStringField :
public MDFieldImpl<MDString *> {
4790 enum class EmptyIs {
4795 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
4796 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
4799struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4803struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4807struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4808 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4809 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4811 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4812 bool AllowNull =
true)
4813 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4815 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4816 bool isMDField()
const {
return WhatIs == IsTypeB; }
4817 int64_t getMDSignedValue()
const {
4818 assert(isMDSignedField() &&
"Wrong field type");
4821 Metadata *getMDFieldValue()
const {
4822 assert(isMDField() &&
"Wrong field type");
4827struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
4829 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
4832 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
4834 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
4835 bool isMDField()
const {
return WhatIs == IsTypeB; }
4836 uint64_t getMDUnsignedValue()
const {
4837 assert(isMDUnsignedField() &&
"Wrong field type");
4840 Metadata *getMDFieldValue()
const {
4841 assert(isMDField() &&
"Wrong field type");
4846 if (isMDUnsignedField())
4850 return getMDFieldValue();
4862 return tokError(
"expected integer");
4871 MDUnsignedField &Result) {
4873 return tokError(
"expected unsigned integer");
4876 if (U.ugt(Result.Max))
4877 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4879 Result.assign(U.getZExtValue());
4880 assert(Result.Val <= Result.Max &&
"Expected value in range");
4887 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4891 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4897 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4900 return tokError(
"expected DWARF tag");
4904 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4905 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4914 DwarfMacinfoTypeField &Result) {
4916 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4919 return tokError(
"expected DWARF macinfo type");
4923 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4925 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4927 Result.assign(Macinfo);
4934 DwarfVirtualityField &Result) {
4936 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4939 return tokError(
"expected DWARF virtuality code");
4943 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4945 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4946 Result.assign(Virtuality);
4953 DwarfEnumKindField &Result) {
4955 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4958 return tokError(
"expected DWARF enum kind code");
4962 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
4964 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
4965 Result.assign(EnumKind);
4973 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4976 return tokError(
"expected DWARF language");
4980 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4982 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4983 Result.assign(Lang);
4991 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4994 return tokError(
"expected DWARF calling convention");
4998 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5000 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5008 EmissionKindField &Result) {
5010 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
5013 return tokError(
"expected emission kind");
5017 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
5019 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5020 Result.assign(*Kind);
5027 FixedPointKindField &Result) {
5029 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
5032 return tokError(
"expected fixed-point kind");
5036 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.
getStrVal() +
5038 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5039 Result.assign(*Kind);
5046 NameTableKindField &Result) {
5048 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
5051 return tokError(
"expected nameTable kind");
5055 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
5057 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5058 Result.assign((
unsigned)*Kind);
5065 DwarfAttEncodingField &Result) {
5067 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
5070 return tokError(
"expected DWARF type attribute encoding");
5074 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5076 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5077 Result.assign(Encoding);
5093 bool Res = parseUInt32(TempVal);
5099 return tokError(
"expected debug info flag");
5103 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
5118 Result.assign(Combined);
5133 bool Res = parseUInt32(TempVal);
5139 return tokError(
"expected debug info flag");
5143 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5158 Result.assign(Combined);
5165 return tokError(
"expected signed integer");
5169 return tokError(
"value for '" +
Name +
"' too small, limit is " +
5172 return tokError(
"value for '" +
Name +
"' too large, limit is " +
5174 Result.assign(S.getExtValue());
5175 assert(Result.Val >= Result.Min &&
"Expected value in range");
5176 assert(Result.Val <= Result.Max &&
"Expected value in range");
5185 return tokError(
"expected 'true' or 'false'");
5187 Result.assign(
true);
5190 Result.assign(
false);
5200 if (!Result.AllowNull)
5201 return tokError(
"'" +
Name +
"' cannot be null");
5203 Result.assign(
nullptr);
5208 if (parseMetadata(MD,
nullptr))
5217 MDSignedOrMDField &Result) {
5220 MDSignedField Res = Result.A;
5221 if (!parseMDField(Loc,
Name, Res)) {
5229 MDField Res = Result.B;
5230 if (!parseMDField(Loc,
Name, Res)) {
5240 MDUnsignedOrMDField &Result) {
5243 MDUnsignedField Res = Result.A;
5244 if (!parseMDField(Loc,
Name, Res)) {
5252 MDField Res = Result.B;
5253 if (!parseMDField(Loc,
Name, Res)) {
5265 if (parseStringConstant(S))
5269 switch (Result.EmptyIs) {
5270 case MDStringField::EmptyIs::Null:
5271 Result.assign(
nullptr);
5273 case MDStringField::EmptyIs::Empty:
5275 case MDStringField::EmptyIs::Error:
5276 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
5287 if (parseMDNodeVector(MDs))
5290 Result.assign(std::move(MDs));
5296 ChecksumKindField &Result) {
5297 std::optional<DIFile::ChecksumKind> CSKind =
5301 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
5304 Result.assign(*CSKind);
5311template <
class ParserTy>
5312bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5315 return tokError(
"expected field label here");
5324template <
class ParserTy>
5325bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5332 if (parseMDFieldsImplBody(ParseField))
5335 ClosingLoc = Lex.
getLoc();
5339template <
class FieldTy>
5340bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5342 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
5346 return parseMDField(Loc,
Name, Result);
5349bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5352#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5353 if (Lex.getStrVal() == #CLASS) \
5354 return parse##CLASS(N, IsDistinct);
5355#include "llvm/IR/Metadata.def"
5357 return tokError(
"expected metadata type");
5360#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5361#define NOP_FIELD(NAME, TYPE, INIT)
5362#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5364 return error(ClosingLoc, "missing required field '" #NAME "'");
5365#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5366 if (Lex.getStrVal() == #NAME) \
5367 return parseMDField(#NAME, NAME);
5368#define PARSE_MD_FIELDS() \
5369 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5372 if (parseMDFieldsImpl( \
5374 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5375 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5380 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5382#define GET_OR_DISTINCT(CLASS, ARGS) \
5383 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5388bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5389#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5390 OPTIONAL(line, LineField, ); \
5391 OPTIONAL(column, ColumnField, ); \
5392 REQUIRED(scope, MDField, ( false)); \
5393 OPTIONAL(inlinedAt, MDField, ); \
5394 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5395 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5396 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5398#undef VISIT_MD_FIELDS
5402 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5408bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5410 return tokError(
"missing 'distinct', required for !DIAssignID()");
5426bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5427#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5428 REQUIRED(tag, DwarfTagField, ); \
5429 OPTIONAL(header, MDStringField, ); \
5430 OPTIONAL(operands, MDFieldList, );
5432#undef VISIT_MD_FIELDS
5435 (Context, tag.Val, header.Val, operands.Val));
5444bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5445#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5446 OPTIONAL(name, MDStringField, ); \
5447 OPTIONAL(file, MDField, ); \
5448 OPTIONAL(line, LineField, ); \
5449 OPTIONAL(scope, MDField, ); \
5450 OPTIONAL(baseType, MDField, ); \
5451 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5452 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5453 OPTIONAL(flags, DIFlagField, ); \
5454 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5455 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5456 OPTIONAL(stride, MDSignedOrMDField, ); \
5457 OPTIONAL(bias, MDSignedOrMDField, );
5459#undef VISIT_MD_FIELDS
5461 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5462 if (Bound.isMDSignedField())
5465 if (Bound.isMDField())
5466 return Bound.getMDFieldValue();
5470 Metadata *LowerBound = convToMetadata(lowerBound);
5472 Metadata *Stride = convToMetadata(stride);
5473 Metadata *Bias = convToMetadata(bias);
5477 size.getValueAsMetadata(Context), align.Val, flags.Val,
5478 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5487bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5488#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5489 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5490 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5491 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5492 OPTIONAL(stride, MDSignedOrMDField, );
5494#undef VISIT_MD_FIELDS
5501 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5502 if (Bound.isMDSignedField())
5505 if (Bound.isMDField())
5506 return Bound.getMDFieldValue();
5510 Count = convToMetadata(
count);
5511 LowerBound = convToMetadata(lowerBound);
5513 Stride = convToMetadata(stride);
5516 (Context, Count, LowerBound, UpperBound, Stride));
5524bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5525#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5526 OPTIONAL(count, MDSignedOrMDField, ); \
5527 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5528 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5529 OPTIONAL(stride, MDSignedOrMDField, );
5531#undef VISIT_MD_FIELDS
5533 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5534 if (Bound.isMDSignedField())
5536 Context, {dwarf::DW_OP_consts,
5537 static_cast<uint64_t>(Bound.getMDSignedValue())});
5538 if (Bound.isMDField())
5539 return Bound.getMDFieldValue();
5544 Metadata *LowerBound = ConvToMetadata(lowerBound);
5546 Metadata *Stride = ConvToMetadata(stride);
5549 (Context, Count, LowerBound, UpperBound, Stride));
5556bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5557#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5558 REQUIRED(name, MDStringField, ); \
5559 REQUIRED(value, MDAPSIntField, ); \
5560 OPTIONAL(isUnsigned, MDBoolField, (false));
5562#undef VISIT_MD_FIELDS
5564 if (isUnsigned.Val &&
value.Val.isNegative())
5565 return tokError(
"unsigned enumerator with negative value");
5570 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())
5582bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5583#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5584 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5585 OPTIONAL(name, MDStringField, ); \
5586 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5587 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5588 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5589 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5590 OPTIONAL(flags, DIFlagField, );
5592#undef VISIT_MD_FIELDS
5595 size.getValueAsMetadata(Context),
5596 align.Val, encoding.Val,
5597 num_extra_inhabitants.Val, flags.Val));
5606bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
5607#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5608 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5609 OPTIONAL(name, MDStringField, ); \
5610 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5611 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5612 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5613 OPTIONAL(flags, DIFlagField, ); \
5614 OPTIONAL(kind, FixedPointKindField, ); \
5615 OPTIONAL(factor, MDSignedField, ); \
5616 OPTIONAL(numerator, MDAPSIntField, ); \
5617 OPTIONAL(denominator, MDAPSIntField, );
5619#undef VISIT_MD_FIELDS
5622 (Context, tag.Val,
name.Val,
5623 size.getValueAsMetadata(Context), align.Val,
5624 encoding.Val, flags.Val, kind.Val, factor.Val,
5625 numerator.Val, denominator.Val));
5631bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5632#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5633 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5634 OPTIONAL(name, MDStringField, ); \
5635 OPTIONAL(stringLength, MDField, ); \
5636 OPTIONAL(stringLengthExpression, MDField, ); \
5637 OPTIONAL(stringLocationExpression, MDField, ); \
5638 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5639 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5640 OPTIONAL(encoding, DwarfAttEncodingField, );
5642#undef VISIT_MD_FIELDS
5646 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5647 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
5648 align.Val, encoding.Val));
5661bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5662#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5663 REQUIRED(tag, DwarfTagField, ); \
5664 OPTIONAL(name, MDStringField, ); \
5665 OPTIONAL(file, MDField, ); \
5666 OPTIONAL(line, LineField, ); \
5667 OPTIONAL(scope, MDField, ); \
5668 REQUIRED(baseType, MDField, ); \
5669 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5670 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5671 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5672 OPTIONAL(flags, DIFlagField, ); \
5673 OPTIONAL(extraData, MDField, ); \
5674 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5675 OPTIONAL(annotations, MDField, ); \
5676 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5677 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5678 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5679 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5680 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5682#undef VISIT_MD_FIELDS
5684 std::optional<unsigned> DWARFAddressSpace;
5685 if (dwarfAddressSpace.Val != UINT32_MAX)
5686 DWARFAddressSpace = dwarfAddressSpace.Val;
5687 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5689 PtrAuthData.emplace(
5690 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5691 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5692 ptrAuthAuthenticatesNullValues.Val);
5696 baseType.Val,
size.getValueAsMetadata(Context), align.Val,
5697 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5698 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5702bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5703#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5704 REQUIRED(tag, DwarfTagField, ); \
5705 OPTIONAL(name, MDStringField, ); \
5706 OPTIONAL(file, MDField, ); \
5707 OPTIONAL(line, LineField, ); \
5708 OPTIONAL(scope, MDField, ); \
5709 OPTIONAL(baseType, MDField, ); \
5710 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5711 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5712 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5713 OPTIONAL(flags, DIFlagField, ); \
5714 OPTIONAL(elements, MDField, ); \
5715 OPTIONAL(runtimeLang, DwarfLangField, ); \
5716 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5717 OPTIONAL(vtableHolder, MDField, ); \
5718 OPTIONAL(templateParams, MDField, ); \
5719 OPTIONAL(identifier, MDStringField, ); \
5720 OPTIONAL(discriminator, MDField, ); \
5721 OPTIONAL(dataLocation, MDField, ); \
5722 OPTIONAL(associated, MDField, ); \
5723 OPTIONAL(allocated, MDField, ); \
5724 OPTIONAL(rank, MDSignedOrMDField, ); \
5725 OPTIONAL(annotations, MDField, ); \
5726 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5727 OPTIONAL(specification, MDField, ); \
5728 OPTIONAL(bitStride, MDField, );
5730#undef VISIT_MD_FIELDS
5733 if (
rank.isMDSignedField())
5736 else if (
rank.isMDField())
5737 Rank =
rank.getMDFieldValue();
5739 std::optional<unsigned> EnumKind;
5741 EnumKind = enumKind.Val;
5746 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5747 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
5748 align.Val, offset.getValueAsMetadata(Context), specification.Val,
5749 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
5750 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
5751 dataLocation.Val, associated.Val, allocated.Val, Rank,
5752 annotations.Val, bitStride.Val)) {
5761 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5762 size.getValueAsMetadata(Context), align.Val,
5763 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
5764 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
5765 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
5766 allocated.Val, Rank, annotations.Val, specification.Val,
5767 num_extra_inhabitants.Val, bitStride.Val));
5771bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5772#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5773 OPTIONAL(flags, DIFlagField, ); \
5774 OPTIONAL(cc, DwarfCCField, ); \
5775 REQUIRED(types, MDField, );
5777#undef VISIT_MD_FIELDS
5780 (Context, flags.Val, cc.Val, types.Val));
5789bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5793#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5794 REQUIRED(filename, MDStringField, ); \
5795 REQUIRED(directory, MDStringField, ); \
5796 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5797 OPTIONAL(checksum, MDStringField, ); \
5798 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
5800#undef VISIT_MD_FIELDS
5802 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5803 if (checksumkind.Seen && checksum.Seen)
5804 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5805 else if (checksumkind.Seen || checksum.Seen)
5806 return tokError(
"'checksumkind' and 'checksum' must be provided together");
5812 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5823bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5825 return tokError(
"missing 'distinct', required for !DICompileUnit");
5827#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5828 REQUIRED(language, DwarfLangField, ); \
5829 REQUIRED(file, MDField, ( false)); \
5830 OPTIONAL(producer, MDStringField, ); \
5831 OPTIONAL(isOptimized, MDBoolField, ); \
5832 OPTIONAL(flags, MDStringField, ); \
5833 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5834 OPTIONAL(splitDebugFilename, MDStringField, ); \
5835 OPTIONAL(emissionKind, EmissionKindField, ); \
5836 OPTIONAL(enums, MDField, ); \
5837 OPTIONAL(retainedTypes, MDField, ); \
5838 OPTIONAL(globals, MDField, ); \
5839 OPTIONAL(imports, MDField, ); \
5840 OPTIONAL(macros, MDField, ); \
5841 OPTIONAL(dwoId, MDUnsignedField, ); \
5842 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5843 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5844 OPTIONAL(nameTableKind, NameTableKindField, ); \
5845 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5846 OPTIONAL(sysroot, MDStringField, ); \
5847 OPTIONAL(sdk, MDStringField, );
5849#undef VISIT_MD_FIELDS
5852 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5853 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5854 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5855 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5856 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5869bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5871#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5872 OPTIONAL(scope, MDField, ); \
5873 OPTIONAL(name, MDStringField, ); \
5874 OPTIONAL(linkageName, MDStringField, ); \
5875 OPTIONAL(file, MDField, ); \
5876 OPTIONAL(line, LineField, ); \
5877 OPTIONAL(type, MDField, ); \
5878 OPTIONAL(isLocal, MDBoolField, ); \
5879 OPTIONAL(isDefinition, MDBoolField, (true)); \
5880 OPTIONAL(scopeLine, LineField, ); \
5881 OPTIONAL(containingType, MDField, ); \
5882 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5883 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5884 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5885 OPTIONAL(flags, DIFlagField, ); \
5886 OPTIONAL(spFlags, DISPFlagField, ); \
5887 OPTIONAL(isOptimized, MDBoolField, ); \
5888 OPTIONAL(unit, MDField, ); \
5889 OPTIONAL(templateParams, MDField, ); \
5890 OPTIONAL(declaration, MDField, ); \
5891 OPTIONAL(retainedNodes, MDField, ); \
5892 OPTIONAL(thrownTypes, MDField, ); \
5893 OPTIONAL(annotations, MDField, ); \
5894 OPTIONAL(targetFuncName, MDStringField, ); \
5895 OPTIONAL(keyInstructions, MDBoolField, );
5897#undef VISIT_MD_FIELDS
5902 spFlags.Seen ? spFlags.Val
5904 isOptimized.Val, virtuality.Val);
5905 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5908 "missing 'distinct', required for !DISubprogram that is a Definition");
5911 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5912 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5913 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5914 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5915 targetFuncName.Val, keyInstructions.Val));
5921bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5922#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5923 REQUIRED(scope, MDField, ( false)); \
5924 OPTIONAL(file, MDField, ); \
5925 OPTIONAL(line, LineField, ); \
5926 OPTIONAL(column, ColumnField, );
5928#undef VISIT_MD_FIELDS
5937bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5938#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5939 REQUIRED(scope, MDField, ( false)); \
5940 OPTIONAL(file, MDField, ); \
5941 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5943#undef VISIT_MD_FIELDS
5946 (Context, scope.Val,
file.Val, discriminator.Val));
5952bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5953#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5954 REQUIRED(scope, MDField, ); \
5955 OPTIONAL(declaration, MDField, ); \
5956 OPTIONAL(name, MDStringField, ); \
5957 OPTIONAL(file, MDField, ); \
5958 OPTIONAL(line, LineField, );
5960#undef VISIT_MD_FIELDS
5963 (Context, scope.Val, declaration.Val,
name.Val,
5964 file.Val, line.Val));
5970bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5971#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5972 REQUIRED(scope, MDField, ); \
5973 OPTIONAL(name, MDStringField, ); \
5974 OPTIONAL(exportSymbols, MDBoolField, );
5976#undef VISIT_MD_FIELDS
5979 (Context, scope.Val,
name.Val, exportSymbols.Val));
5986bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5987#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5988 REQUIRED(type, DwarfMacinfoTypeField, ); \
5989 OPTIONAL(line, LineField, ); \
5990 REQUIRED(name, MDStringField, ); \
5991 OPTIONAL(value, MDStringField, );
5993#undef VISIT_MD_FIELDS
5996 (Context, type.Val, line.Val,
name.Val,
value.Val));
6002bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6003#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6004 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6005 OPTIONAL(line, LineField, ); \
6006 REQUIRED(file, MDField, ); \
6007 OPTIONAL(nodes, MDField, );
6009#undef VISIT_MD_FIELDS
6012 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6020bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6021#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6022 REQUIRED(scope, MDField, ); \
6023 REQUIRED(name, MDStringField, ); \
6024 OPTIONAL(configMacros, MDStringField, ); \
6025 OPTIONAL(includePath, MDStringField, ); \
6026 OPTIONAL(apinotes, MDStringField, ); \
6027 OPTIONAL(file, MDField, ); \
6028 OPTIONAL(line, LineField, ); \
6029 OPTIONAL(isDecl, MDBoolField, );
6031#undef VISIT_MD_FIELDS
6034 configMacros.Val, includePath.Val,
6035 apinotes.Val, line.Val, isDecl.Val));
6041bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6042#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6043 OPTIONAL(name, MDStringField, ); \
6044 REQUIRED(type, MDField, ); \
6045 OPTIONAL(defaulted, MDBoolField, );
6047#undef VISIT_MD_FIELDS
6050 (Context,
name.Val, type.Val, defaulted.Val));
6058bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6059#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6060 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6061 OPTIONAL(name, MDStringField, ); \
6062 OPTIONAL(type, MDField, ); \
6063 OPTIONAL(defaulted, MDBoolField, ); \
6064 REQUIRED(value, MDField, );
6067#undef VISIT_MD_FIELDS
6071 (Context, tag.Val,
name.Val, type.Val, defaulted.Val,
value.Val));
6080bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6081#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6082 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6083 OPTIONAL(scope, MDField, ); \
6084 OPTIONAL(linkageName, MDStringField, ); \
6085 OPTIONAL(file, MDField, ); \
6086 OPTIONAL(line, LineField, ); \
6087 OPTIONAL(type, MDField, ); \
6088 OPTIONAL(isLocal, MDBoolField, ); \
6089 OPTIONAL(isDefinition, MDBoolField, (true)); \
6090 OPTIONAL(templateParams, MDField, ); \
6091 OPTIONAL(declaration, MDField, ); \
6092 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6093 OPTIONAL(annotations, MDField, );
6095#undef VISIT_MD_FIELDS
6099 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6100 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6101 declaration.Val, templateParams.Val, align.Val,
6113bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6114#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6115 REQUIRED(scope, MDField, ( false)); \
6116 OPTIONAL(name, MDStringField, ); \
6117 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6118 OPTIONAL(file, MDField, ); \
6119 OPTIONAL(line, LineField, ); \
6120 OPTIONAL(type, MDField, ); \
6121 OPTIONAL(flags, DIFlagField, ); \
6122 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6123 OPTIONAL(annotations, MDField, );
6125#undef VISIT_MD_FIELDS
6128 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6129 type.Val, arg.Val, flags.Val, align.Val,
6136bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6137#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6138 REQUIRED(scope, MDField, ( false)); \
6139 REQUIRED(name, MDStringField, ); \
6140 REQUIRED(file, MDField, ); \
6141 REQUIRED(line, LineField, ); \
6142 OPTIONAL(column, ColumnField, ); \
6143 OPTIONAL(isArtificial, MDBoolField, ); \
6144 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6146#undef VISIT_MD_FIELDS
6148 std::optional<unsigned> CoroSuspendIdx =
6149 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6153 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6154 column.Val, isArtificial.Val, CoroSuspendIdx));
6160bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6173 return tokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
6182 return tokError(
Twine(
"invalid DWARF attribute encoding '") +
6187 return tokError(
"expected unsigned integer");
6205bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6207 assert(Lex.
getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6210 return parseDIExpressionBody(Result, IsDistinct);
6215bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6216 assert(PFS &&
"Expected valid function state");
6227 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6229 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6241bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6243#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6244 REQUIRED(var, MDField, ); \
6245 REQUIRED(expr, MDField, );
6247#undef VISIT_MD_FIELDS
6257bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6258#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6259 OPTIONAL(name, MDStringField, ); \
6260 OPTIONAL(file, MDField, ); \
6261 OPTIONAL(line, LineField, ); \
6262 OPTIONAL(setter, MDStringField, ); \
6263 OPTIONAL(getter, MDStringField, ); \
6264 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6265 OPTIONAL(type, MDField, );
6267#undef VISIT_MD_FIELDS
6270 (Context,
name.Val,
file.Val, line.Val, setter.Val,
6271 getter.Val, attributes.Val, type.Val));
6278bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6279#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6280 REQUIRED(tag, DwarfTagField, ); \
6281 REQUIRED(scope, MDField, ); \
6282 OPTIONAL(entity, MDField, ); \
6283 OPTIONAL(file, MDField, ); \
6284 OPTIONAL(line, LineField, ); \
6285 OPTIONAL(name, MDStringField, ); \
6286 OPTIONAL(elements, MDField, );
6288#undef VISIT_MD_FIELDS
6291 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6292 line.Val,
name.Val, elements.Val));
6296#undef PARSE_MD_FIELD
6308bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6311 if (parseMetadata(MD, &PFS))
6322bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6323 PerFunctionState *PFS) {
6326 if (parseType(Ty, TypeMsg, Loc))
6329 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6332 if (parseValue(Ty, V, PFS))
6347bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6353 if (parseDIArgList(AL, PFS))
6359 if (parseSpecializedMDNode(
N)) {
6369 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6379 if (parseMDString(S))
6389 if (parseMDNodeTail(
N))
6400 PerFunctionState *PFS) {
6402 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6407 return error(
ID.Loc,
"invalid use of function-local name");
6408 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6409 return V ==
nullptr;
6412 return error(
ID.Loc,
"invalid use of function-local name");
6413 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6414 return V ==
nullptr;
6417 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6421 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6426 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6429 return V ==
nullptr;
6431 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6434 return V ==
nullptr;
6437 return error(
ID.Loc,
"integer constant must have integer type");
6439 V = ConstantInt::get(Context,
ID.APSIntVal);
6444 return error(
ID.Loc,
"floating point constant invalid for type");
6450 bool IsSNAN =
ID.APFloatVal.isSignaling();
6465 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6467 ID.APFloatVal.isNegative(), &Payload);
6470 V = ConstantFP::get(Context,
ID.APFloatVal);
6472 if (
V->getType() != Ty)
6473 return error(
ID.Loc,
"floating point constant does not have type '" +
6479 return error(
ID.Loc,
"null must be a pointer type");
6485 return error(
ID.Loc,
"invalid type for undef constant");
6489 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6490 return error(
ID.Loc,
"invalid empty array initializer");
6496 return error(
ID.Loc,
"invalid type for null constant");
6497 if (
auto *TETy = dyn_cast<TargetExtType>(Ty))
6499 return error(
ID.Loc,
"invalid type for null constant");
6504 return error(
ID.Loc,
"invalid type for none constant");
6510 return error(
ID.Loc,
"invalid type for poison constant");
6514 if (
ID.ConstantVal->getType() != Ty)
6515 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6522 return error(
ID.Loc,
"vector constant must have vector type");
6524 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6526 "' but expected '" +
6533 if (
StructType *ST = dyn_cast<StructType>(Ty)) {
6534 if (
ST->getNumElements() !=
ID.UIntVal)
6536 "initializer with struct type has wrong # elements");
6538 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6541 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6542 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6545 "element " +
Twine(i) +
6546 " of struct initializer doesn't match struct element type");
6549 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6551 return error(
ID.Loc,
"constant expression type mismatch");
6561 if (parseValID(
ID,
nullptr))
6574 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6576 assert(isa<Constant>(V) &&
"Expected a constant value");
6577 C = cast<Constant>(V);
6584 return error(Loc,
"expected a constant value");
6588bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6591 return parseValID(
ID, PFS, Ty) ||
6592 convertValIDToValue(Ty,
ID, V, PFS);
6595bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6597 return parseType(Ty) || parseValue(Ty, V, PFS);
6600bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
6601 PerFunctionState &PFS) {
6604 if (parseTypeAndValue(V, PFS))
6606 if (!isa<BasicBlock>(V))
6607 return error(Loc,
"expected a basic block");
6608 BB = cast<BasicBlock>(V);
6616 if (!
Name.starts_with(
"llvm.dbg."))
6619 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6620 FnID == Intrinsic::dbg_assign;
6628bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6629 unsigned &FunctionNumber,
6634 unsigned Visibility;
6635 unsigned DLLStorageClass;
6640 Type *RetType =
nullptr;
6642 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6644 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6645 parseType(RetType, RetTypeLoc,
true ))
6654 return error(LinkageLoc,
"invalid linkage for function definition");
6664 return error(LinkageLoc,
"invalid linkage for function declaration");
6668 return error(LinkageLoc,
"invalid function linkage type");
6672 return error(LinkageLoc,
6673 "symbol with local linkage must have default visibility");
6676 return error(LinkageLoc,
6677 "symbol with local linkage cannot have a DLL storage class");
6680 return error(RetTypeLoc,
"invalid function return type");
6684 std::string FunctionName;
6689 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6693 return tokError(
"expected function name");
6699 return tokError(
"expected '(' in function argument list");
6704 std::vector<unsigned> FwdRefAttrGrps;
6707 std::string Partition;
6711 unsigned AddrSpace = 0;
6717 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6718 parseOptionalUnnamedAddr(UnnamedAddr) ||
6719 parseOptionalProgramAddrSpace(AddrSpace) ||
6720 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6724 parseOptionalComdat(FunctionName,
C) ||
6725 parseOptionalAlignment(Alignment) ||
6726 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6730 parseGlobalTypeAndValue(PersonalityFn)))
6733 if (FuncAttrs.contains(Attribute::Builtin))
6734 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6739 FuncAttrs.removeAttribute(Attribute::Alignment);
6744 std::vector<Type*> ParamTypeList;
6747 for (
const ArgInfo &Arg : ArgList) {
6748 ParamTypeList.push_back(Arg.Ty);
6749 Attrs.push_back(Arg.Attrs);
6757 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6764 if (!FunctionName.empty()) {
6767 auto FRVI = ForwardRefVals.find(FunctionName);
6768 if (FRVI != ForwardRefVals.end()) {
6769 FwdFn = FRVI->second.first;
6771 return error(FRVI->second.second,
6772 "invalid forward reference to "
6775 "' with wrong type: "
6779 ForwardRefVals.erase(FRVI);
6780 }
else if ((Fn =
M->getFunction(FunctionName))) {
6782 return error(NameLoc,
6783 "invalid redefinition of function '" + FunctionName +
"'");
6784 }
else if (
M->getNamedValue(FunctionName)) {
6785 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6791 if (FunctionNumber == (
unsigned)-1)
6792 FunctionNumber = NumberedVals.getNext();
6796 auto I = ForwardRefValIDs.find(FunctionNumber);
6797 if (
I != ForwardRefValIDs.end()) {
6798 FwdFn =
I->second.first;
6800 return error(NameLoc,
"type of definition and forward reference of '@" +
6801 Twine(FunctionNumber) +
6806 ForwardRefValIDs.erase(
I);
6815 if (FunctionName.empty())
6816 NumberedVals.add(FunctionNumber, Fn);
6831 if (!
GC.empty()) Fn->
setGC(GC);
6834 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6838 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6840 if (ArgList[i].
Name.empty())
continue;
6845 if (ArgIt->
getName() != ArgList[i].Name)
6846 return error(ArgList[i].Loc,
6847 "redefinition of argument '%" + ArgList[i].
Name +
"'");
6860 if (FunctionName.empty()) {
6862 ID.UIntVal = FunctionNumber;
6865 ID.StrVal = FunctionName;
6867 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6868 if (
Blocks != ForwardRefBlockAddresses.end())
6870 "cannot take blockaddress inside a declaration");
6874bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6876 if (FunctionNumber == -1) {
6878 ID.StrVal = std::string(
F.getName());
6881 ID.UIntVal = FunctionNumber;
6884 auto Blocks =
P.ForwardRefBlockAddresses.find(
ID);
6885 if (
Blocks ==
P.ForwardRefBlockAddresses.end())
6888 for (
const auto &
I :
Blocks->second) {
6889 const ValID &BBID =
I.first;
6893 "Expected local id or name");
6900 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6911 P.ForwardRefBlockAddresses.erase(
Blocks);
6917bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
6920 return tokError(
"expected '{' in function body");
6923 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6927 if (PFS.resolveForwardRefBlockAddresses())
6933 return tokError(
"function body requires at least one basic block");
6937 if (parseBasicBlock(PFS))
6941 if (parseUseListOrder(&PFS))
6948 return PFS.finishFunction();
6953bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6970 std::string NameStr;
6975 auto DeleteDbgRecord = [](
DbgRecord *DR) { DR->deleteRecord(); };
6976 using DbgRecordPtr = std::unique_ptr<
DbgRecord,
decltype(DeleteDbgRecord)>;
6983 if (SeenOldDbgInfoFormat)
6984 return error(Lex.
getLoc(),
"debug record should not appear in a module "
6985 "containing debug info intrinsics");
6986 SeenNewDbgInfoFormat =
true;
6990 if (parseDebugRecord(DR, PFS))
6992 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7004 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7009 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7013 switch (parseInstruction(Inst, BB, PFS)) {
7016 case InstError:
return true;
7023 if (parseInstructionMetadata(*Inst))
7026 case InstExtraComma:
7031 if (parseInstructionMetadata(*Inst))
7037 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7041 for (DbgRecordPtr &DR : TrailingDbgRecord)
7043 TrailingDbgRecord.clear();
7046 assert(TrailingDbgRecord.empty() &&
7047 "All debug values should have been attached to an instruction.");
7056bool LLParser::parseDebugRecord(
DbgRecord *&DR, PerFunctionState &PFS) {
7061 return error(DVRLoc,
"expected debug record type here");
7063 .
Case(
"declare", RecordKind::ValueKind)
7064 .
Case(
"value", RecordKind::ValueKind)
7065 .
Case(
"assign", RecordKind::ValueKind)
7066 .
Case(
"label", RecordKind::LabelKind);
7075 if (parseMDNode(Label))
7080 if (parseMDNode(DbgLoc))
7089 .
Case(
"declare", LocType::Declare)
7090 .
Case(
"value", LocType::Value)
7091 .
Case(
"assign", LocType::Assign);
7099 if (parseMetadata(ValLocMD, &PFS))
7106 if (parseMDNode(Variable))
7119 MDNode *AssignID =
nullptr;
7120 Metadata *AddressLocation =
nullptr;
7121 MDNode *AddressExpression =
nullptr;
7124 if (parseMDNode(AssignID))
7130 if (parseMetadata(AddressLocation, &PFS))
7136 if (parseMDNode(AddressExpression))
7161 PerFunctionState &PFS) {
7164 return tokError(
"found end of file when expecting more instructions");
7171 return error(Loc,
"expected instruction opcode");
7175 return parseRet(Inst, BB, PFS);
7177 return parseBr(Inst, PFS);
7179 return parseSwitch(Inst, PFS);
7181 return parseIndirectBr(Inst, PFS);
7183 return parseInvoke(Inst, PFS);
7185 return parseResume(Inst, PFS);
7187 return parseCleanupRet(Inst, PFS);
7189 return parseCatchRet(Inst, PFS);
7191 return parseCatchSwitch(Inst, PFS);
7193 return parseCatchPad(Inst, PFS);
7195 return parseCleanupPad(Inst, PFS);
7197 return parseCallBr(Inst, PFS);
7201 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7217 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7220 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
7221 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
7230 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7244 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7246 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
7252 return parseArithmetic(Inst, PFS, KeywordVal,
7256 if (parseLogical(Inst, PFS, KeywordVal))
7259 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(
true);
7264 return parseLogical(Inst, PFS, KeywordVal);
7267 if (parseCompare(Inst, PFS, KeywordVal))
7270 cast<ICmpInst>(Inst)->setSameSign();
7275 int Res = parseCompare(Inst, PFS, KeywordVal);
7287 bool Res = parseCast(Inst, PFS, KeywordVal);
7299 if (parseCast(Inst, PFS, KeywordVal))
7302 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(
true);
7304 cast<TruncInst>(Inst)->setHasNoSignedWrap(
true);
7316 return parseCast(Inst, PFS, KeywordVal);
7320 if (parseCast(Inst, PFS, KeywordVal))
7330 int Res = parseSelect(Inst, PFS);
7334 if (!isa<FPMathOperator>(Inst))
7335 return error(Loc,
"fast-math-flags specified for select without "
7336 "floating-point scalar or vector return type");
7342 return parseVAArg(Inst, PFS);
7344 return parseExtractElement(Inst, PFS);
7346 return parseInsertElement(Inst, PFS);
7348 return parseShuffleVector(Inst, PFS);
7351 int Res = parsePHI(Inst, PFS);
7355 if (!isa<FPMathOperator>(Inst))
7356 return error(Loc,
"fast-math-flags specified for phi without "
7357 "floating-point scalar or vector return type");
7363 return parseLandingPad(Inst, PFS);
7365 return parseFreeze(Inst, PFS);
7377 return parseAlloc(Inst, PFS);
7379 return parseLoad(Inst, PFS);
7381 return parseStore(Inst, PFS);
7383 return parseCmpXchg(Inst, PFS);
7385 return parseAtomicRMW(Inst, PFS);
7387 return parseFence(Inst, PFS);
7389 return parseGetElementPtr(Inst, PFS);
7391 return parseExtractValue(Inst, PFS);
7393 return parseInsertValue(Inst, PFS);
7398bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7399 if (
Opc == Instruction::FCmp) {
7402 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7423 return tokError(
"expected icmp predicate (e.g. 'eq')");
7448 PerFunctionState &PFS) {
7451 if (parseType(Ty,
true ))
7454 Type *ResType = PFS.getFunction().getReturnType();
7458 return error(TypeLoc,
"value doesn't match function result type '" +
7466 if (parseValue(Ty, RV, PFS))
7470 return error(TypeLoc,
"value doesn't match function result type '" +
7480bool LLParser::parseBr(
Instruction *&Inst, PerFunctionState &PFS) {
7484 if (parseTypeAndValue(Op0, Loc, PFS))
7487 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7493 return error(Loc,
"branch condition must have 'i1' type");
7495 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7496 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7497 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7498 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7510bool LLParser::parseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7511 LocTy CondLoc, BBLoc;
7514 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7515 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7516 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7520 if (!
Cond->getType()->isIntegerTy())
7521 return error(CondLoc,
"switch condition must have integer type");
7530 if (parseTypeAndValue(
Constant, CondLoc, PFS) ||
7531 parseToken(
lltok::comma,
"expected ',' after case value") ||
7532 parseTypeAndBasicBlock(DestBB, PFS))
7536 return error(CondLoc,
"duplicate case value in switch");
7538 return error(CondLoc,
"case value is not a constant integer");
7546 for (
const auto &[OnVal, Dest] : Table)
7547 SI->addCase(OnVal, Dest);
7555bool LLParser::parseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
7558 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7559 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7563 if (!
Address->getType()->isPointerTy())
7564 return error(AddrLoc,
"indirectbr address must have pointer type");
7571 if (parseTypeAndBasicBlock(DestBB, PFS))
7576 if (parseTypeAndBasicBlock(DestBB, PFS))
7582 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7597 FuncTy = dyn_cast<FunctionType>(RetType);
7602 for (
const ParamInfo &Arg : ArgList)
7616bool LLParser::parseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
7618 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7619 std::vector<unsigned> FwdRefAttrGrps;
7622 unsigned InvokeAddrSpace;
7623 Type *RetType =
nullptr;
7630 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7631 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7632 parseType(RetType, RetTypeLoc,
true ) ||
7633 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7634 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7636 parseOptionalOperandBundles(BundleList, PFS) ||
7638 parseTypeAndBasicBlock(NormalBB, PFS) ||
7640 parseTypeAndBasicBlock(UnwindBB, PFS))
7647 if (resolveFunctionType(RetType, ArgList, Ty))
7648 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7654 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
7666 for (
const ParamInfo &Arg : ArgList) {
7667 Type *ExpectedTy =
nullptr;
7670 }
else if (!Ty->isVarArg()) {
7671 return error(Arg.Loc,
"too many arguments specified");
7674 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7675 return error(Arg.Loc,
"argument is not of expected type '" +
7677 Args.push_back(Arg.V);
7682 return error(CallLoc,
"not enough parameters specified for call");
7691 II->setCallingConv(CC);
7692 II->setAttributes(PAL);
7693 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
7700bool LLParser::parseResume(
Instruction *&Inst, PerFunctionState &PFS) {
7702 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7711 PerFunctionState &PFS) {
7712 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7717 if (!
Args.empty() &&
7718 parseToken(
lltok::comma,
"expected ',' in argument list"))
7723 Type *ArgTy =
nullptr;
7724 if (parseType(ArgTy, ArgLoc))
7729 if (parseMetadataAsValue(V, PFS))
7732 if (parseValue(ArgTy, V, PFS))
7744bool LLParser::parseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
7745 Value *CleanupPad =
nullptr;
7747 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7762 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7773bool LLParser::parseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
7774 Value *CatchPad =
nullptr;
7776 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7783 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7784 parseTypeAndBasicBlock(BB, PFS))
7793bool LLParser::parseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7801 return tokError(
"expected scope value for catchswitch");
7806 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7812 if (parseTypeAndBasicBlock(DestBB, PFS))
7817 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7820 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7828 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7835 CatchSwitch->addHandler(DestBB);
7842bool LLParser::parseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
7843 Value *CatchSwitch =
nullptr;
7849 return tokError(
"expected scope value for catchpad");
7855 if (parseExceptionArgs(Args, PFS))
7864bool LLParser::parseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
7865 Value *ParentPad =
nullptr;
7872 return tokError(
"expected scope value for cleanuppad");
7878 if (parseExceptionArgs(Args, PFS))
7894bool LLParser::parseUnaryOp(
Instruction *&Inst, PerFunctionState &PFS,
7895 unsigned Opc,
bool IsFP) {
7897 if (parseTypeAndValue(LHS, Loc, PFS))
7904 return error(Loc,
"invalid operand type for instruction");
7914bool LLParser::parseCallBr(
Instruction *&Inst, PerFunctionState &PFS) {
7916 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7917 std::vector<unsigned> FwdRefAttrGrps;
7920 Type *RetType =
nullptr;
7927 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7928 parseType(RetType, RetTypeLoc,
true ) ||
7929 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7930 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7932 parseOptionalOperandBundles(BundleList, PFS) ||
7934 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7943 if (parseTypeAndBasicBlock(DestBB, PFS))
7948 if (parseTypeAndBasicBlock(DestBB, PFS))
7954 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7961 if (resolveFunctionType(RetType, ArgList, Ty))
7962 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7980 for (
const ParamInfo &Arg : ArgList) {
7981 Type *ExpectedTy =
nullptr;
7984 }
else if (!Ty->isVarArg()) {
7985 return error(Arg.Loc,
"too many arguments specified");
7988 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7989 return error(Arg.Loc,
"argument is not of expected type '" +
7991 Args.push_back(Arg.V);
7996 return error(CallLoc,
"not enough parameters specified for call");
8008 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8022bool LLParser::parseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
8023 unsigned Opc,
bool IsFP) {
8025 if (parseTypeAndValue(LHS, Loc, PFS) ||
8026 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8034 return error(Loc,
"invalid operand type for instruction");
8042bool LLParser::parseLogical(
Instruction *&Inst, PerFunctionState &PFS,
8045 if (parseTypeAndValue(LHS, Loc, PFS) ||
8046 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8052 "instruction requires integer or integer vector operands");
8061bool LLParser::parseCompare(
Instruction *&Inst, PerFunctionState &PFS,
8067 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8068 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8072 if (
Opc == Instruction::FCmp) {
8074 return error(Loc,
"fcmp requires floating point operands");
8077 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8080 return error(Loc,
"icmp requires integer operands");
8092bool LLParser::parseCast(
Instruction *&Inst, PerFunctionState &PFS,
8096 Type *DestTy =
nullptr;
8097 if (parseTypeAndValue(
Op, Loc, PFS) ||
8098 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8103 return error(Loc,
"invalid cast opcode for cast from '" +
8112bool LLParser::parseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
8114 Value *Op0, *Op1, *Op2;
8115 if (parseTypeAndValue(Op0, Loc, PFS) ||
8116 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8117 parseTypeAndValue(Op1, PFS) ||
8118 parseToken(
lltok::comma,
"expected ',' after select value") ||
8119 parseTypeAndValue(Op2, PFS))
8123 return error(Loc, Reason);
8131bool LLParser::parseVAArg(
Instruction *&Inst, PerFunctionState &PFS) {
8133 Type *EltTy =
nullptr;
8135 if (parseTypeAndValue(
Op, PFS) ||
8136 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8137 parseType(EltTy, TypeLoc))
8141 return error(TypeLoc,
"va_arg requires operand with first class type");
8149bool LLParser::parseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
8152 if (parseTypeAndValue(Op0, Loc, PFS) ||
8153 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8154 parseTypeAndValue(Op1, PFS))
8158 return error(Loc,
"invalid extractelement operands");
8166bool LLParser::parseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
8168 Value *Op0, *Op1, *Op2;
8169 if (parseTypeAndValue(Op0, Loc, PFS) ||
8170 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8171 parseTypeAndValue(Op1, PFS) ||
8172 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8173 parseTypeAndValue(Op2, PFS))
8177 return error(Loc,
"invalid insertelement operands");
8185bool LLParser::parseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
8187 Value *Op0, *Op1, *Op2;
8188 if (parseTypeAndValue(Op0, Loc, PFS) ||
8189 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8190 parseTypeAndValue(Op1, PFS) ||
8191 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8192 parseTypeAndValue(Op2, PFS))
8196 return error(Loc,
"invalid shufflevector operands");
8204int LLParser::parsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
8208 if (parseType(Ty, TypeLoc))
8212 return error(TypeLoc,
"phi node must have first class type");
8215 bool AteExtraComma =
false;
8227 AteExtraComma =
true;
8231 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8232 parseValue(Ty, Op0, PFS) ||
8233 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8238 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8242 for (
const auto &[Val, BB] : PHIVals)
8245 return AteExtraComma ? InstExtraComma : InstNormal;
8254bool LLParser::parseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
8257 if (parseType(Ty, TyLoc))
8270 return tokError(
"expected 'catch' or 'filter' clause type");
8274 if (parseTypeAndValue(V, VLoc, PFS))
8280 if (isa<ArrayType>(
V->getType()))
8281 return error(VLoc,
"'catch' clause has an invalid type");
8283 if (!isa<ArrayType>(
V->getType()))
8284 return error(VLoc,
"'filter' clause has an invalid type");
8287 Constant *CV = dyn_cast<Constant>(V);
8289 return error(VLoc,
"clause argument must be a constant");
8293 Inst = LP.release();
8299bool LLParser::parseFreeze(
Instruction *&Inst, PerFunctionState &PFS) {
8302 if (parseTypeAndValue(
Op, Loc, PFS))
8318bool LLParser::parseCall(
Instruction *&Inst, PerFunctionState &PFS,
8320 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
8321 std::vector<unsigned> FwdRefAttrGrps;
8323 unsigned CallAddrSpace;
8325 Type *RetType =
nullptr;
8334 "expected 'tail call', 'musttail call', or 'notail call'"))
8339 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8340 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8341 parseType(RetType, RetTypeLoc,
true ) ||
8342 parseValID(CalleeID, &PFS) ||
8344 PFS.getFunction().isVarArg()) ||
8345 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8346 parseOptionalOperandBundles(BundleList, PFS))
8353 if (resolveFunctionType(RetType, ArgList, Ty))
8354 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8360 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
8373 for (
const ParamInfo &Arg : ArgList) {
8374 Type *ExpectedTy =
nullptr;
8377 }
else if (!Ty->isVarArg()) {
8378 return error(Arg.Loc,
"too many arguments specified");
8381 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8382 return error(Arg.Loc,
"argument is not of expected type '" +
8384 Args.push_back(Arg.V);
8385 Attrs.push_back(Arg.Attrs);
8389 return error(CallLoc,
"not enough parameters specified for call");
8400 if (!isa<FPMathOperator>(CI)) {
8402 return error(CallLoc,
"fast-math-flags specified for call without "
8403 "floating-point scalar or vector return type");
8410 if (SeenNewDbgInfoFormat) {
8412 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8413 "using non-intrinsic debug info");
8415 SeenOldDbgInfoFormat =
true;
8418 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8430int LLParser::parseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
8432 LocTy SizeLoc, TyLoc, ASLoc;
8434 unsigned AddrSpace = 0;
8437 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8438 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8440 if (parseType(Ty, TyLoc))
8444 return error(TyLoc,
"invalid type for alloca");
8446 bool AteExtraComma =
false;
8448 if (Lex.
getKind() == lltok::kw_align) {
8449 if (parseOptionalAlignment(Alignment))
8451 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8455 if (parseOptionalAddrSpace(AddrSpace))
8458 AteExtraComma =
true;
8460 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8463 if (Lex.
getKind() == lltok::kw_align) {
8464 if (parseOptionalAlignment(Alignment))
8466 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8470 if (parseOptionalAddrSpace(AddrSpace))
8473 AteExtraComma =
true;
8479 if (
Size && !
Size->getType()->isIntegerTy())
8480 return error(SizeLoc,
"element count must have integer type");
8483 if (!Alignment && !Ty->
isSized(&Visited))
8484 return error(TyLoc,
"Cannot allocate unsized type");
8486 Alignment =
M->getDataLayout().getPrefTypeAlign(Ty);
8491 return AteExtraComma ? InstExtraComma : InstNormal;
8498int LLParser::parseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
8501 bool AteExtraComma =
false;
8502 bool isAtomic =
false;
8511 bool isVolatile =
false;
8519 if (parseType(Ty) ||
8520 parseToken(
lltok::comma,
"expected comma after load's type") ||
8521 parseTypeAndValue(Val, Loc, PFS) ||
8522 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8523 parseOptionalCommaAlign(Alignment, AteExtraComma))
8527 return error(Loc,
"load operand must be a pointer to a first class type");
8528 if (isAtomic && !Alignment)
8529 return error(Loc,
"atomic load must have explicit non-zero alignment");
8532 return error(Loc,
"atomic load cannot use Release ordering");
8535 if (!Alignment && !Ty->
isSized(&Visited))
8536 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8538 Alignment =
M->getDataLayout().getABITypeAlign(Ty);
8539 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8540 return AteExtraComma ? InstExtraComma : InstNormal;
8548int LLParser::parseStore(
Instruction *&Inst, PerFunctionState &PFS) {
8551 bool AteExtraComma =
false;
8552 bool isAtomic =
false;
8561 bool isVolatile =
false;
8567 if (parseTypeAndValue(Val, Loc, PFS) ||
8568 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8569 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8570 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8571 parseOptionalCommaAlign(Alignment, AteExtraComma))
8574 if (!
Ptr->getType()->isPointerTy())
8575 return error(PtrLoc,
"store operand must be a pointer");
8577 return error(Loc,
"store operand must be a first class value");
8578 if (isAtomic && !Alignment)
8579 return error(Loc,
"atomic store must have explicit non-zero alignment");
8582 return error(Loc,
"atomic store cannot use Acquire ordering");
8585 return error(Loc,
"storing unsized types is not allowed");
8587 Alignment =
M->getDataLayout().getABITypeAlign(Val->
getType());
8589 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8590 return AteExtraComma ? InstExtraComma : InstNormal;
8597int LLParser::parseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
8599 bool AteExtraComma =
false;
8603 bool isVolatile =
false;
8604 bool isWeak =
false;
8613 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8614 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8615 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8616 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8617 parseTypeAndValue(New, NewLoc, PFS) ||
8618 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8619 parseOrdering(FailureOrdering) ||
8620 parseOptionalCommaAlign(Alignment, AteExtraComma))
8624 return tokError(
"invalid cmpxchg success ordering");
8626 return tokError(
"invalid cmpxchg failure ordering");
8627 if (!
Ptr->getType()->isPointerTy())
8628 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8629 if (
Cmp->getType() !=
New->getType())
8630 return error(NewLoc,
"compare value and new value type do not match");
8631 if (!
New->getType()->isFirstClassType())
8632 return error(NewLoc,
"cmpxchg operand must be a first class value");
8634 const Align DefaultAlignment(
8635 PFS.getFunction().getDataLayout().getTypeStoreSize(
8640 SuccessOrdering, FailureOrdering, SSID);
8645 return AteExtraComma ? InstExtraComma : InstNormal;
8651int LLParser::parseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
8653 bool AteExtraComma =
false;
8656 bool isVolatile =
false;
8666 return tokError(
"expected binary operation in atomicrmw");
8717 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8718 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8719 parseTypeAndValue(Val, ValLoc, PFS) ||
8720 parseScopeAndOrdering(
true , SSID, Ordering) ||
8721 parseOptionalCommaAlign(Alignment, AteExtraComma))
8725 return tokError(
"atomicrmw cannot be unordered");
8726 if (!
Ptr->getType()->isPointerTy())
8727 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8729 return error(ValLoc,
"atomicrmw operand may not be scalable");
8738 " operand must be an integer, floating point, or pointer type");
8742 return error(ValLoc,
"atomicrmw " +
8744 " operand must be a floating point type");
8748 return error(ValLoc,
"atomicrmw " +
8750 " operand must be an integer");
8755 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8758 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8760 const Align DefaultAlignment(
8761 PFS.getFunction().getDataLayout().getTypeStoreSize(
8765 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8768 return AteExtraComma ? InstExtraComma : InstNormal;
8773int LLParser::parseFence(
Instruction *&Inst, PerFunctionState &PFS) {
8776 if (parseScopeAndOrdering(
true , SSID, Ordering))
8780 return tokError(
"fence cannot be unordered");
8782 return tokError(
"fence cannot be monotonic");
8784 Inst =
new FenceInst(Context, Ordering, SSID);
8790int LLParser::parseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
8792 Value *Val =
nullptr;
8808 if (parseType(Ty) ||
8809 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8810 parseTypeAndValue(
Ptr, Loc, PFS))
8815 if (!BasePointerType)
8816 return error(Loc,
"base of getelementptr must be a pointer");
8819 bool AteExtraComma =
false;
8823 ? cast<VectorType>(
BaseType)->getElementCount()
8828 AteExtraComma =
true;
8831 if (parseTypeAndValue(Val, EltLoc, PFS))
8834 return error(EltLoc,
"getelementptr index must be an integer");
8836 if (
auto *ValVTy = dyn_cast<VectorType>(Val->
getType())) {
8841 "getelementptr vector index has a wrong number of elements");
8842 GEPWidth = ValNumEl;
8849 return error(Loc,
"base element of getelementptr must be sized");
8851 auto *STy = dyn_cast<StructType>(Ty);
8853 return error(Loc,
"getelementptr cannot target structure that contains "
8854 "scalable vector type");
8857 return error(Loc,
"invalid getelementptr indices");
8860 GEP->setNoWrapFlags(NW);
8861 return AteExtraComma ? InstExtraComma : InstNormal;
8866int LLParser::parseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
8870 if (parseTypeAndValue(Val, Loc, PFS) ||
8871 parseIndexList(Indices, AteExtraComma))
8875 return error(Loc,
"extractvalue operand must be aggregate type");
8878 return error(Loc,
"invalid indices for extractvalue");
8880 return AteExtraComma ? InstExtraComma : InstNormal;
8885int LLParser::parseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
8889 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8890 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8891 parseTypeAndValue(Val1, Loc1, PFS) ||
8892 parseIndexList(Indices, AteExtraComma))
8896 return error(Loc0,
"insertvalue operand must be aggregate type");
8900 return error(Loc0,
"invalid indices for insertvalue");
8901 if (IndexedType != Val1->
getType())
8902 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8906 return AteExtraComma ? InstExtraComma : InstNormal;
8932 if (parseMetadata(MD,
nullptr))
8937 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8945 if (!
V->hasUseList())
8948 return error(Loc,
"value has no uses");
8950 unsigned NumUses = 0;
8952 for (
const Use &U :
V->uses()) {
8953 if (++NumUses > Indexes.
size())
8955 Order[&
U] = Indexes[NumUses - 1];
8958 return error(Loc,
"value only has one use");
8959 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8961 "wrong number of indexes, expected " +
Twine(
V->getNumUses()));
8963 V->sortUseList([&](
const Use &L,
const Use &R) {
8976 return tokError(
"expected non-empty list of uselistorder indexes");
8983 bool IsOrdered =
true;
8984 assert(Indexes.
empty() &&
"Expected empty order vector");
8987 if (parseUInt32(Index))
8992 Max = std::max(Max, Index);
9001 if (Indexes.
size() < 2)
9002 return error(Loc,
"expected >= 2 uselistorder indexes");
9005 "expected distinct uselistorder indexes in range [0, size)");
9007 return error(Loc,
"expected uselistorder indexes to change the order");
9014bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9021 if (parseTypeAndValue(V, PFS) ||
9022 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9023 parseUseListOrderIndexes(Indexes))
9026 return sortUseListOrder(V, Indexes, Loc);
9031bool LLParser::parseUseListOrderBB() {
9038 if (parseValID(Fn,
nullptr) ||
9039 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9040 parseValID(Label,
nullptr) ||
9041 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9042 parseUseListOrderIndexes(Indexes))
9048 GV =
M->getNamedValue(Fn.
StrVal);
9050 GV = NumberedVals.get(Fn.
UIntVal);
9052 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9055 "invalid function forward reference in uselistorder_bb");
9056 auto *
F = dyn_cast<Function>(GV);
9058 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9059 if (
F->isDeclaration())
9060 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
9064 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
9066 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
9067 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
9069 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
9070 if (!isa<BasicBlock>(V))
9071 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
9073 return sortUseListOrder(V, Indexes, Loc);
9079bool LLParser::parseModuleEntry(
unsigned ID) {
9088 parseStringConstant(Path) ||
9096 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9097 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9098 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9099 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9100 parseUInt32(Hash[4]))
9107 auto ModuleEntry =
Index->addModule(Path, Hash);
9108 ModuleIdMap[
ID] = ModuleEntry->first();
9115bool LLParser::parseTypeIdEntry(
unsigned ID) {
9124 parseStringConstant(
Name))
9129 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9134 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9135 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9136 for (
auto TIDRef : FwdRefTIDs->second) {
9138 "Forward referenced type id GUID expected to be 0");
9141 ForwardRefTypeIds.erase(FwdRefTIDs);
9153 parseTypeTestResolution(TIS.
TTRes))
9158 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9169 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
9175bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9184 parseStringConstant(
Name))
9188 Index->getOrInsertTypeIdCompatibleVtableSummary(
Name);
9195 IdToIndexMapType IdToIndexMap;
9208 if (parseGVReference(VI, GVId))
9215 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9216 TI.push_back({
Offset, VI});
9224 for (
auto I : IdToIndexMap) {
9225 auto &Infos = ForwardRefValueInfos[
I.first];
9226 for (
auto P :
I.second) {
9228 "Forward referenced ValueInfo expected to be empty");
9229 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9239 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9240 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9241 for (
auto TIDRef : FwdRefTIDs->second) {
9243 "Forward referenced type id GUID expected to be 0");
9246 ForwardRefTypeIds.erase(FwdRefTIDs);
9286 return error(Lex.
getLoc(),
"unexpected TypeTestResolution kind");
9313 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9326 return error(Lex.
getLoc(),
"expected optional TypeTestResolution field");
9339bool LLParser::parseOptionalWpdResolutions(
9340 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9352 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9355 WPDResMap[
Offset] = WPDRes;
9391 return error(Lex.
getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9405 if (parseOptionalResByArg(WPDRes.
ResByArg))
9410 "expected optional WholeProgramDevirtResolution field");
9427bool LLParser::parseOptionalResByArg(
9436 std::vector<uint64_t>
Args;
9437 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9461 "unexpected WholeProgramDevirtResolution::ByArg kind");
9471 parseUInt64(ByArg.
Info))
9477 parseUInt32(ByArg.
Byte))
9483 parseUInt32(ByArg.
Bit))
9488 "expected optional whole program devirt field");
9495 ResByArg[
Args] = ByArg;
9506bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9514 if (parseUInt64(Val))
9516 Args.push_back(Val);
9525static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9530 assert(!(ReadOnly && WriteOnly));
9540bool LLParser::addGlobalValueToIndex(
9542 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9547 VI =
Index->getOrInsertValueInfo(GUID);
9551 auto *GV =
M->getNamedValue(
Name);
9553 return error(Loc,
"Reference to undefined global \"" +
Name +
"\"");
9555 VI =
Index->getOrInsertValueInfo(GV);
9559 "Need a source_filename to compute GUID for local");
9561 GlobalValue::getGlobalIdentifier(
Name, Linkage, SourceFileName));
9567 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9568 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9569 for (
auto VIRef : FwdRefVIs->second) {
9571 "Forward referenced ValueInfo expected to be empty");
9574 ForwardRefValueInfos.erase(FwdRefVIs);
9578 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9579 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9580 for (
auto AliaseeRef : FwdRefAliasees->second) {
9581 assert(!AliaseeRef.first->hasAliasee() &&
9582 "Forward referencing alias already has aliasee");
9583 assert(Summary &&
"Aliasee must be a definition");
9584 AliaseeRef.first->setAliasee(VI,
Summary.get());
9586 ForwardRefAliasees.erase(FwdRefAliasees);
9591 Index->addGlobalValueSummary(VI, std::move(Summary));
9594 if (
ID == NumberedValueInfos.size())
9595 NumberedValueInfos.push_back(VI);
9598 if (
ID > NumberedValueInfos.size())
9599 NumberedValueInfos.resize(
ID + 1);
9600 NumberedValueInfos[
ID] =
VI;
9608bool LLParser::parseSummaryIndexFlags() {
9615 if (parseUInt64(Flags))
9618 Index->setFlags(Flags);
9624bool LLParser::parseBlockCount() {
9631 if (parseUInt64(BlockCount))
9634 Index->setBlockCount(BlockCount);
9642bool LLParser::parseGVEntry(
unsigned ID) {
9657 parseStringConstant(
Name))
9663 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9667 return error(Lex.
getLoc(),
"expected name or guid tag");
9692 if (parseFunctionSummary(
Name, GUID,
ID))
9696 if (parseVariableSummary(
Name, GUID,
ID))
9700 if (parseAliasSummary(
Name, GUID,
ID))
9704 return error(Lex.
getLoc(),
"expected summary type");
9730 false,
false,
false,
9735 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9737 std::vector<CallsiteInfo> Callsites;
9738 std::vector<AllocInfo> Allocs;
9743 parseModuleReference(ModulePath) ||
9744 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9747 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9754 if (parseOptionalFFlags(FFlags))
9758 if (parseOptionalCalls(Calls))
9762 if (parseOptionalTypeIdInfo(TypeIdInfo))
9766 if (parseOptionalRefs(Refs))
9770 if (parseOptionalParamAccesses(ParamAccesses))
9774 if (parseOptionalAllocs(Allocs))
9778 if (parseOptionalCallsites(Callsites))
9782 return error(Lex.
getLoc(),
"expected optional function summary field");
9789 auto FS = std::make_unique<FunctionSummary>(
9790 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9796 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9798 FS->setModulePath(ModulePath);
9800 return addGlobalValueToIndex(
Name, GUID,
9802 std::move(FS), Loc);
9818 false,
false,
false,
9828 parseModuleReference(ModulePath) ||
9829 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9831 parseGVarFlags(GVarFlags))
9838 if (parseOptionalVTableFuncs(VTableFuncs))
9842 if (parseOptionalRefs(Refs))
9846 return error(Lex.
getLoc(),
"expected optional variable summary field");
9854 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9856 GS->setModulePath(ModulePath);
9857 GS->setVTableFuncs(std::move(VTableFuncs));
9859 return addGlobalValueToIndex(
Name, GUID,
9861 std::move(GS), Loc);
9877 false,
false,
false,
9881 parseModuleReference(ModulePath) ||
9882 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9890 if (parseGVReference(AliaseeVI, GVId))
9896 auto AS = std::make_unique<AliasSummary>(GVFlags);
9898 AS->setModulePath(ModulePath);
9902 ForwardRefAliasees[GVId].emplace_back(AS.
get(), Loc);
9904 auto Summary =
Index->findSummaryInModule(AliaseeVI, ModulePath);
9905 assert(Summary &&
"Aliasee must be a definition");
9906 AS->setAliasee(AliaseeVI, Summary);
9909 return addGlobalValueToIndex(
Name, GUID,
9911 std::move(AS), Loc);
9916bool LLParser::parseFlag(
unsigned &Val) {
9918 return tokError(
"expected integer");
9939 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9948 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9954 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9960 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9966 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9972 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9978 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9984 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9990 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9996 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10002 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10007 return error(Lex.
getLoc(),
"expected function flag type");
10011 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10022bool LLParser::parseOptionalCalls(
10027 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10031 IdToIndexMapType IdToIndexMap;
10042 if (parseGVReference(VI, GVId))
10046 unsigned RelBF = 0;
10047 unsigned HasTailCall =
false;
10054 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10059 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10064 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10068 return error(Lex.
getLoc(),
"expected hotness, relbf, or tail");
10072 return tokError(
"Expected only one of hotness or relbf");
10077 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10087 for (
auto I : IdToIndexMap) {
10088 auto &Infos = ForwardRefValueInfos[
I.first];
10089 for (
auto P :
I.second) {
10091 "Forward referenced ValueInfo expected to be empty");
10092 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10109 case lltok::kw_cold:
10115 case lltok::kw_hot:
10122 return error(Lex.
getLoc(),
"invalid call edge hotness");
10131bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10135 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10139 IdToIndexMapType IdToIndexMap;
10143 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10150 if (parseGVReference(VI, GVId))
10163 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10164 VTableFuncs.push_back({
VI,
Offset});
10166 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10172 for (
auto I : IdToIndexMap) {
10173 auto &Infos = ForwardRefValueInfos[
I.first];
10174 for (
auto P :
I.second) {
10176 "Forward referenced ValueInfo expected to be empty");
10177 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10181 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10188bool LLParser::parseParamNo(
uint64_t &ParamNo) {
10190 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10199 auto ParseAPSInt = [&](
APSInt &Val) {
10201 return tokError(
"expected integer");
10204 Val.setIsSigned(
true);
10227 IdLocListType &IdLocList) {
10236 if (parseGVReference(VI, GVId))
10240 IdLocList.emplace_back(GVId, Loc);
10243 parseParamNo(
Call.ParamNo) ||
10245 parseParamAccessOffset(
Call.Offsets))
10258 IdLocListType &IdLocList) {
10260 parseParamNo(
Param.ParamNo) ||
10262 parseParamAccessOffset(
Param.Use))
10272 if (parseParamAccessCall(Call, IdLocList))
10274 Param.Calls.push_back(Call);
10289bool LLParser::parseOptionalParamAccesses(
10290 std::vector<FunctionSummary::ParamAccess> &Params) {
10298 IdLocListType VContexts;
10299 size_t CallsNum = 0;
10302 if (parseParamAccess(ParamAccess, VContexts))
10304 CallsNum += ParamAccess.
Calls.size();
10305 assert(VContexts.size() == CallsNum);
10307 Params.emplace_back(std::move(ParamAccess));
10315 IdLocListType::const_iterator ItContext = VContexts.begin();
10316 for (
auto &PA : Params) {
10317 for (
auto &
C : PA.Calls) {
10319 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10320 ItContext->second);
10324 assert(ItContext == VContexts.end());
10335 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10339 struct ValueContext {
10344 std::vector<ValueContext> VContexts;
10349 if (parseGVReference(
VC.VI,
VC.GVId))
10351 VContexts.push_back(VC);
10357 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10358 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10361 IdToIndexMapType IdToIndexMap;
10362 for (
auto &VC : VContexts) {
10367 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10373 for (
auto I : IdToIndexMap) {
10374 auto &Infos = ForwardRefValueInfos[
I.first];
10375 for (
auto P :
I.second) {
10377 "Forward referenced ValueInfo expected to be empty");
10378 Infos.emplace_back(&Refs[
P.first],
P.second);
10392bool LLParser::parseOptionalTypeIdInfo(
10404 if (parseTypeTests(TypeIdInfo.
TypeTests))
10428 return error(Lex.
getLoc(),
"invalid typeIdInfo list type");
10432 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10441bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10449 IdToIndexMapType IdToIndexMap;
10458 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10460 }
else if (parseUInt64(GUID))
10462 TypeTests.push_back(GUID);
10467 for (
auto I : IdToIndexMap) {
10468 auto &Ids = ForwardRefTypeIds[
I.first];
10469 for (
auto P :
I.second) {
10470 assert(TypeTests[
P.first] == 0 &&
10471 "Forward referenced type id GUID expected to be 0");
10472 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10476 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10484bool LLParser::parseVFuncIdList(
10485 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10493 IdToIndexMapType IdToIndexMap;
10496 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10498 VFuncIdList.push_back(VFuncId);
10506 for (
auto I : IdToIndexMap) {
10507 auto &Ids = ForwardRefTypeIds[
I.first];
10508 for (
auto P :
I.second) {
10509 assert(VFuncIdList[
P.first].GUID == 0 &&
10510 "Forward referenced type id GUID expected to be 0");
10511 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10520bool LLParser::parseConstVCallList(
10522 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10530 IdToIndexMapType IdToIndexMap;
10533 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10535 ConstVCallList.push_back(ConstVCall);
10543 for (
auto I : IdToIndexMap) {
10544 auto &Ids = ForwardRefTypeIds[
I.first];
10545 for (
auto P :
I.second) {
10546 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10547 "Forward referenced type id GUID expected to be 0");
10548 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10558 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10560 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
10564 if (parseArgs(ConstVCall.
Args))
10577 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10592 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
10594 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10596 parseUInt64(VFuncId.
GUID))
10602 parseUInt64(VFuncId.
Offset) ||
10631 assert(HasLinkage &&
"Linkage not optional in summary entry");
10638 parseOptionalVisibility(Flag);
10643 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10649 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10655 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10661 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10670 if (parseOptionalImportType(Lex.
getKind(), IK))
10672 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10676 return error(Lex.
getLoc(),
"expected gv flag type");
10698 auto ParseRest = [
this](
unsigned int &Val) {
10702 return parseFlag(Val);
10708 case lltok::kw_readonly:
10709 if (ParseRest(Flag))
10713 case lltok::kw_writeonly:
10714 if (ParseRest(Flag))
10719 if (ParseRest(Flag))
10724 if (ParseRest(Flag))
10729 return error(Lex.
getLoc(),
"expected gvar flag type");
10737bool LLParser::parseModuleReference(
StringRef &ModulePath) {
10745 auto I = ModuleIdMap.find(ModuleID);
10747 assert(
I != ModuleIdMap.end());
10748 ModulePath =
I->second;
10754bool LLParser::parseGVReference(
ValueInfo &VI,
unsigned &GVId) {
10757 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10763 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10765 VI = NumberedValueInfos[GVId];
10782bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10786 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10801 if (parseAllocType(V))
10806 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10810 std::vector<MIBInfo> MIBs;
10811 if (parseMemProfs(MIBs))
10814 Allocs.push_back({Versions, MIBs});
10831bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10835 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10841 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10850 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10861 if (parseUInt64(StackId))
10892 case lltok::kw_cold:
10895 case lltok::kw_hot:
10899 return error(Lex.
getLoc(),
"invalid alloc type");
10912bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10916 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10920 IdToIndexMapType IdToIndexMap;
10923 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10932 if (parseGVReference(VI, GVId))
10936 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10945 if (parseUInt32(V))
10951 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10962 if (parseUInt64(StackId))
10975 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10976 Callsites.push_back({
VI, Clones, StackIdIndices});
10984 for (
auto I : IdToIndexMap) {
10985 auto &Infos = ForwardRefValueInfos[
I.first];
10986 for (
auto P :
I.second) {
10988 "Forward referenced ValueInfo expected to be empty");
10989 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10993 if (parseToken(
lltok::rparen,
"expected ')' in callsites"))
static int64_t upperBound(StackOffset Size)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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...
Module.h This file contains the declarations for the Module class.
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)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
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)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
PowerPC Reduce CR logical Operation
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)"
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 LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
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.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ 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 LLVM_ABI StringRef getOperationName(BinOp Op)
LLVM_ABI AttributeSet getFnAttrs() const
The function attributes are returned.
static LLVM_ABI 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.
LLVM_ABI 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 LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static LLVM_ABI 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 LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
LLVM_ABI 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 LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
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, InsertPosition InsertBefore=nullptr)
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Represents which components of the pointer may be captured in which location.
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI 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="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
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 LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI 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 Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI 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 LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
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 LLVM_ABI DIFlags getFlag(StringRef Flag)
String type, Fortran CHARACTER(n)
Subprogram description. Uses SubclassData1.
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
Type array for a subprogram.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
This class represents an Operation in the Expression.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI 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 LLVM_ABI 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.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static LLVM_ABI 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)
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
Generic tagged DWARF-like metadata node.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI 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 LLVM_ABI 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 LLVM_ABI 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...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
LLVM_ABI 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
void setDSOLocal(bool Local)
LLVM_ABI 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)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
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
LLVM_ABI void setPartition(StringRef Part)
LLVM_ABI 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)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI 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 LLVM_ABI 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 InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI 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 InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI 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.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
unsigned getUIntVal() const
lltok::Kind getKind() const
const std::string & getStrVal() const
const APSInt & getAPSIntVal() const
void setIgnoreColonInIdentifiers(bool val)
const APFloat & getAPFloatVal() const
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
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*.
This is an important class for using LLVM in a threaded context.
LLVM_ABI bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
LLVM_ABI SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
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 LLVM_ABI 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.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI 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="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI 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 LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI 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, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
static LLVM_ABI 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.
This instruction constructs a fixed permutation of two input vectors.
ArrayRef< int > getShuffleMask() const
static LLVM_ABI 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 reserve(size_type N)
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 LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Triple - Helper class for working with autoconf configuration names.
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.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
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.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
bool isPointerTy() const
True if this is an instance of PointerType.
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.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
TypeID
Definitions of all of the base types for the Type system.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
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.
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 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.
bool isVoidTy() const
Return true if this is 'void'.
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
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 LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI 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
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
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.
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
LLVM_ABI unsigned getTag(StringRef TagString)
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
LLVM_ABI 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.
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...
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ 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.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
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)
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Linkage
Describes symbol linkage. This can be used to resolve definition clashes.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_no_sanitize_hwaddress
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_amdgpu_gfx_whole_wave
@ 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
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI 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)
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
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...
LLVM_ABI 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.
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
bool isPointerTy(const Type *T)
CaptureComponents
Components of the pointer that may be captured.
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.
const char * toString(DWARFSectionKind Kind)
LLVM_ABI 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
bool capturesNothing(CaptureComponents CC)
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
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 LLVM_ABI const fltSemantics & IEEEsingle() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToEven
static LLVM_ABI const fltSemantics & IEEEdouble() LLVM_READNONE
static LLVM_ABI const fltSemantics & IEEEhalf() LLVM_READNONE
static LLVM_ABI const fltSemantics & BFloat() LLVM_READNONE
This struct is a compact representation of a valid (non-zero power of two) alignment.
Helper struct shared between Function Specialization and SCCP Solver.
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::@40 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.