63 "Allow incomplete IR on a best effort basis (references to unknown "
64 "metadata will be dropped)"));
87 "Can't read textual IR with a Context that discards named Values");
90 if (parseTargetDefinitions(DataLayoutCallback))
100 restoreParsingState(Slots);
104 if (parseType(Ty) || parseConstantValue(Ty,
C))
107 return error(Lex.
getLoc(),
"expected end of string");
113 restoreParsingState(Slots);
122 Read =
End.getPointer() - Start.getPointer();
127void LLParser::restoreParsingState(
const SlotMapping *Slots) {
134 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
135 for (
const auto &
I : Slots->
Types)
136 NumberedTypes.insert(
137 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
142 if (!isa<DbgInfoIntrinsic>(
II) &&
143 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
148 if (
auto *MV = dyn_cast<MetadataAsValue>(V))
149 if (
auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
150 if (MD->isTemporary())
154 assert(
II->use_empty() &&
"Cannot have uses");
155 II->eraseFromParent();
164void LLParser::dropUnknownMetadataReferences() {
165 auto Pred = [](
unsigned MDKind,
MDNode *
Node) {
return Node->isTemporary(); };
167 F.eraseMetadataIf(Pred);
169 I.eraseMetadataIf(Pred);
171 if (
auto *
II = dyn_cast<IntrinsicInst>(&
I))
177 GV.eraseMetadataIf(Pred);
182 if (
Info.first->getNumTemporaryUses() == 1) {
183 NumberedMetadata.erase(
ID);
184 ForwardRefMDNodes.erase(
ID);
197 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
198 "Mixed debug intrinsics/records seen without a parsing error?");
203 M->setNewDbgInfoFormatFlag(SeenNewDbgInfoFormat);
207 for (
const auto &RAG : ForwardRefAttrGroups) {
209 const std::vector<unsigned> &
Attrs = RAG.second;
212 for (
const auto &Attr : Attrs) {
213 auto R = NumberedAttrBuilders.find(Attr);
214 if (R != NumberedAttrBuilders.end())
218 if (
Function *Fn = dyn_cast<Function>(V)) {
228 Fn->setAlignment(*
A);
233 Fn->setAttributes(AS);
234 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
240 CI->setAttributes(AS);
247 II->setAttributes(AS);
248 }
else if (
CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
254 CBI->setAttributes(AS);
255 }
else if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
266 if (!ForwardRefBlockAddresses.empty())
267 return error(ForwardRefBlockAddresses.begin()->first.Loc,
268 "expected function name in blockaddress");
270 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
274 GV =
M->getNamedValue(GVRef.
StrVal);
276 GV = NumberedVals.get(GVRef.
UIntVal);
281 "' referenced by dso_local_equivalent");
285 "expected a function, alias to function, or ifunc "
286 "in dso_local_equivalent");
289 FwdRef->replaceAllUsesWith(Equiv);
290 FwdRef->eraseFromParent();
297 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
298 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
301 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
302 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
305 ForwardRefDSOLocalEquivalentIDs.clear();
306 ForwardRefDSOLocalEquivalentNames.clear();
308 for (
const auto &NT : NumberedTypes)
309 if (
NT.second.second.isValid())
311 "use of undefined type '%" +
Twine(
NT.first) +
"'");
313 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
314 NamedTypes.begin(), E = NamedTypes.end();
I != E; ++
I)
315 if (
I->second.second.isValid())
316 return error(
I->second.second,
317 "use of undefined type named '" +
I->getKey() +
"'");
319 if (!ForwardRefComdats.empty())
320 return error(ForwardRefComdats.begin()->second,
321 "use of undefined comdat '$" +
322 ForwardRefComdats.begin()->first +
"'");
339 auto *CB = dyn_cast<CallBase>(
U.getUser());
340 if (!CB || !CB->isCallee(&U))
341 return error(
Info.second,
"intrinsic can only be used as callee");
346 return error(
Info.second,
"invalid intrinsic signature");
351 Info.first->eraseFromParent();
352 ForwardRefVals.erase(
Name);
363 for (
Use &U :
V->uses()) {
364 auto *CB = dyn_cast<CallBase>(
U.getUser());
365 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
367 FTy = CB->getFunctionType();
375 Type *Ty = GetCommonFunctionType(
Info.first);
380 if (
auto *FTy = dyn_cast<FunctionType>(Ty))
386 Info.first->replaceAllUsesWith(GV);
387 Info.first->eraseFromParent();
388 ForwardRefVals.erase(
Name);
391 if (!ForwardRefVals.empty())
392 return error(ForwardRefVals.begin()->second.second,
393 "use of undefined value '@" + ForwardRefVals.begin()->first +
396 if (!ForwardRefValIDs.empty())
397 return error(ForwardRefValIDs.begin()->second.second,
398 "use of undefined value '@" +
399 Twine(ForwardRefValIDs.begin()->first) +
"'");
402 dropUnknownMetadataReferences();
404 if (!ForwardRefMDNodes.empty())
405 return error(ForwardRefMDNodes.begin()->second.second,
406 "use of undefined metadata '!" +
407 Twine(ForwardRefMDNodes.begin()->first) +
"'");
410 for (
auto &
N : NumberedMetadata) {
411 if (
N.second && !
N.second->isResolved())
412 N.second->resolveCycles();
415 for (
auto *Inst : InstsWithTBAATag) {
416 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
419 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
422 if (MD != UpgradedMD)
423 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
432 if (UpgradeDebugInfo)
448 for (
const auto &
I : NamedTypes)
449 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
450 for (
const auto &
I : NumberedTypes)
451 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
457bool LLParser::validateEndOfIndex() {
461 if (!ForwardRefValueInfos.empty())
462 return error(ForwardRefValueInfos.begin()->second.front().second,
463 "use of undefined summary '^" +
464 Twine(ForwardRefValueInfos.begin()->first) +
"'");
466 if (!ForwardRefAliasees.empty())
467 return error(ForwardRefAliasees.begin()->second.front().second,
468 "use of undefined summary '^" +
469 Twine(ForwardRefAliasees.begin()->first) +
"'");
471 if (!ForwardRefTypeIds.empty())
472 return error(ForwardRefTypeIds.begin()->second.front().second,
473 "use of undefined type id summary '^" +
474 Twine(ForwardRefTypeIds.begin()->first) +
"'");
488 std::string TentativeDLStr =
M->getDataLayoutStr();
495 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
499 if (parseSourceFileName())
508 if (
auto LayoutOverride =
509 DataLayoutCallback(
M->getTargetTriple(), TentativeDLStr)) {
510 TentativeDLStr = *LayoutOverride;
516 M->setDataLayout(MaybeDL.
get());
520bool LLParser::parseTopLevelEntities() {
528 if (parseSummaryEntry())
532 if (parseSourceFileName())
544 return tokError(
"expected top-level entity");
555 if (parseModuleAsm())
559 if (parseUnnamedType())
563 if (parseNamedType())
567 if (parseUnnamedGlobal())
571 if (parseNamedGlobal())
576 if (parseStandaloneMetadata())
580 if (parseSummaryEntry())
584 if (parseNamedMetadata())
588 if (parseUnnamedAttrGrp())
592 if (parseUseListOrder())
596 if (parseUseListOrderBB())
605bool LLParser::parseModuleAsm() {
611 parseStringConstant(AsmStr))
614 M->appendModuleInlineAsm(AsmStr);
621bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
627 return tokError(
"unknown target property");
630 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
631 parseStringConstant(Str))
633 M->setTargetTriple(Str);
637 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
640 if (parseStringConstant(TentativeDLStr))
648bool LLParser::parseSourceFileName() {
651 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
652 parseStringConstant(SourceFileName))
655 M->setSourceFileName(SourceFileName);
661bool LLParser::parseUnnamedType() {
666 if (parseToken(
lltok::equal,
"expected '=' after name") ||
671 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
674 if (!isa<StructType>(Result)) {
675 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
677 return error(TypeLoc,
"non-struct types may not be recursive");
687bool LLParser::parseNamedType() {
692 if (parseToken(
lltok::equal,
"expected '=' after name") ||
697 if (parseStructDefinition(NameLoc,
Name, NamedTypes[
Name], Result))
700 if (!isa<StructType>(Result)) {
701 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
703 return error(NameLoc,
"non-struct types may not be recursive");
713bool LLParser::parseDeclare() {
717 std::vector<std::pair<unsigned, MDNode *>> MDs;
721 if (parseMetadataAttachment(MDK,
N))
723 MDs.push_back({MDK,
N});
727 unsigned FunctionNumber = -1;
729 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
732 F->addMetadata(MD.first, *MD.second);
738bool LLParser::parseDefine() {
743 unsigned FunctionNumber = -1;
745 return parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
746 parseOptionalFunctionMetadata(*
F) ||
747 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
753bool LLParser::parseGlobalType(
bool &IsConstant) {
760 return tokError(
"expected 'global' or 'constant'");
766bool LLParser::parseOptionalUnnamedAddr(
787bool LLParser::parseUnnamedGlobal() {
795 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(), VarID))
799 if (parseToken(
lltok::equal,
"expected '=' after name"))
802 VarID = NumberedVals.getNext();
806 unsigned Linkage, Visibility, DLLStorageClass;
810 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
812 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
817 return parseGlobal(
Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
818 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
821 return parseAliasOrIFunc(
Name, VarID, NameLoc, Linkage, Visibility,
822 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
831bool LLParser::parseNamedGlobal() {
838 unsigned Linkage, Visibility, DLLStorageClass;
842 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
843 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
845 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
850 return parseGlobal(
Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
851 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
854 return parseAliasOrIFunc(
Name, -1, NameLoc, Linkage, Visibility,
855 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
859bool LLParser::parseComdat() {
869 return tokError(
"expected comdat type");
874 return tokError(
"unknown selection kind");
896 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(
Name))
897 return error(NameLoc,
"redefinition of comdat '$" +
Name +
"'");
900 if (
I != ComdatSymTab.
end())
903 C =
M->getOrInsertComdat(
Name);
904 C->setSelectionKind(SK);
911bool LLParser::parseMDString(
MDString *&Result) {
913 if (parseStringConstant(Str))
921bool LLParser::parseMDNodeID(
MDNode *&Result) {
925 if (parseUInt32(MID))
929 if (NumberedMetadata.count(MID)) {
930 Result = NumberedMetadata[MID];
935 auto &FwdRef = ForwardRefMDNodes[MID];
938 Result = FwdRef.first.get();
939 NumberedMetadata[MID].reset(Result);
945bool LLParser::parseNamedMetadata() {
964 if (parseDIExpression(
N,
false))
970 return tokError(
"found DIArgList outside of function");
978 return parseToken(
lltok::rbrace,
"expected end of metadata node");
983bool LLParser::parseStandaloneMetadata() {
986 unsigned MetadataID = 0;
989 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
994 return tokError(
"unexpected type in metadata definition");
998 if (parseSpecializedMDNode(
Init, IsDistinct))
1001 parseMDTuple(
Init, IsDistinct))
1005 auto FI = ForwardRefMDNodes.find(MetadataID);
1006 if (FI != ForwardRefMDNodes.end()) {
1007 auto *ToReplace = FI->second.first.get();
1010 if (isa<DIAssignID>(
Init)) {
1011 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1012 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1013 "Inst unexpectedly already has DIAssignID attachment");
1014 Inst->setMetadata(LLVMContext::MD_DIAssignID,
Init);
1018 ToReplace->replaceAllUsesWith(
Init);
1019 ForwardRefMDNodes.erase(FI);
1021 assert(NumberedMetadata[MetadataID] ==
Init &&
"Tracking VH didn't work");
1023 if (NumberedMetadata.count(MetadataID))
1024 return tokError(
"Metadata id is already used");
1025 NumberedMetadata[MetadataID].reset(
Init);
1032bool LLParser::skipModuleSummaryEntry() {
1042 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1043 "start of summary entry");
1045 return parseSummaryIndexFlags();
1047 return parseBlockCount();
1049 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1050 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1054 unsigned NumOpenParen = 1;
1064 return tokError(
"found end of file while parsing summary entry");
1070 }
while (NumOpenParen > 0);
1076bool LLParser::parseSummaryEntry() {
1090 return skipModuleSummaryEntry();
1092 bool result =
false;
1095 result = parseGVEntry(SummaryID);
1098 result = parseModuleEntry(SummaryID);
1101 result = parseTypeIdEntry(SummaryID);
1104 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1107 result = parseSummaryIndexFlags();
1110 result = parseBlockCount();
1113 result =
error(Lex.
getLoc(),
"unexpected summary kind");
1150bool LLParser::parseAliasOrIFunc(
const std::string &
Name,
unsigned NameID,
1151 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1152 unsigned DLLStorageClass,
bool DSOLocal,
1167 return error(NameLoc,
"invalid linkage type for alias");
1170 return error(NameLoc,
1171 "symbol with local linkage must have default visibility");
1174 return error(NameLoc,
1175 "symbol with local linkage cannot have a DLL storage class");
1179 if (parseType(Ty) ||
1180 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1189 if (parseGlobalTypeAndValue(Aliasee))
1194 if (parseValID(
ID,
nullptr))
1197 return error(AliaseeLoc,
"invalid aliasee");
1198 Aliasee =
ID.ConstantVal;
1202 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1204 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1205 unsigned AddrSpace = PTy->getAddressSpace();
1211 if (!
Name.empty()) {
1212 auto I = ForwardRefVals.find(
Name);
1213 if (
I != ForwardRefVals.end()) {
1214 GVal =
I->second.first;
1215 ForwardRefVals.erase(
Name);
1216 }
else if (
M->getNamedValue(
Name)) {
1217 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1220 auto I = ForwardRefValIDs.find(NameID);
1221 if (
I != ForwardRefValIDs.end()) {
1222 GVal =
I->second.first;
1223 ForwardRefValIDs.erase(
I);
1228 std::unique_ptr<GlobalAlias> GA;
1229 std::unique_ptr<GlobalIFunc> GI;
1259 return tokError(
"unknown alias or ifunc property!");
1264 NumberedVals.add(NameID, GV);
1271 "forward reference and definition of alias have different types");
1281 M->insertAlias(GA.release());
1283 M->insertIFunc(GI.release());
1293 case lltok::kw_sanitize_memtag:
1309 Meta.NoAddress =
true;
1312 Meta.NoHWAddress =
true;
1314 case lltok::kw_sanitize_memtag:
1318 Meta.IsDynInit =
true;
1321 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1341bool LLParser::parseGlobal(
const std::string &
Name,
unsigned NameID,
1342 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1343 unsigned Visibility,
unsigned DLLStorageClass,
1347 return error(NameLoc,
1348 "symbol with local linkage must have default visibility");
1351 return error(NameLoc,
1352 "symbol with local linkage cannot have a DLL storage class");
1356 LocTy IsExternallyInitializedLoc;
1360 if (parseOptionalAddrSpace(AddrSpace) ||
1362 IsExternallyInitialized,
1363 &IsExternallyInitializedLoc) ||
1364 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1373 if (parseGlobalValue(Ty,
Init))
1378 return error(TyLoc,
"invalid type for global variable");
1383 if (!
Name.empty()) {
1384 auto I = ForwardRefVals.find(
Name);
1385 if (
I != ForwardRefVals.end()) {
1386 GVal =
I->second.first;
1387 ForwardRefVals.erase(
I);
1388 }
else if (
M->getNamedValue(
Name)) {
1389 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1394 if (NameID == (
unsigned)-1)
1395 NameID = NumberedVals.getNext();
1397 auto I = ForwardRefValIDs.find(NameID);
1398 if (
I != ForwardRefValIDs.end()) {
1399 GVal =
I->second.first;
1400 ForwardRefValIDs.erase(
I);
1409 NumberedVals.add(NameID, GV);
1427 "forward reference and definition of global have different types");
1447 }
else if (Lex.
getKind() == lltok::kw_align) {
1449 if (parseOptionalAlignment(Alignment))
1455 if (parseOptionalCodeModel(CodeModel))
1459 if (parseGlobalObjectMetadataAttachment(*GV))
1462 if (parseSanitizer(GV))
1466 if (parseOptionalComdat(
Name,
C))
1471 return tokError(
"unknown global variable property!");
1477 std::vector<unsigned> FwdRefAttrGrps;
1478 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1480 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1482 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1490bool LLParser::parseUnnamedAttrGrp() {
1496 return tokError(
"expected attribute group id");
1499 std::vector<unsigned> unused;
1507 auto R = NumberedAttrBuilders.find(VarID);
1508 if (R == NumberedAttrBuilders.end())
1509 R = NumberedAttrBuilders.emplace(VarID,
AttrBuilder(
M->getContext())).first;
1511 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1512 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1515 if (!
R->second.hasAttributes())
1516 return error(AttrGrpLoc,
"attribute group has no attributes");
1523#define GET_ATTR_NAMES
1524#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1525 case lltok::kw_##DISPLAY_NAME: \
1526 return Attribute::ENUM_NAME;
1527#include "llvm/IR/Attributes.inc"
1536 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1539 case Attribute::Alignment: {
1548 if (parseOptionalAlignment(Alignment,
true))
1551 B.addAlignmentAttr(Alignment);
1554 case Attribute::StackAlignment: {
1559 parseUInt32(Alignment))
1562 if (parseOptionalStackAlignment(Alignment))
1565 B.addStackAlignmentAttr(Alignment);
1568 case Attribute::AllocSize: {
1569 unsigned ElemSizeArg;
1570 std::optional<unsigned> NumElemsArg;
1571 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1573 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1576 case Attribute::VScaleRange: {
1577 unsigned MinValue, MaxValue;
1578 if (parseVScaleRangeArguments(MinValue, MaxValue))
1580 B.addVScaleRangeAttr(MinValue,
1581 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1584 case Attribute::Dereferenceable: {
1586 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1588 B.addDereferenceableAttr(Bytes);
1591 case Attribute::DereferenceableOrNull: {
1593 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1595 B.addDereferenceableOrNullAttr(Bytes);
1598 case Attribute::UWTable: {
1600 if (parseOptionalUWTableKind(Kind))
1602 B.addUWTableAttr(Kind);
1605 case Attribute::AllocKind: {
1607 if (parseAllocKind(Kind))
1609 B.addAllocKindAttr(Kind);
1612 case Attribute::Memory: {
1613 std::optional<MemoryEffects> ME = parseMemoryAttr();
1616 B.addMemoryAttr(*ME);
1619 case Attribute::NoFPClass: {
1622 B.addNoFPClassAttr(NoFPClass);
1628 case Attribute::Range:
1629 return parseRangeAttr(
B);
1630 case Attribute::Initializes:
1631 return parseInitializesAttr(
B);
1633 B.addAttribute(Attr);
1641 case lltok::kw_readnone:
1644 case lltok::kw_readonly:
1647 case lltok::kw_writeonly:
1666bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1667 std::vector<unsigned> &FwdRefAttrGrps,
1668 bool InAttrGrp, LocTy &BuiltinLoc) {
1669 bool HaveError =
false;
1680 if (parseStringAttribute(
B))
1692 "cannot have an attribute group reference in an attribute group");
1702 if (Token == lltok::kw_builtin)
1714 return error(Lex.
getLoc(),
"unterminated attribute group");
1717 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1724 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1728 B.addMemoryAttr(ME);
1742 PTy->getAddressSpace());
1751 error(Loc,
"'" +
Name +
"' is not a basic block");
1753 error(Loc,
"'" +
Name +
"' defined with type '" +
1766 error(Loc,
"global variable reference must have pointer type");
1772 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1777 auto I = ForwardRefVals.find(
Name);
1778 if (
I != ForwardRefVals.end())
1779 Val =
I->second.first;
1784 return cast_or_null<GlobalValue>(
1785 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1789 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1796 error(Loc,
"global variable reference must have pointer type");
1805 auto I = ForwardRefValIDs.find(
ID);
1806 if (
I != ForwardRefValIDs.end())
1807 Val =
I->second.first;
1812 return cast_or_null<GlobalValue>(
1813 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1817 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1825Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1829 if (
I != ComdatSymTab.
end())
1834 ForwardRefComdats[
Name] = Loc;
1844bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1846 return tokError(ErrMsg);
1853bool LLParser::parseStringConstant(std::string &Result) {
1855 return tokError(
"expected string constant");
1863bool LLParser::parseUInt32(
uint32_t &Val) {
1865 return tokError(
"expected integer");
1867 if (Val64 !=
unsigned(Val64))
1868 return tokError(
"expected 32-bit integer (too large)");
1876bool LLParser::parseUInt64(
uint64_t &Val) {
1878 return tokError(
"expected integer");
1891 return tokError(
"expected localdynamic, initialexec or localexec");
1919 return parseTLSModel(TLM) ||
1920 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1928bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1929 AddrSpace = DefaultAS;
1933 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1936 if (AddrSpaceStr ==
"A") {
1937 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1938 }
else if (AddrSpaceStr ==
"G") {
1939 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1940 }
else if (AddrSpaceStr ==
"P") {
1941 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1943 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1949 return tokError(
"expected integer or string constant");
1951 if (parseUInt32(AddrSpace))
1953 if (!isUInt<24>(AddrSpace))
1954 return error(Loc,
"invalid address space, must be a 24-bit integer");
1958 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1959 ParseAddrspaceValue(AddrSpace) ||
1970 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1972 B.addAttribute(Attr, Val);
1977bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1978 bool HaveError =
false;
1985 if (parseStringAttribute(
B))
1995 if (parseEnumAttribute(Attr,
B,
false))
1999 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2001 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2049bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2050 unsigned &Visibility,
2051 unsigned &DLLStorageClass,
bool &DSOLocal) {
2055 parseOptionalDSOLocal(DSOLocal);
2056 parseOptionalVisibility(Visibility);
2057 parseOptionalDLLStorageClass(DLLStorageClass);
2060 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2066void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2088void LLParser::parseOptionalVisibility(
unsigned &Res) {
2106bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2110 return tokError(
"unknown import kind. Expect definition or declaration.");
2125void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2195bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2271 return parseUInt32(
CC);
2281bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2288 return parseMDNode(MD);
2293bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2296 return tokError(
"expected metadata after comma");
2300 if (parseMetadataAttachment(MDK,
N))
2303 if (MDK == LLVMContext::MD_DIAssignID)
2304 TempDIAssignIDAttachments[
N].push_back(&Inst);
2308 if (MDK == LLVMContext::MD_tbaa)
2309 InstsWithTBAATag.push_back(&Inst);
2318bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2321 if (parseMetadataAttachment(MDK,
N))
2330bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2332 if (parseGlobalObjectMetadataAttachment(
F))
2340bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2341 Alignment = std::nullopt;
2342 if (!EatIfPresent(lltok::kw_align))
2348 bool HaveParens =
false;
2354 if (parseUInt64(
Value))
2358 return error(ParenLoc,
"expected ')'");
2361 return error(AlignLoc,
"alignment is not a power of two");
2363 return error(AlignLoc,
"huge alignments are not supported yet");
2374 auto ErrMsg =
"expected global code model string";
2375 if (StrVal ==
"tiny")
2377 else if (StrVal ==
"small")
2379 else if (StrVal ==
"kernel")
2381 else if (StrVal ==
"medium")
2383 else if (StrVal ==
"large")
2386 return tokError(ErrMsg);
2397bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2399 assert((AttrKind == lltok::kw_dereferenceable ||
2400 AttrKind == lltok::kw_dereferenceable_or_null) &&
2404 if (!EatIfPresent(AttrKind))
2408 return error(ParenLoc,
"expected '('");
2410 if (parseUInt64(Bytes))
2414 return error(ParenLoc,
"expected ')'");
2416 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2420bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2431 return error(KindLoc,
"expected unwind table kind");
2440 return error(ParenLoc,
"expected '('");
2443 if (parseStringConstant(Arg))
2444 return error(KindLoc,
"expected allockind value");
2448 }
else if (
A ==
"realloc") {
2450 }
else if (
A ==
"free") {
2452 }
else if (
A ==
"uninitialized") {
2454 }
else if (
A ==
"zeroed") {
2456 }
else if (
A ==
"aligned") {
2459 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2464 return error(ParenLoc,
"expected ')'");
2466 return error(KindLoc,
"expected allockind value");
2477 return std::nullopt;
2492 return std::nullopt;
2496std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2506 tokError(
"expected '('");
2507 return std::nullopt;
2510 bool SeenLoc =
false;
2516 tokError(
"expected ':' after location");
2517 return std::nullopt;
2524 tokError(
"expected memory location (argmem, inaccessiblemem) "
2525 "or access kind (none, read, write, readwrite)");
2527 tokError(
"expected access kind (none, read, write, readwrite)");
2528 return std::nullopt;
2537 tokError(
"default access kind must be specified first");
2538 return std::nullopt;
2547 tokError(
"unterminated memory attribute");
2548 return std::nullopt;
2590unsigned LLParser::parseNoFPClassAttr() {
2595 tokError(
"expected '('");
2602 if (TestMask != 0) {
2606 !parseUInt64(
Value)) {
2608 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2619 error(Lex.
getLoc(),
"expected nofpclass test mask");
2637bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2638 bool &AteExtraComma) {
2639 AteExtraComma =
false;
2643 AteExtraComma =
true;
2647 if (Lex.
getKind() != lltok::kw_align)
2648 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2650 if (parseOptionalAlignment(Alignment))
2663bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2664 bool &AteExtraComma) {
2665 AteExtraComma =
false;
2669 AteExtraComma =
true;
2675 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2677 if (parseOptionalAddrSpace(AddrSpace))
2684bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2685 std::optional<unsigned> &HowManyArg) {
2688 auto StartParen = Lex.
getLoc();
2690 return error(StartParen,
"expected '('");
2692 if (parseUInt32(BaseSizeArg))
2696 auto HowManyAt = Lex.
getLoc();
2698 if (parseUInt32(HowMany))
2700 if (HowMany == BaseSizeArg)
2701 return error(HowManyAt,
2702 "'allocsize' indices can't refer to the same parameter");
2703 HowManyArg = HowMany;
2705 HowManyArg = std::nullopt;
2707 auto EndParen = Lex.
getLoc();
2709 return error(EndParen,
"expected ')'");
2713bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2714 unsigned &MaxValue) {
2717 auto StartParen = Lex.
getLoc();
2719 return error(StartParen,
"expected '('");
2721 if (parseUInt32(MinValue))
2725 if (parseUInt32(MaxValue))
2728 MaxValue = MinValue;
2730 auto EndParen = Lex.
getLoc();
2732 return error(EndParen,
"expected ')'");
2741bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2746 return parseScope(SSID) || parseOrdering(Ordering);
2756 auto StartParenAt = Lex.
getLoc();
2758 return error(StartParenAt,
"Expected '(' in syncscope");
2761 auto SSNAt = Lex.
getLoc();
2762 if (parseStringConstant(SSN))
2763 return error(SSNAt,
"Expected synchronization scope name");
2765 auto EndParenAt = Lex.
getLoc();
2767 return error(EndParenAt,
"Expected ')' in syncscope");
2782 return tokError(
"Expected ordering on atomic instruction");
2801bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2803 if (!EatIfPresent(lltok::kw_alignstack))
2807 return error(ParenLoc,
"expected '('");
2809 if (parseUInt32(Alignment))
2813 return error(ParenLoc,
"expected ')'");
2815 return error(AlignLoc,
"stack alignment is not a power of two");
2829 bool &AteExtraComma) {
2830 AteExtraComma =
false;
2833 return tokError(
"expected ',' as start of index list");
2837 if (Indices.
empty())
2838 return tokError(
"expected index");
2839 AteExtraComma =
true;
2843 if (parseUInt32(
Idx))
2856bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2860 return tokError(Msg);
2869 if (
Result->isPointerTy()) {
2871 if (parseOptionalAddrSpace(AddrSpace))
2877 return tokError(
"ptr* is invalid - use ptr instead");
2888 if (parseTargetExtType(Result))
2894 if (parseAnonStructType(Result,
false))
2900 if (parseArrayVectorType(Result,
false))
2907 if (parseAnonStructType(Result,
true) ||
2908 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2910 }
else if (parseArrayVectorType(Result,
true))
2949 if (!AllowVoid &&
Result->isVoidTy())
2950 return error(TypeLoc,
"void type only allowed for function results");
2956 return tokError(
"basic block pointers are invalid");
2958 return tokError(
"pointers to void are invalid - use i8* instead");
2960 return tokError(
"pointer to this type is invalid");
2968 return tokError(
"basic block pointers are invalid");
2970 return tokError(
"pointers to void are invalid; use i8* instead");
2972 return tokError(
"pointer to this type is invalid");
2974 if (parseOptionalAddrSpace(AddrSpace) ||
2975 parseToken(
lltok::star,
"expected '*' in address space"))
2984 if (parseFunctionType(Result))
2997 PerFunctionState &PFS,
bool IsMustTailCall,
2998 bool InVarArgsFunc) {
3004 if (!ArgList.
empty() &&
3005 parseToken(
lltok::comma,
"expected ',' in argument list"))
3010 const char *Msg =
"unexpected ellipsis in argument list for ";
3011 if (!IsMustTailCall)
3012 return tokError(
Twine(Msg) +
"non-musttail call");
3014 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
3016 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3021 Type *ArgTy =
nullptr;
3023 if (parseType(ArgTy, ArgLoc))
3029 if (parseMetadataAsValue(V, PFS))
3033 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3040 if (IsMustTailCall && InVarArgsFunc)
3041 return tokError(
"expected '...' at end of argument list for musttail call "
3042 "in varargs function");
3053 if (!EatIfPresent(AttrToken))
3062 B.addTypeAttr(AttrKind, Ty);
3078 return tokError(
"expected integer");
3081 "integer is too large for the bit width of specified type");
3087 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3090 return error(TyLoc,
"the range must have integer type!");
3098 return tokError(
"the range should not represent the full or empty set!");
3112 auto ParseAPSInt = [&](
APInt &Val) {
3114 return tokError(
"expected integer");
3135 return tokError(
"the range should not represent the full or empty set!");
3147 if (!CRLOrNull.has_value())
3148 return tokError(
"Invalid (unordered or overlapping) range list");
3149 B.addInitializesAttr(*CRLOrNull);
3162bool LLParser::parseOptionalOperandBundles(
3170 if (!BundleList.
empty() &&
3171 parseToken(
lltok::comma,
"expected ',' in input list"))
3175 if (parseStringConstant(
Tag))
3178 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3181 std::vector<Value *> Inputs;
3184 if (!Inputs.empty() &&
3185 parseToken(
lltok::comma,
"expected ',' in input list"))
3189 Value *Input =
nullptr;
3190 if (parseType(Ty) || parseValue(Ty, Input, PFS))
3192 Inputs.push_back(Input);
3200 if (BundleList.
empty())
3201 return error(BeginLoc,
"operand bundle set must not be empty");
3208 unsigned NextID,
unsigned ID)
const {
3210 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3211 Twine(NextID) +
"' or greater");
3228 unsigned CurValID = 0;
3243 Type *ArgTy =
nullptr;
3245 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3249 return error(TypeLoc,
"argument can not have void type");
3259 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3266 CurValID = ArgID + 1;
3270 return error(TypeLoc,
"invalid type for function argument");
3278 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3283bool LLParser::parseFunctionType(
Type *&Result) {
3287 return tokError(
"invalid function return type");
3292 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3296 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
3297 if (!ArgList[i].
Name.empty())
3298 return error(ArgList[i].Loc,
"argument name invalid in function type");
3299 if (ArgList[i].
Attrs.hasAttributes())
3300 return error(ArgList[i].Loc,
3301 "argument attributes invalid in function type");
3305 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
3314bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3316 if (parseStructBody(Elts))
3325 std::pair<Type *, LocTy> &Entry,
3329 return error(TypeLoc,
"redefinition of type");
3340 ResultTy =
Entry.first;
3352 return error(TypeLoc,
"forward references to non-struct type");
3356 return parseArrayVectorType(ResultTy,
true);
3357 return parseType(ResultTy);
3370 if (parseStructBody(Body) ||
3371 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3400 return error(EltTyLoc,
"invalid element type for struct");
3408 return error(EltTyLoc,
"invalid element type for struct");
3413 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3422bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3423 bool Scalable =
false;
3427 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3435 return tokError(
"expected number in address space");
3441 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3445 Type *EltTy =
nullptr;
3446 if (parseType(EltTy))
3450 "expected end of sequential type"))
3455 return error(SizeLoc,
"zero element vector is illegal");
3457 return error(SizeLoc,
"size too large for vector");
3459 return error(TypeLoc,
"invalid vector element type");
3463 return error(TypeLoc,
"invalid array element type");
3480bool LLParser::parseTargetExtType(
Type *&Result) {
3485 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3486 parseStringConstant(TypeName))
3494 bool SeenInt =
false;
3501 if (parseUInt32(IntVal))
3504 }
else if (SeenInt) {
3507 return tokError(
"expected uint32 param");
3510 if (parseType(TypeParam,
true))
3516 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3530 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3533 auto It = UnnamedArgNums.
begin();
3536 unsigned ArgNum = *It++;
3537 NumberedVals.add(ArgNum, &
A);
3542LLParser::PerFunctionState::~PerFunctionState() {
3545 for (
const auto &
P : ForwardRefVals) {
3546 if (isa<BasicBlock>(
P.second.first))
3548 P.second.first->replaceAllUsesWith(
3550 P.second.first->deleteValue();
3553 for (
const auto &
P : ForwardRefValIDs) {
3554 if (isa<BasicBlock>(
P.second.first))
3556 P.second.first->replaceAllUsesWith(
3558 P.second.first->deleteValue();
3562bool LLParser::PerFunctionState::finishFunction() {
3563 if (!ForwardRefVals.empty())
3564 return P.error(ForwardRefVals.begin()->second.second,
3565 "use of undefined value '%" + ForwardRefVals.begin()->first +
3567 if (!ForwardRefValIDs.empty())
3568 return P.error(ForwardRefValIDs.begin()->second.second,
3569 "use of undefined value '%" +
3570 Twine(ForwardRefValIDs.begin()->first) +
"'");
3577Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3580 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3585 auto I = ForwardRefVals.find(
Name);
3586 if (
I != ForwardRefVals.end())
3587 Val =
I->second.first;
3592 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3596 P.error(Loc,
"invalid use of a non-first-class type");
3608 P.error(Loc,
"name is too long which can result in name collisions, "
3609 "consider making the name shorter or "
3610 "increasing -non-global-value-max-name-size");
3614 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3618Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3620 Value *Val = NumberedVals.get(
ID);
3625 auto I = ForwardRefValIDs.find(
ID);
3626 if (
I != ForwardRefValIDs.end())
3627 Val =
I->second.first;
3632 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3635 P.error(Loc,
"invalid use of a non-first-class type");
3647 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3653bool LLParser::PerFunctionState::setInstName(
int NameID,
3654 const std::string &NameStr,
3658 if (NameID != -1 || !NameStr.empty())
3659 return P.error(NameLoc,
"instructions returning void cannot have a name");
3665 if (NameStr.empty()) {
3668 NameID = NumberedVals.getNext();
3670 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3674 auto FI = ForwardRefValIDs.find(NameID);
3675 if (FI != ForwardRefValIDs.end()) {
3678 return P.error(NameLoc,
"instruction forward referenced with type '" +
3682 Sentinel->replaceAllUsesWith(Inst);
3684 ForwardRefValIDs.erase(FI);
3687 NumberedVals.add(NameID, Inst);
3692 auto FI = ForwardRefVals.find(NameStr);
3693 if (FI != ForwardRefVals.end()) {
3696 return P.error(NameLoc,
"instruction forward referenced with type '" +
3700 Sentinel->replaceAllUsesWith(Inst);
3702 ForwardRefVals.erase(FI);
3708 if (Inst->
getName() != NameStr)
3709 return P.error(NameLoc,
"multiple definition of local value named '" +
3716BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3718 return dyn_cast_or_null<BasicBlock>(
3722BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3723 return dyn_cast_or_null<BasicBlock>(
3730BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3731 int NameID, LocTy Loc) {
3735 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3738 NameID = NumberedVals.getNext();
3740 BB = getBB(NameID, Loc);
3742 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3746 BB = getBB(
Name, Loc);
3748 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3759 ForwardRefValIDs.erase(NameID);
3760 NumberedVals.add(NameID, BB);
3763 ForwardRefVals.erase(
Name);
3780bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3784 return tokError(
"expected value token");
3827 if (parseGlobalValueVector(Elts) ||
3828 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3831 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3832 ID.UIntVal = Elts.
size();
3833 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3834 Elts.
size() *
sizeof(Elts[0]));
3846 if (parseGlobalValueVector(Elts) ||
3848 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3852 if (isPackedStruct) {
3853 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3854 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3855 Elts.
size() *
sizeof(Elts[0]));
3856 ID.UIntVal = Elts.
size();
3862 return error(
ID.Loc,
"constant vector must not be empty");
3864 if (!Elts[0]->
getType()->isIntegerTy() &&
3865 !Elts[0]->
getType()->isFloatingPointTy() &&
3869 "vector elements must have integer, pointer or floating point type");
3872 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3874 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3875 " is not of type '" +
3886 if (parseGlobalValueVector(Elts) ||
3898 if (!Elts[0]->
getType()->isFirstClassType())
3899 return error(FirstEltLoc,
"invalid array element type: " +
3905 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3907 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3908 " is not of type '" +
3928 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3931 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3934 parseStringConstant(
ID.StrVal) ||
3935 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3940 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
3951 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3952 parseValID(Fn, PFS) ||
3954 "expected comma in block address expression") ||
3955 parseValID(Label, PFS) ||
3956 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
3960 return error(Fn.
Loc,
"expected function name in blockaddress");
3962 return error(
Label.Loc,
"expected basic block name in blockaddress");
3967 GV = NumberedVals.get(Fn.
UIntVal);
3968 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3969 GV =
M->getNamedValue(Fn.
StrVal);
3974 if (!isa<Function>(GV))
3975 return error(Fn.
Loc,
"expected function name in blockaddress");
3976 F = cast<Function>(GV);
3977 if (
F->isDeclaration())
3978 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
3984 ForwardRefBlockAddresses.insert(std::make_pair(
3986 std::map<ValID, GlobalValue *>()))
3987 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
3996 "type of blockaddress must be a pointer and not '" +
4001 FwdDeclAS = PFS->getFunction().getAddressSpace();
4010 ID.ConstantVal = FwdRef;
4018 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4020 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4022 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4024 return error(
Label.Loc,
"referenced value is not a basic block");
4027 return error(
Label.Loc,
"cannot take address of numeric label after "
4028 "the function is defined");
4029 BB = dyn_cast_or_null<BasicBlock>(
4030 F->getValueSymbolTable()->lookup(
Label.StrVal));
4032 return error(
Label.Loc,
"referenced value is not a basic block");
4046 if (parseValID(Fn, PFS))
4051 "expected global value name in dso_local_equivalent");
4056 GV = NumberedVals.get(Fn.
UIntVal);
4057 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4058 GV =
M->getNamedValue(Fn.
StrVal);
4064 ? ForwardRefDSOLocalEquivalentIDs
4065 : ForwardRefDSOLocalEquivalentNames;
4066 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn,
nullptr).first->second;
4073 ID.ConstantVal = FwdRef;
4079 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4080 "in dso_local_equivalent");
4091 if (parseValID(
ID, PFS))
4095 return error(
ID.Loc,
"expected global value name in no_cfi");
4106 Constant *Disc =
nullptr, *AddrDisc =
nullptr;
4109 "expected '(' in constant ptrauth expression") ||
4110 parseGlobalTypeAndValue(
Ptr) ||
4112 "expected comma in constant ptrauth expression") ||
4113 parseGlobalTypeAndValue(Key))
4117 if (parseGlobalTypeAndValue(Disc) ||
4118 (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4121 "expected ')' in constant ptrauth expression"))
4124 if (!
Ptr->getType()->isPointerTy())
4125 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4127 auto *KeyC = dyn_cast<ConstantInt>(Key);
4128 if (!KeyC || KeyC->getBitWidth() != 32)
4129 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4133 DiscC = dyn_cast<ConstantInt>(Disc);
4137 "constant ptrauth integer discriminator must be i64 constant");
4143 if (!AddrDisc->getType()->isPointerTy())
4145 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4161 Type *DestTy =
nullptr;
4164 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4165 parseGlobalTypeAndValue(SrcVal) ||
4166 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4167 parseType(DestTy) ||
4168 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4171 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4180 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4182 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4184 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4186 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4188 return error(
ID.Loc,
"urem constexprs are no longer supported");
4190 return error(
ID.Loc,
"srem constexprs are no longer supported");
4192 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4194 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4196 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4198 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4200 return error(
ID.Loc,
"frem constexprs are no longer supported");
4202 return error(
ID.Loc,
"and constexprs are no longer supported");
4204 return error(
ID.Loc,
"or constexprs are no longer supported");
4206 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4208 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4210 return error(
ID.Loc,
"shl constexprs are no longer supported");
4212 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4214 return error(
ID.Loc,
"select constexprs are no longer supported");
4216 return error(
ID.Loc,
"zext constexprs are no longer supported");
4218 return error(
ID.Loc,
"sext constexprs are no longer supported");
4220 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4222 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4224 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4226 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4228 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4230 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4232 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4234 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4246 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4247 Opc == Instruction::Mul) {
4256 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4257 parseGlobalTypeAndValue(Val0) ||
4258 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4259 parseGlobalTypeAndValue(Val1) ||
4260 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4263 return error(
ID.Loc,
"operands of constexpr must have same type");
4267 "constexpr requires integer or integer vector operands");
4278 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4281 if (parseGlobalTypeAndValue(
C))
4283 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4298 bool HasInRange =
false;
4304 if (Opc == Instruction::GetElementPtr) {
4320 return tokError(
"expected integer");
4326 return tokError(
"expected integer");
4335 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4338 if (Opc == Instruction::GetElementPtr) {
4339 if (parseType(Ty) ||
4340 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4344 if (parseGlobalValueVector(Elts) ||
4348 if (Opc == Instruction::GetElementPtr) {
4349 if (Elts.
size() == 0 ||
4350 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4351 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4354 std::optional<ConstantRange>
InRange;
4356 unsigned IndexWidth =
4357 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4358 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4359 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4360 if (InRangeStart.
sge(InRangeEnd))
4361 return error(
ID.Loc,
"expected end to be larger than start");
4367 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4374 return error(
ID.Loc,
"getelementptr index must be an integer");
4375 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4376 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4377 if (GEPWidth && (ValNumEl != GEPWidth))
4380 "getelementptr vector index has a wrong number of elements");
4383 GEPWidth = ValNumEl;
4388 if (!Indices.empty() && !Ty->
isSized(&Visited))
4389 return error(
ID.Loc,
"base element of getelementptr must be sized");
4392 return error(
ID.Loc,
"invalid getelementptr indices");
4396 }
else if (Opc == Instruction::ShuffleVector) {
4397 if (Elts.
size() != 3)
4398 return error(
ID.Loc,
"expected three operands to shufflevector");
4400 return error(
ID.Loc,
"invalid operands to shufflevector");
4404 }
else if (Opc == Instruction::ExtractElement) {
4405 if (Elts.
size() != 2)
4406 return error(
ID.Loc,
"expected two operands to extractelement");
4408 return error(
ID.Loc,
"invalid extractelement operands");
4411 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4412 if (Elts.
size() != 3)
4413 return error(
ID.Loc,
"expected three operands to insertelement");
4415 return error(
ID.Loc,
"invalid insertelement operands");
4434 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4435 convertValIDToValue(Ty,
ID, V,
nullptr);
4436 if (V && !(
C = dyn_cast<Constant>(V)))
4437 return error(
ID.Loc,
"global values must be constants");
4441bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4443 return parseType(Ty) || parseGlobalValue(Ty, V);
4455 return tokError(
"expected comdat variable");
4458 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4461 if (GlobalName.
empty())
4462 return tokError(
"comdat cannot be unnamed");
4463 C = getComdat(std::string(GlobalName), KwLoc);
4486 if (parseGlobalTypeAndValue(
C))
4494bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4496 if (parseMDNodeVector(Elts))
4507bool LLParser::parseMDNode(
MDNode *&
N) {
4509 return parseSpecializedMDNode(
N);
4511 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4514bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4517 return parseMDTuple(
N);
4520 return parseMDNodeID(
N);
4526template <
class FieldTy>
struct MDFieldImpl {
4527 typedef MDFieldImpl ImplTy;
4531 void assign(FieldTy Val) {
4533 this->Val = std::move(Val);
4536 explicit MDFieldImpl(FieldTy
Default)
4544template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4545 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4556 void assign(FieldTypeA
A) {
4558 this->A = std::move(
A);
4562 void assign(FieldTypeB
B) {
4564 this->B = std::move(
B);
4568 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4570 WhatIs(IsInvalid) {}
4573struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4580struct LineField :
public MDUnsignedField {
4581 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4584struct ColumnField :
public MDUnsignedField {
4585 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4588struct DwarfTagField :
public MDUnsignedField {
4594struct DwarfMacinfoTypeField :
public MDUnsignedField {
4600struct DwarfAttEncodingField :
public MDUnsignedField {
4601 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4604struct DwarfVirtualityField :
public MDUnsignedField {
4608struct DwarfLangField :
public MDUnsignedField {
4612struct DwarfCCField :
public MDUnsignedField {
4613 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4616struct EmissionKindField :
public MDUnsignedField {
4617 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4620struct NameTableKindField :
public MDUnsignedField {
4621 NameTableKindField()
4624 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4627struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4628 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4631struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4632 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4635struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4636 MDAPSIntField() : ImplTy(
APSInt()) {}
4639struct MDSignedField :
public MDFieldImpl<int64_t> {
4643 MDSignedField(int64_t
Default = 0)
4645 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4649struct MDBoolField :
public MDFieldImpl<bool> {
4653struct MDField :
public MDFieldImpl<Metadata *> {
4656 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4659struct MDStringField :
public MDFieldImpl<MDString *> {
4661 MDStringField(
bool AllowEmpty =
true)
4662 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4665struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4669struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4673struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4674 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4675 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4677 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4678 bool AllowNull =
true)
4679 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4681 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4682 bool isMDField()
const {
return WhatIs == IsTypeB; }
4683 int64_t getMDSignedValue()
const {
4684 assert(isMDSignedField() &&
"Wrong field type");
4687 Metadata *getMDFieldValue()
const {
4688 assert(isMDField() &&
"Wrong field type");
4700 return tokError(
"expected integer");
4709 MDUnsignedField &Result) {
4711 return tokError(
"expected unsigned integer");
4714 if (U.ugt(Result.Max))
4715 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4717 Result.assign(U.getZExtValue());
4718 assert(Result.Val <= Result.Max &&
"Expected value in range");
4725 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4729 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4735 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4738 return tokError(
"expected DWARF tag");
4742 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4743 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4752 DwarfMacinfoTypeField &Result) {
4754 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4757 return tokError(
"expected DWARF macinfo type");
4761 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4763 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4765 Result.assign(Macinfo);
4772 DwarfVirtualityField &Result) {
4774 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4777 return tokError(
"expected DWARF virtuality code");
4781 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4783 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4784 Result.assign(Virtuality);
4792 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4795 return tokError(
"expected DWARF language");
4799 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4801 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4802 Result.assign(Lang);
4810 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4813 return tokError(
"expected DWARF calling convention");
4817 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4819 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4827 EmissionKindField &Result) {
4829 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4832 return tokError(
"expected emission kind");
4836 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4838 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4839 Result.assign(*Kind);
4846 NameTableKindField &Result) {
4848 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4851 return tokError(
"expected nameTable kind");
4855 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4857 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4858 Result.assign((
unsigned)*Kind);
4865 DwarfAttEncodingField &Result) {
4867 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4870 return tokError(
"expected DWARF type attribute encoding");
4874 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
4876 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
4877 Result.assign(Encoding);
4893 bool Res = parseUInt32(TempVal);
4899 return tokError(
"expected debug info flag");
4903 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
4918 Result.assign(Combined);
4933 bool Res = parseUInt32(TempVal);
4939 return tokError(
"expected debug info flag");
4943 return tokError(
Twine(
"invalid subprogram debug info flag '") +
4958 Result.assign(Combined);
4965 return tokError(
"expected signed integer");
4969 return tokError(
"value for '" +
Name +
"' too small, limit is " +
4972 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4974 Result.assign(S.getExtValue());
4975 assert(Result.Val >= Result.Min &&
"Expected value in range");
4976 assert(Result.Val <= Result.Max &&
"Expected value in range");
4985 return tokError(
"expected 'true' or 'false'");
4987 Result.assign(
true);
4990 Result.assign(
false);
5000 if (!Result.AllowNull)
5001 return tokError(
"'" +
Name +
"' cannot be null");
5003 Result.assign(
nullptr);
5008 if (parseMetadata(MD,
nullptr))
5017 MDSignedOrMDField &Result) {
5020 MDSignedField Res = Result.A;
5021 if (!parseMDField(Loc,
Name, Res)) {
5029 MDField Res = Result.B;
5030 if (!parseMDField(Loc,
Name, Res)) {
5042 if (parseStringConstant(S))
5045 if (!Result.AllowEmpty && S.empty())
5046 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
5048 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
5055 if (parseMDNodeVector(MDs))
5058 Result.assign(std::move(MDs));
5064 ChecksumKindField &Result) {
5065 std::optional<DIFile::ChecksumKind> CSKind =
5069 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
5072 Result.assign(*CSKind);
5079template <
class ParserTy>
5080bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5083 return tokError(
"expected field label here");
5092template <
class ParserTy>
5093bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5100 if (parseMDFieldsImplBody(ParseField))
5103 ClosingLoc = Lex.
getLoc();
5107template <
class FieldTy>
5108bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5110 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
5114 return parseMDField(Loc,
Name, Result);
5117bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5120#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5121 if (Lex.getStrVal() == #CLASS) \
5122 return parse##CLASS(N, IsDistinct);
5123#include "llvm/IR/Metadata.def"
5125 return tokError(
"expected metadata type");
5128#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5129#define NOP_FIELD(NAME, TYPE, INIT)
5130#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5132 return error(ClosingLoc, "missing required field '" #NAME "'");
5133#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5134 if (Lex.getStrVal() == #NAME) \
5135 return parseMDField(#NAME, NAME);
5136#define PARSE_MD_FIELDS() \
5137 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5140 if (parseMDFieldsImpl( \
5142 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5143 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5148 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5150#define GET_OR_DISTINCT(CLASS, ARGS) \
5151 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5156bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5157#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5158 OPTIONAL(line, LineField, ); \
5159 OPTIONAL(column, ColumnField, ); \
5160 REQUIRED(scope, MDField, ( false)); \
5161 OPTIONAL(inlinedAt, MDField, ); \
5162 OPTIONAL(isImplicitCode, MDBoolField, (false));
5164#undef VISIT_MD_FIELDS
5168 inlinedAt.Val, isImplicitCode.Val));
5174bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5176 return Lex.
Error(
"missing 'distinct', required for !DIAssignID()");
5192bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5193#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5194 REQUIRED(tag, DwarfTagField, ); \
5195 OPTIONAL(header, MDStringField, ); \
5196 OPTIONAL(operands, MDFieldList, );
5198#undef VISIT_MD_FIELDS
5201 (Context, tag.Val, header.Val, operands.Val));
5209bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5210#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5211 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5212 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5213 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5214 OPTIONAL(stride, MDSignedOrMDField, );
5216#undef VISIT_MD_FIELDS
5223 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5224 if (Bound.isMDSignedField())
5227 if (Bound.isMDField())
5228 return Bound.getMDFieldValue();
5232 Count = convToMetadata(
count);
5233 LowerBound = convToMetadata(lowerBound);
5235 Stride = convToMetadata(stride);
5238 (Context, Count, LowerBound, UpperBound, Stride));
5246bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5247#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5248 OPTIONAL(count, MDSignedOrMDField, ); \
5249 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5250 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5251 OPTIONAL(stride, MDSignedOrMDField, );
5253#undef VISIT_MD_FIELDS
5255 auto ConvToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5256 if (Bound.isMDSignedField())
5258 Context, {dwarf::DW_OP_consts,
5259 static_cast<uint64_t>(Bound.getMDSignedValue())});
5260 if (Bound.isMDField())
5261 return Bound.getMDFieldValue();
5266 Metadata *LowerBound = ConvToMetadata(lowerBound);
5268 Metadata *Stride = ConvToMetadata(stride);
5271 (Context, Count, LowerBound, UpperBound, Stride));
5278bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5279#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5280 REQUIRED(name, MDStringField, ); \
5281 REQUIRED(value, MDAPSIntField, ); \
5282 OPTIONAL(isUnsigned, MDBoolField, (false));
5284#undef VISIT_MD_FIELDS
5286 if (isUnsigned.Val &&
value.Val.isNegative())
5287 return tokError(
"unsigned enumerator with negative value");
5292 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())
5304bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5305#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5306 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5307 OPTIONAL(name, MDStringField, ); \
5308 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5309 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5310 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5311 OPTIONAL(flags, DIFlagField, );
5313#undef VISIT_MD_FIELDS
5316 align.Val, encoding.Val, flags.Val));
5322bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5323#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5324 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5325 OPTIONAL(name, MDStringField, ); \
5326 OPTIONAL(stringLength, MDField, ); \
5327 OPTIONAL(stringLengthExpression, MDField, ); \
5328 OPTIONAL(stringLocationExpression, MDField, ); \
5329 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5330 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5331 OPTIONAL(encoding, DwarfAttEncodingField, );
5333#undef VISIT_MD_FIELDS
5337 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5338 stringLocationExpression.Val,
size.Val, align.Val, encoding.Val));
5351bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5352#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5353 REQUIRED(tag, DwarfTagField, ); \
5354 OPTIONAL(name, MDStringField, ); \
5355 OPTIONAL(file, MDField, ); \
5356 OPTIONAL(line, LineField, ); \
5357 OPTIONAL(scope, MDField, ); \
5358 REQUIRED(baseType, MDField, ); \
5359 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5360 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5361 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5362 OPTIONAL(flags, DIFlagField, ); \
5363 OPTIONAL(extraData, MDField, ); \
5364 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5365 OPTIONAL(annotations, MDField, ); \
5366 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5367 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5368 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5369 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5370 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5372#undef VISIT_MD_FIELDS
5374 std::optional<unsigned> DWARFAddressSpace;
5375 if (dwarfAddressSpace.Val != UINT32_MAX)
5376 DWARFAddressSpace = dwarfAddressSpace.Val;
5377 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5379 PtrAuthData.emplace(
5380 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5381 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5382 ptrAuthAuthenticatesNullValues.Val);
5385 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5386 scope.Val, baseType.Val,
size.Val, align.Val,
5387 offset.Val, DWARFAddressSpace, PtrAuthData,
5388 flags.Val, extraData.Val, annotations.Val));
5392bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5393#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5394 REQUIRED(tag, DwarfTagField, ); \
5395 OPTIONAL(name, MDStringField, ); \
5396 OPTIONAL(file, MDField, ); \
5397 OPTIONAL(line, LineField, ); \
5398 OPTIONAL(scope, MDField, ); \
5399 OPTIONAL(baseType, MDField, ); \
5400 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5401 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5402 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5403 OPTIONAL(flags, DIFlagField, ); \
5404 OPTIONAL(elements, MDField, ); \
5405 OPTIONAL(runtimeLang, DwarfLangField, ); \
5406 OPTIONAL(vtableHolder, MDField, ); \
5407 OPTIONAL(templateParams, MDField, ); \
5408 OPTIONAL(identifier, MDStringField, ); \
5409 OPTIONAL(discriminator, MDField, ); \
5410 OPTIONAL(dataLocation, MDField, ); \
5411 OPTIONAL(associated, MDField, ); \
5412 OPTIONAL(allocated, MDField, ); \
5413 OPTIONAL(rank, MDSignedOrMDField, ); \
5414 OPTIONAL(annotations, MDField, );
5416#undef VISIT_MD_FIELDS
5419 if (
rank.isMDSignedField())
5422 else if (
rank.isMDField())
5423 Rank =
rank.getMDFieldValue();
5428 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5429 scope.Val, baseType.Val,
size.Val, align.Val, offset.Val, flags.Val,
5430 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5431 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5432 Rank, annotations.Val)) {
5441 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5442 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5443 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5444 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5449bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5450#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5451 OPTIONAL(flags, DIFlagField, ); \
5452 OPTIONAL(cc, DwarfCCField, ); \
5453 REQUIRED(types, MDField, );
5455#undef VISIT_MD_FIELDS
5458 (Context, flags.Val, cc.Val, types.Val));
5467bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5471#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5472 REQUIRED(filename, MDStringField, ); \
5473 REQUIRED(directory, MDStringField, ); \
5474 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5475 OPTIONAL(checksum, MDStringField, ); \
5476 OPTIONAL(source, MDStringField, );
5478#undef VISIT_MD_FIELDS
5480 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5481 if (checksumkind.Seen && checksum.Seen)
5482 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5483 else if (checksumkind.Seen || checksum.Seen)
5484 return Lex.
Error(
"'checksumkind' and 'checksum' must be provided together");
5490 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5501bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5503 return Lex.
Error(
"missing 'distinct', required for !DICompileUnit");
5505#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5506 REQUIRED(language, DwarfLangField, ); \
5507 REQUIRED(file, MDField, ( false)); \
5508 OPTIONAL(producer, MDStringField, ); \
5509 OPTIONAL(isOptimized, MDBoolField, ); \
5510 OPTIONAL(flags, MDStringField, ); \
5511 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5512 OPTIONAL(splitDebugFilename, MDStringField, ); \
5513 OPTIONAL(emissionKind, EmissionKindField, ); \
5514 OPTIONAL(enums, MDField, ); \
5515 OPTIONAL(retainedTypes, MDField, ); \
5516 OPTIONAL(globals, MDField, ); \
5517 OPTIONAL(imports, MDField, ); \
5518 OPTIONAL(macros, MDField, ); \
5519 OPTIONAL(dwoId, MDUnsignedField, ); \
5520 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5521 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5522 OPTIONAL(nameTableKind, NameTableKindField, ); \
5523 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5524 OPTIONAL(sysroot, MDStringField, ); \
5525 OPTIONAL(sdk, MDStringField, );
5527#undef VISIT_MD_FIELDS
5530 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5531 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5532 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5533 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5534 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5547bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5549#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5550 OPTIONAL(scope, MDField, ); \
5551 OPTIONAL(name, MDStringField, ); \
5552 OPTIONAL(linkageName, MDStringField, ); \
5553 OPTIONAL(file, MDField, ); \
5554 OPTIONAL(line, LineField, ); \
5555 OPTIONAL(type, MDField, ); \
5556 OPTIONAL(isLocal, MDBoolField, ); \
5557 OPTIONAL(isDefinition, MDBoolField, (true)); \
5558 OPTIONAL(scopeLine, LineField, ); \
5559 OPTIONAL(containingType, MDField, ); \
5560 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5561 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5562 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5563 OPTIONAL(flags, DIFlagField, ); \
5564 OPTIONAL(spFlags, DISPFlagField, ); \
5565 OPTIONAL(isOptimized, MDBoolField, ); \
5566 OPTIONAL(unit, MDField, ); \
5567 OPTIONAL(templateParams, MDField, ); \
5568 OPTIONAL(declaration, MDField, ); \
5569 OPTIONAL(retainedNodes, MDField, ); \
5570 OPTIONAL(thrownTypes, MDField, ); \
5571 OPTIONAL(annotations, MDField, ); \
5572 OPTIONAL(targetFuncName, MDStringField, );
5574#undef VISIT_MD_FIELDS
5579 spFlags.Seen ? spFlags.Val
5581 isOptimized.Val, virtuality.Val);
5582 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5585 "missing 'distinct', required for !DISubprogram that is a Definition");
5588 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5589 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5590 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5591 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5592 targetFuncName.Val));
5598bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5599#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5600 REQUIRED(scope, MDField, ( false)); \
5601 OPTIONAL(file, MDField, ); \
5602 OPTIONAL(line, LineField, ); \
5603 OPTIONAL(column, ColumnField, );
5605#undef VISIT_MD_FIELDS
5614bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5615#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5616 REQUIRED(scope, MDField, ( false)); \
5617 OPTIONAL(file, MDField, ); \
5618 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5620#undef VISIT_MD_FIELDS
5623 (Context, scope.Val,
file.Val, discriminator.Val));
5629bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5630#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5631 REQUIRED(scope, MDField, ); \
5632 OPTIONAL(declaration, MDField, ); \
5633 OPTIONAL(name, MDStringField, ); \
5634 OPTIONAL(file, MDField, ); \
5635 OPTIONAL(line, LineField, );
5637#undef VISIT_MD_FIELDS
5640 (Context, scope.Val, declaration.Val,
name.Val,
5641 file.Val, line.Val));
5647bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5648#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5649 REQUIRED(scope, MDField, ); \
5650 OPTIONAL(name, MDStringField, ); \
5651 OPTIONAL(exportSymbols, MDBoolField, );
5653#undef VISIT_MD_FIELDS
5656 (Context, scope.Val,
name.Val, exportSymbols.Val));
5663bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5664#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5665 REQUIRED(type, DwarfMacinfoTypeField, ); \
5666 OPTIONAL(line, LineField, ); \
5667 REQUIRED(name, MDStringField, ); \
5668 OPTIONAL(value, MDStringField, );
5670#undef VISIT_MD_FIELDS
5673 (Context, type.Val, line.Val,
name.Val,
value.Val));
5679bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
5680#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5681 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5682 OPTIONAL(line, LineField, ); \
5683 REQUIRED(file, MDField, ); \
5684 OPTIONAL(nodes, MDField, );
5686#undef VISIT_MD_FIELDS
5689 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
5697bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
5698#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5699 REQUIRED(scope, MDField, ); \
5700 REQUIRED(name, MDStringField, ); \
5701 OPTIONAL(configMacros, MDStringField, ); \
5702 OPTIONAL(includePath, MDStringField, ); \
5703 OPTIONAL(apinotes, MDStringField, ); \
5704 OPTIONAL(file, MDField, ); \
5705 OPTIONAL(line, LineField, ); \
5706 OPTIONAL(isDecl, MDBoolField, );
5708#undef VISIT_MD_FIELDS
5711 configMacros.Val, includePath.Val,
5712 apinotes.Val, line.Val, isDecl.Val));
5718bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
5719#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5720 OPTIONAL(name, MDStringField, ); \
5721 REQUIRED(type, MDField, ); \
5722 OPTIONAL(defaulted, MDBoolField, );
5724#undef VISIT_MD_FIELDS
5727 (Context,
name.Val, type.Val, defaulted.Val));
5735bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
5736#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5737 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5738 OPTIONAL(name, MDStringField, ); \
5739 OPTIONAL(type, MDField, ); \
5740 OPTIONAL(defaulted, MDBoolField, ); \
5741 REQUIRED(value, MDField, );
5744#undef VISIT_MD_FIELDS
5748 (Context, tag.Val,
name.Val, type.Val, defaulted.Val,
value.Val));
5757bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
5758#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5759 OPTIONAL(name, MDStringField, ( false)); \
5760 OPTIONAL(scope, MDField, ); \
5761 OPTIONAL(linkageName, MDStringField, ); \
5762 OPTIONAL(file, MDField, ); \
5763 OPTIONAL(line, LineField, ); \
5764 OPTIONAL(type, MDField, ); \
5765 OPTIONAL(isLocal, MDBoolField, ); \
5766 OPTIONAL(isDefinition, MDBoolField, (true)); \
5767 OPTIONAL(templateParams, MDField, ); \
5768 OPTIONAL(declaration, MDField, ); \
5769 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5770 OPTIONAL(annotations, MDField, );
5772#undef VISIT_MD_FIELDS
5776 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
5777 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5778 declaration.Val, templateParams.Val, align.Val,
5790bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
5791#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5792 REQUIRED(scope, MDField, ( false)); \
5793 OPTIONAL(name, MDStringField, ); \
5794 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5795 OPTIONAL(file, MDField, ); \
5796 OPTIONAL(line, LineField, ); \
5797 OPTIONAL(type, MDField, ); \
5798 OPTIONAL(flags, DIFlagField, ); \
5799 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5800 OPTIONAL(annotations, MDField, );
5802#undef VISIT_MD_FIELDS
5805 (Context, scope.Val,
name.Val,
file.Val, line.Val,
5806 type.Val, arg.Val, flags.Val, align.Val,
5813bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
5814#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5815 REQUIRED(scope, MDField, ( false)); \
5816 REQUIRED(name, MDStringField, ); \
5817 REQUIRED(file, MDField, ); \
5818 REQUIRED(line, LineField, );
5820#undef VISIT_MD_FIELDS
5823 (Context, scope.Val,
name.Val,
file.Val, line.Val));
5829bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
5845 return tokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
5854 return tokError(
Twine(
"invalid DWARF attribute encoding '") +
5859 return tokError(
"expected unsigned integer");
5877bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
5878 assert(PFS &&
"Expected valid function state");
5889 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
5891 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5903bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
5905#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5906 REQUIRED(var, MDField, ); \
5907 REQUIRED(expr, MDField, );
5909#undef VISIT_MD_FIELDS
5919bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
5920#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5921 OPTIONAL(name, MDStringField, ); \
5922 OPTIONAL(file, MDField, ); \
5923 OPTIONAL(line, LineField, ); \
5924 OPTIONAL(setter, MDStringField, ); \
5925 OPTIONAL(getter, MDStringField, ); \
5926 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5927 OPTIONAL(type, MDField, );
5929#undef VISIT_MD_FIELDS
5932 (Context,
name.Val,
file.Val, line.Val, setter.Val,
5933 getter.Val, attributes.Val, type.Val));
5940bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
5941#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5942 REQUIRED(tag, DwarfTagField, ); \
5943 REQUIRED(scope, MDField, ); \
5944 OPTIONAL(entity, MDField, ); \
5945 OPTIONAL(file, MDField, ); \
5946 OPTIONAL(line, LineField, ); \
5947 OPTIONAL(name, MDStringField, ); \
5948 OPTIONAL(elements, MDField, );
5950#undef VISIT_MD_FIELDS
5953 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
5954 line.Val,
name.Val, elements.Val));
5958#undef PARSE_MD_FIELD
5970bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
5973 if (parseMetadata(MD, &PFS))
5984bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
5985 PerFunctionState *PFS) {
5988 if (parseType(Ty, TypeMsg, Loc))
5991 return error(Loc,
"invalid metadata-value-metadata roundtrip");
5994 if (parseValue(Ty, V, PFS))
6009bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6015 if (parseDIArgList(AL, PFS))
6021 if (parseSpecializedMDNode(
N)) {
6031 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6041 if (parseMDString(S))
6051 if (parseMDNodeTail(
N))
6062 PerFunctionState *PFS) {
6064 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6069 return error(
ID.Loc,
"invalid use of function-local name");
6070 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6071 return V ==
nullptr;
6074 return error(
ID.Loc,
"invalid use of function-local name");
6075 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6076 return V ==
nullptr;
6079 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6083 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6088 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6091 return V ==
nullptr;
6093 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6096 return V ==
nullptr;
6099 return error(
ID.Loc,
"integer constant must have integer type");
6101 V = ConstantInt::get(Context,
ID.APSIntVal);
6106 return error(
ID.Loc,
"floating point constant invalid for type");
6112 bool IsSNAN =
ID.APFloatVal.isSignaling();
6127 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
6129 ID.APFloatVal.isNegative(), &Payload);
6132 V = ConstantFP::get(Context,
ID.APFloatVal);
6134 if (
V->getType() != Ty)
6135 return error(
ID.Loc,
"floating point constant does not have type '" +
6141 return error(
ID.Loc,
"null must be a pointer type");
6147 return error(
ID.Loc,
"invalid type for undef constant");
6151 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6152 return error(
ID.Loc,
"invalid empty array initializer");
6158 return error(
ID.Loc,
"invalid type for null constant");
6159 if (
auto *TETy = dyn_cast<TargetExtType>(Ty))
6161 return error(
ID.Loc,
"invalid type for null constant");
6166 return error(
ID.Loc,
"invalid type for none constant");
6172 return error(
ID.Loc,
"invalid type for poison constant");
6176 if (
ID.ConstantVal->getType() != Ty)
6177 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6184 return error(
ID.Loc,
"vector constant must have vector type");
6186 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6188 "' but expected '" +
6195 if (
StructType *ST = dyn_cast<StructType>(Ty)) {
6196 if (
ST->getNumElements() !=
ID.UIntVal)
6198 "initializer with struct type has wrong # elements");
6200 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6203 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6204 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6207 "element " +
Twine(i) +
6208 " of struct initializer doesn't match struct element type");
6211 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6213 return error(
ID.Loc,
"constant expression type mismatch");
6223 if (parseValID(
ID,
nullptr))
6234 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6236 assert(isa<Constant>(V) &&
"Expected a constant value");
6237 C = cast<Constant>(V);
6244 return error(Loc,
"expected a constant value");
6248bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6251 return parseValID(
ID, PFS, Ty) ||
6252 convertValIDToValue(Ty,
ID, V, PFS);
6255bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6257 return parseType(Ty) || parseValue(Ty, V, PFS);
6260bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
6261 PerFunctionState &PFS) {
6264 if (parseTypeAndValue(V, PFS))
6266 if (!isa<BasicBlock>(V))
6267 return error(Loc,
"expected a basic block");
6268 BB = cast<BasicBlock>(V);
6276 if (!
Name.starts_with(
"llvm.dbg."))
6279 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6280 FnID == Intrinsic::dbg_assign;
6288bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6289 unsigned &FunctionNumber,
6294 unsigned Visibility;
6295 unsigned DLLStorageClass;
6300 Type *RetType =
nullptr;
6302 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6304 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
6305 parseType(RetType, RetTypeLoc,
true ))
6314 return error(LinkageLoc,
"invalid linkage for function definition");
6324 return error(LinkageLoc,
"invalid linkage for function declaration");
6328 return error(LinkageLoc,
"invalid function linkage type");
6332 return error(LinkageLoc,
6333 "symbol with local linkage must have default visibility");
6336 return error(LinkageLoc,
6337 "symbol with local linkage cannot have a DLL storage class");
6340 return error(RetTypeLoc,
"invalid function return type");
6344 std::string FunctionName;
6349 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6353 return tokError(
"expected function name");
6359 return tokError(
"expected '(' in function argument list");
6364 std::vector<unsigned> FwdRefAttrGrps;
6367 std::string Partition;
6371 unsigned AddrSpace = 0;
6377 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6378 parseOptionalUnnamedAddr(UnnamedAddr) ||
6379 parseOptionalProgramAddrSpace(AddrSpace) ||
6380 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6384 parseOptionalComdat(FunctionName,
C) ||
6385 parseOptionalAlignment(Alignment) ||
6386 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6390 parseGlobalTypeAndValue(PersonalityFn)))
6393 if (FuncAttrs.contains(Attribute::Builtin))
6394 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6399 FuncAttrs.removeAttribute(Attribute::Alignment);
6404 std::vector<Type*> ParamTypeList;
6407 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
6408 ParamTypeList.push_back(ArgList[i].Ty);
6409 Attrs.push_back(ArgList[i].Attrs);
6417 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6424 if (!FunctionName.empty()) {
6427 auto FRVI = ForwardRefVals.find(FunctionName);
6428 if (FRVI != ForwardRefVals.end()) {
6429 FwdFn = FRVI->second.first;
6431 return error(FRVI->second.second,
6432 "invalid forward reference to "
6435 "' with wrong type: "
6439 ForwardRefVals.erase(FRVI);
6440 }
else if ((Fn =
M->getFunction(FunctionName))) {
6442 return error(NameLoc,
6443 "invalid redefinition of function '" + FunctionName +
"'");
6444 }
else if (
M->getNamedValue(FunctionName)) {
6445 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6451 if (FunctionNumber == (
unsigned)-1)
6452 FunctionNumber = NumberedVals.getNext();
6456 auto I = ForwardRefValIDs.find(FunctionNumber);
6457 if (
I != ForwardRefValIDs.end()) {
6458 FwdFn =
I->second.first;
6460 return error(NameLoc,
"type of definition and forward reference of '@" +
6461 Twine(FunctionNumber) +
6466 ForwardRefValIDs.erase(
I);
6475 if (FunctionName.empty())
6476 NumberedVals.add(FunctionNumber, Fn);
6491 if (!
GC.empty()) Fn->
setGC(GC);
6494 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6498 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i, ++ArgIt) {
6500 if (ArgList[i].
Name.empty())
continue;
6505 if (ArgIt->
getName() != ArgList[i].Name)
6506 return error(ArgList[i].Loc,
6507 "redefinition of argument '%" + ArgList[i].
Name +
"'");
6520 if (FunctionName.empty()) {
6522 ID.UIntVal = FunctionNumber;
6525 ID.StrVal = FunctionName;
6527 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6528 if (
Blocks != ForwardRefBlockAddresses.end())
6530 "cannot take blockaddress inside a declaration");
6534bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6536 if (FunctionNumber == -1) {
6538 ID.StrVal = std::string(
F.getName());
6541 ID.UIntVal = FunctionNumber;
6544 auto Blocks =
P.ForwardRefBlockAddresses.find(
ID);
6545 if (
Blocks ==
P.ForwardRefBlockAddresses.end())
6548 for (
const auto &
I :
Blocks->second) {
6549 const ValID &BBID =
I.first;
6553 "Expected local id or name");
6560 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6571 P.ForwardRefBlockAddresses.erase(
Blocks);
6577bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
6580 return tokError(
"expected '{' in function body");
6583 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6587 if (PFS.resolveForwardRefBlockAddresses())
6593 return tokError(
"function body requires at least one basic block");
6597 if (parseBasicBlock(PFS))
6601 if (parseUseListOrder(&PFS))
6608 return PFS.finishFunction();
6613bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6630 std::string NameStr;
6635 auto DeleteDbgRecord = [](
DbgRecord *DR) { DR->deleteRecord(); };
6636 using DbgRecordPtr = std::unique_ptr<
DbgRecord,
decltype(DeleteDbgRecord)>;
6643 if (SeenOldDbgInfoFormat)
6644 return error(Lex.
getLoc(),
"debug record should not appear in a module "
6645 "containing debug info intrinsics");
6646 if (!SeenNewDbgInfoFormat)
6647 M->setNewDbgInfoFormatFlag(
true);
6648 SeenNewDbgInfoFormat =
true;
6652 if (parseDebugRecord(DR, PFS))
6654 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6666 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
6671 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
6675 switch (parseInstruction(Inst, BB, PFS)) {
6678 case InstError:
return true;
6685 if (parseInstructionMetadata(*Inst))
6688 case InstExtraComma:
6693 if (parseInstructionMetadata(*Inst))
6699 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6703 for (DbgRecordPtr &DR : TrailingDbgRecord)
6705 TrailingDbgRecord.clear();
6708 assert(TrailingDbgRecord.empty() &&
6709 "All debug values should have been attached to an instruction.");
6718bool LLParser::parseDebugRecord(
DbgRecord *&DR, PerFunctionState &PFS) {
6723 return error(DVRLoc,
"expected debug record type here");
6725 .
Case(
"declare", RecordKind::ValueKind)
6726 .
Case(
"value", RecordKind::ValueKind)
6727 .
Case(
"assign", RecordKind::ValueKind)
6728 .
Case(
"label", RecordKind::LabelKind);
6737 if (parseMDNode(Label))
6742 if (parseMDNode(DbgLoc))
6751 .
Case(
"declare", LocType::Declare)
6752 .
Case(
"value", LocType::Value)
6753 .
Case(
"assign", LocType::Assign);
6761 if (parseMetadata(ValLocMD, &PFS))
6768 if (parseMDNode(Variable))
6781 MDNode *AssignID =
nullptr;
6782 Metadata *AddressLocation =
nullptr;
6783 MDNode *AddressExpression =
nullptr;
6786 if (parseMDNode(AssignID))
6792 if (parseMetadata(AddressLocation, &PFS))
6798 if (parseMDNode(AddressExpression))
6823 PerFunctionState &PFS) {
6826 return tokError(
"found end of file when expecting more instructions");
6833 return error(Loc,
"expected instruction opcode");
6837 return parseRet(Inst, BB, PFS);
6839 return parseBr(Inst, PFS);
6841 return parseSwitch(Inst, PFS);
6843 return parseIndirectBr(Inst, PFS);
6845 return parseInvoke(Inst, PFS);
6847 return parseResume(Inst, PFS);
6849 return parseCleanupRet(Inst, PFS);
6851 return parseCatchRet(Inst, PFS);
6853 return parseCatchSwitch(Inst, PFS);
6855 return parseCatchPad(Inst, PFS);
6857 return parseCleanupPad(Inst, PFS);
6859 return parseCallBr(Inst, PFS);
6863 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
6879 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6882 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
6883 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
6892 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
6906 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6908 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
6914 return parseArithmetic(Inst, PFS, KeywordVal,
6918 if (parseLogical(Inst, PFS, KeywordVal))
6921 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(
true);
6926 return parseLogical(Inst, PFS, KeywordVal);
6928 return parseCompare(Inst, PFS, KeywordVal);
6931 int Res = parseCompare(Inst, PFS, KeywordVal);
6943 bool Res = parseCast(Inst, PFS, KeywordVal);
6955 if (parseCast(Inst, PFS, KeywordVal))
6958 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(
true);
6960 cast<TruncInst>(Inst)->setHasNoSignedWrap(
true);
6973 return parseCast(Inst, PFS, KeywordVal);
6977 int Res = parseSelect(Inst, PFS);
6981 if (!isa<FPMathOperator>(Inst))
6982 return error(Loc,
"fast-math-flags specified for select without "
6983 "floating-point scalar or vector return type");
6989 return parseVAArg(Inst, PFS);
6991 return parseExtractElement(Inst, PFS);
6993 return parseInsertElement(Inst, PFS);
6995 return parseShuffleVector(Inst, PFS);
6998 int Res = parsePHI(Inst, PFS);
7002 if (!isa<FPMathOperator>(Inst))
7003 return error(Loc,
"fast-math-flags specified for phi without "
7004 "floating-point scalar or vector return type");
7010 return parseLandingPad(Inst, PFS);
7012 return parseFreeze(Inst, PFS);
7024 return parseAlloc(Inst, PFS);
7026 return parseLoad(Inst, PFS);
7028 return parseStore(Inst, PFS);
7030 return parseCmpXchg(Inst, PFS);
7032 return parseAtomicRMW(Inst, PFS);
7034 return parseFence(Inst, PFS);
7036 return parseGetElementPtr(Inst, PFS);
7038 return parseExtractValue(Inst, PFS);
7040 return parseInsertValue(Inst, PFS);
7045bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7046 if (Opc == Instruction::FCmp) {
7049 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7070 return tokError(
"expected icmp predicate (e.g. 'eq')");
7095 PerFunctionState &PFS) {
7098 if (parseType(Ty,
true ))
7101 Type *ResType = PFS.getFunction().getReturnType();
7105 return error(TypeLoc,
"value doesn't match function result type '" +
7113 if (parseValue(Ty, RV, PFS))
7117 return error(TypeLoc,
"value doesn't match function result type '" +
7127bool LLParser::parseBr(
Instruction *&Inst, PerFunctionState &PFS) {
7131 if (parseTypeAndValue(Op0, Loc, PFS))
7134 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7140 return error(Loc,
"branch condition must have 'i1' type");
7142 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7143 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7144 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7145 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7157bool LLParser::parseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7158 LocTy CondLoc, BBLoc;
7161 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7162 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7163 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7167 if (!
Cond->getType()->isIntegerTy())
7168 return error(CondLoc,
"switch condition must have integer type");
7177 if (parseTypeAndValue(
Constant, CondLoc, PFS) ||
7178 parseToken(
lltok::comma,
"expected ',' after case value") ||
7179 parseTypeAndBasicBlock(DestBB, PFS))
7183 return error(CondLoc,
"duplicate case value in switch");
7185 return error(CondLoc,
"case value is not a constant integer");
7193 for (
unsigned i = 0, e = Table.
size(); i != e; ++i)
7194 SI->addCase(Table[i].first, Table[i].second);
7202bool LLParser::parseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
7205 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7206 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7210 if (!
Address->getType()->isPointerTy())
7211 return error(AddrLoc,
"indirectbr address must have pointer type");
7218 if (parseTypeAndBasicBlock(DestBB, PFS))
7223 if (parseTypeAndBasicBlock(DestBB, PFS))
7229 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7233 for (
unsigned i = 0, e = DestList.
size(); i != e; ++i)
7242bool LLParser::resolveFunctionType(
Type *RetType,
7245 FuncTy = dyn_cast<FunctionType>(RetType);
7248 std::vector<Type*> ParamTypes;
7249 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
7250 ParamTypes.push_back(ArgList[i].
V->getType());
7263bool LLParser::parseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
7265 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7266 std::vector<unsigned> FwdRefAttrGrps;
7269 unsigned InvokeAddrSpace;
7270 Type *RetType =
nullptr;
7277 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7278 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7279 parseType(RetType, RetTypeLoc,
true ) ||
7280 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7281 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7283 parseOptionalOperandBundles(BundleList, PFS) ||
7285 parseTypeAndBasicBlock(NormalBB, PFS) ||
7287 parseTypeAndBasicBlock(UnwindBB, PFS))
7294 if (resolveFunctionType(RetType, ArgList, Ty))
7295 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7313 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7314 Type *ExpectedTy =
nullptr;
7317 }
else if (!Ty->isVarArg()) {
7318 return error(ArgList[i].Loc,
"too many arguments specified");
7321 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7322 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7324 Args.push_back(ArgList[i].V);
7329 return error(CallLoc,
"not enough parameters specified for call");
7338 II->setCallingConv(
CC);
7339 II->setAttributes(PAL);
7340 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
7347bool LLParser::parseResume(
Instruction *&Inst, PerFunctionState &PFS) {
7349 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7358 PerFunctionState &PFS) {
7359 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7364 if (!
Args.empty() &&
7365 parseToken(
lltok::comma,
"expected ',' in argument list"))
7370 Type *ArgTy =
nullptr;
7371 if (parseType(ArgTy, ArgLoc))
7376 if (parseMetadataAsValue(V, PFS))
7379 if (parseValue(ArgTy, V, PFS))
7391bool LLParser::parseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
7392 Value *CleanupPad =
nullptr;
7394 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7409 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7420bool LLParser::parseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
7421 Value *CatchPad =
nullptr;
7423 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7430 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7431 parseTypeAndBasicBlock(BB, PFS))
7440bool LLParser::parseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7448 return tokError(
"expected scope value for catchswitch");
7453 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7459 if (parseTypeAndBasicBlock(DestBB, PFS))
7464 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7467 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7475 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7482 CatchSwitch->addHandler(DestBB);
7489bool LLParser::parseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
7490 Value *CatchSwitch =
nullptr;
7496 return tokError(
"expected scope value for catchpad");
7502 if (parseExceptionArgs(Args, PFS))
7511bool LLParser::parseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
7512 Value *ParentPad =
nullptr;
7519 return tokError(
"expected scope value for cleanuppad");
7525 if (parseExceptionArgs(Args, PFS))
7541bool LLParser::parseUnaryOp(
Instruction *&Inst, PerFunctionState &PFS,
7542 unsigned Opc,
bool IsFP) {
7544 if (parseTypeAndValue(LHS, Loc, PFS))
7551 return error(Loc,
"invalid operand type for instruction");
7561bool LLParser::parseCallBr(
Instruction *&Inst, PerFunctionState &PFS) {
7563 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7564 std::vector<unsigned> FwdRefAttrGrps;
7567 Type *RetType =
nullptr;
7574 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7575 parseType(RetType, RetTypeLoc,
true ) ||
7576 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7577 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7579 parseOptionalOperandBundles(BundleList, PFS) ||
7581 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7590 if (parseTypeAndBasicBlock(DestBB, PFS))
7595 if (parseTypeAndBasicBlock(DestBB, PFS))
7601 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7608 if (resolveFunctionType(RetType, ArgList, Ty))
7609 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7626 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7627 Type *ExpectedTy =
nullptr;
7630 }
else if (!Ty->isVarArg()) {
7631 return error(ArgList[i].Loc,
"too many arguments specified");
7634 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7635 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7637 Args.push_back(ArgList[i].V);
7642 return error(CallLoc,
"not enough parameters specified for call");
7654 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7668bool LLParser::parseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
7669 unsigned Opc,
bool IsFP) {
7671 if (parseTypeAndValue(LHS, Loc, PFS) ||
7672 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
7680 return error(Loc,
"invalid operand type for instruction");
7688bool LLParser::parseLogical(
Instruction *&Inst, PerFunctionState &PFS,
7691 if (parseTypeAndValue(LHS, Loc, PFS) ||
7692 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
7698 "instruction requires integer or integer vector operands");
7707bool LLParser::parseCompare(
Instruction *&Inst, PerFunctionState &PFS,
7713 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7714 parseToken(
lltok::comma,
"expected ',' after compare value") ||
7718 if (Opc == Instruction::FCmp) {
7720 return error(Loc,
"fcmp requires floating point operands");
7723 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
7726 return error(Loc,
"icmp requires integer operands");
7738bool LLParser::parseCast(
Instruction *&Inst, PerFunctionState &PFS,
7742 Type *DestTy =
nullptr;
7743 if (parseTypeAndValue(
Op, Loc, PFS) ||
7744 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
7750 return error(Loc,
"invalid cast opcode for cast from '" +
7760bool LLParser::parseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
7762 Value *Op0, *Op1, *Op2;
7763 if (parseTypeAndValue(Op0, Loc, PFS) ||
7764 parseToken(
lltok::comma,
"expected ',' after select condition") ||
7765 parseTypeAndValue(Op1, PFS) ||
7766 parseToken(
lltok::comma,
"expected ',' after select value") ||
7767 parseTypeAndValue(Op2, PFS))
7771 return error(Loc, Reason);
7779bool LLParser::parseVAArg(
Instruction *&Inst, PerFunctionState &PFS) {
7781 Type *EltTy =
nullptr;
7783 if (parseTypeAndValue(
Op, PFS) ||
7784 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
7785 parseType(EltTy, TypeLoc))
7789 return error(TypeLoc,
"va_arg requires operand with first class type");
7797bool LLParser::parseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
7800 if (parseTypeAndValue(Op0, Loc, PFS) ||
7801 parseToken(
lltok::comma,
"expected ',' after extract value") ||
7802 parseTypeAndValue(Op1, PFS))
7806 return error(Loc,
"invalid extractelement operands");
7814bool LLParser::parseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
7816 Value *Op0, *Op1, *Op2;
7817 if (parseTypeAndValue(Op0, Loc, PFS) ||
7818 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7819 parseTypeAndValue(Op1, PFS) ||
7820 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7821 parseTypeAndValue(Op2, PFS))
7825 return error(Loc,
"invalid insertelement operands");
7833bool LLParser::parseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
7835 Value *Op0, *Op1, *Op2;
7836 if (parseTypeAndValue(Op0, Loc, PFS) ||
7837 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
7838 parseTypeAndValue(Op1, PFS) ||
7839 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
7840 parseTypeAndValue(Op2, PFS))
7844 return error(Loc,
"invalid shufflevector operands");
7852int LLParser::parsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
7856 if (parseType(Ty, TypeLoc))
7860 return error(TypeLoc,
"phi node must have first class type");
7863 bool AteExtraComma =
false;
7875 AteExtraComma =
true;
7879 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
7880 parseValue(Ty, Op0, PFS) ||
7881 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7886 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7890 for (
unsigned i = 0, e = PHIVals.
size(); i != e; ++i)
7891 PN->
addIncoming(PHIVals[i].first, PHIVals[i].second);
7893 return AteExtraComma ? InstExtraComma : InstNormal;
7902bool LLParser::parseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
7905 if (parseType(Ty, TyLoc))
7918 return tokError(
"expected 'catch' or 'filter' clause type");
7922 if (parseTypeAndValue(V, VLoc, PFS))
7928 if (isa<ArrayType>(
V->getType()))
7929 error(VLoc,
"'catch' clause has an invalid type");
7931 if (!isa<ArrayType>(
V->getType()))
7932 error(VLoc,
"'filter' clause has an invalid type");
7935 Constant *CV = dyn_cast<Constant>(V);
7937 return error(VLoc,
"clause argument must be a constant");
7941 Inst = LP.release();
7947bool LLParser::parseFreeze(
Instruction *&Inst, PerFunctionState &PFS) {
7950 if (parseTypeAndValue(
Op, Loc, PFS))
7966bool LLParser::parseCall(
Instruction *&Inst, PerFunctionState &PFS,
7968 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7969 std::vector<unsigned> FwdRefAttrGrps;
7971 unsigned CallAddrSpace;
7973 Type *RetType =
nullptr;
7982 "expected 'tail call', 'musttail call', or 'notail call'"))
7987 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7988 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7989 parseType(RetType, RetTypeLoc,
true ) ||
7990 parseValID(CalleeID, &PFS) ||
7992 PFS.getFunction().isVarArg()) ||
7993 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
7994 parseOptionalOperandBundles(BundleList, PFS))
8001 if (resolveFunctionType(RetType, ArgList, Ty))
8002 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8008 if (convertValIDToValue(
PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
8021 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
8022 Type *ExpectedTy =
nullptr;
8025 }
else if (!Ty->isVarArg()) {
8026 return error(ArgList[i].Loc,
"too many arguments specified");
8029 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
8030 return error(ArgList[i].Loc,
"argument is not of expected type '" +
8032 Args.push_back(ArgList[i].V);
8033 Attrs.push_back(ArgList[i].Attrs);
8037 return error(CallLoc,
"not enough parameters specified for call");
8048 if (!isa<FPMathOperator>(CI)) {
8050 return error(CallLoc,
"fast-math-flags specified for call without "
8051 "floating-point scalar or vector return type");
8058 if (SeenNewDbgInfoFormat) {
8060 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8061 "using non-intrinsic debug info");
8063 if (!SeenOldDbgInfoFormat)
8064 M->setNewDbgInfoFormatFlag(
false);
8065 SeenOldDbgInfoFormat =
true;
8068 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8080int LLParser::parseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
8082 LocTy SizeLoc, TyLoc, ASLoc;
8084 unsigned AddrSpace = 0;
8087 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8088 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8090 if (parseType(Ty, TyLoc))
8094 return error(TyLoc,
"invalid type for alloca");
8096 bool AteExtraComma =
false;
8098 if (Lex.
getKind() == lltok::kw_align) {
8099 if (parseOptionalAlignment(Alignment))
8101 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8105 if (parseOptionalAddrSpace(AddrSpace))
8108 AteExtraComma =
true;
8110 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8113 if (Lex.
getKind() == lltok::kw_align) {
8114 if (parseOptionalAlignment(Alignment))
8116 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8120 if (parseOptionalAddrSpace(AddrSpace))
8123 AteExtraComma =
true;
8129 if (
Size && !
Size->getType()->isIntegerTy())
8130 return error(SizeLoc,
"element count must have integer type");
8133 if (!Alignment && !Ty->
isSized(&Visited))
8134 return error(TyLoc,
"Cannot allocate unsized type");
8136 Alignment =
M->getDataLayout().getPrefTypeAlign(Ty);
8141 return AteExtraComma ? InstExtraComma : InstNormal;
8148int LLParser::parseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
8151 bool AteExtraComma =
false;
8152 bool isAtomic =
false;
8161 bool isVolatile =
false;
8169 if (parseType(Ty) ||
8170 parseToken(
lltok::comma,
"expected comma after load's type") ||
8171 parseTypeAndValue(Val, Loc, PFS) ||
8172 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8173 parseOptionalCommaAlign(Alignment, AteExtraComma))
8177 return error(Loc,
"load operand must be a pointer to a first class type");
8178 if (isAtomic && !Alignment)
8179 return error(Loc,
"atomic load must have explicit non-zero alignment");
8182 return error(Loc,
"atomic load cannot use Release ordering");
8185 if (!Alignment && !Ty->
isSized(&Visited))
8186 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8188 Alignment =
M->getDataLayout().getABITypeAlign(Ty);
8189 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8190 return AteExtraComma ? InstExtraComma : InstNormal;
8198int LLParser::parseStore(
Instruction *&Inst, PerFunctionState &PFS) {
8201 bool AteExtraComma =
false;
8202 bool isAtomic =
false;
8211 bool isVolatile =
false;
8217 if (parseTypeAndValue(Val, Loc, PFS) ||
8218 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8219 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8220 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8221 parseOptionalCommaAlign(Alignment, AteExtraComma))
8224 if (!
Ptr->getType()->isPointerTy())
8225 return error(PtrLoc,
"store operand must be a pointer");
8227 return error(Loc,
"store operand must be a first class value");
8228 if (isAtomic && !Alignment)
8229 return error(Loc,
"atomic store must have explicit non-zero alignment");
8232 return error(Loc,
"atomic store cannot use Acquire ordering");
8235 return error(Loc,
"storing unsized types is not allowed");
8237 Alignment =
M->getDataLayout().getABITypeAlign(Val->
getType());
8239 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8240 return AteExtraComma ? InstExtraComma : InstNormal;
8247int LLParser::parseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
8249 bool AteExtraComma =
false;
8253 bool isVolatile =
false;
8254 bool isWeak =
false;
8263 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8264 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8265 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8266 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8267 parseTypeAndValue(New, NewLoc, PFS) ||
8268 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8269 parseOrdering(FailureOrdering) ||
8270 parseOptionalCommaAlign(Alignment, AteExtraComma))
8274 return tokError(
"invalid cmpxchg success ordering");
8276 return tokError(
"invalid cmpxchg failure ordering");
8277 if (!
Ptr->getType()->isPointerTy())
8278 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8279 if (
Cmp->getType() !=
New->getType())
8280 return error(NewLoc,
"compare value and new value type do not match");
8281 if (!
New->getType()->isFirstClassType())
8282 return error(NewLoc,
"cmpxchg operand must be a first class value");
8284 const Align DefaultAlignment(
8285 PFS.getFunction().getDataLayout().getTypeStoreSize(
8290 SuccessOrdering, FailureOrdering, SSID);
8295 return AteExtraComma ? InstExtraComma : InstNormal;
8301int LLParser::parseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
8303 bool AteExtraComma =
false;
8306 bool isVolatile =
false;
8316 return tokError(
"expected binary operation in atomicrmw");
8353 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8354 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8355 parseTypeAndValue(Val, ValLoc, PFS) ||
8356 parseScopeAndOrdering(
true , SSID, Ordering) ||
8357 parseOptionalCommaAlign(Alignment, AteExtraComma))
8361 return tokError(
"atomicrmw cannot be unordered");
8362 if (!
Ptr->getType()->isPointerTy())
8363 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8365 return error(ValLoc,
"atomicrmw operand may not be scalable");
8374 " operand must be an integer, floating point, or pointer type");
8378 return error(ValLoc,
"atomicrmw " +
8380 " operand must be a floating point type");
8384 return error(ValLoc,
"atomicrmw " +
8386 " operand must be an integer");
8391 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8394 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8396 const Align DefaultAlignment(
8397 PFS.getFunction().getDataLayout().getTypeStoreSize(
8401 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8404 return AteExtraComma ? InstExtraComma : InstNormal;
8409int LLParser::parseFence(
Instruction *&Inst, PerFunctionState &PFS) {
8412 if (parseScopeAndOrdering(
true , SSID, Ordering))
8416 return tokError(
"fence cannot be unordered");
8418 return tokError(
"fence cannot be monotonic");
8420 Inst =
new FenceInst(Context, Ordering, SSID);
8426int LLParser::parseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
8428 Value *Val =
nullptr;
8444 if (parseType(Ty) ||
8445 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8446 parseTypeAndValue(
Ptr, Loc, PFS))
8451 if (!BasePointerType)
8452 return error(Loc,
"base of getelementptr must be a pointer");
8455 bool AteExtraComma =
false;
8459 ? cast<VectorType>(
BaseType)->getElementCount()
8464 AteExtraComma =
true;
8467 if (parseTypeAndValue(Val, EltLoc, PFS))
8470 return error(EltLoc,
"getelementptr index must be an integer");
8472 if (
auto *ValVTy = dyn_cast<VectorType>(Val->
getType())) {
8477 "getelementptr vector index has a wrong number of elements");
8478 GEPWidth = ValNumEl;
8485 return error(Loc,
"base element of getelementptr must be sized");
8487 auto *STy = dyn_cast<StructType>(Ty);
8489 return error(Loc,
"getelementptr cannot target structure that contains "
8490 "scalable vector type");
8493 return error(Loc,
"invalid getelementptr indices");
8496 GEP->setNoWrapFlags(NW);
8497 return AteExtraComma ? InstExtraComma : InstNormal;
8502int LLParser::parseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
8506 if (parseTypeAndValue(Val, Loc, PFS) ||
8507 parseIndexList(Indices, AteExtraComma))
8511 return error(Loc,
"extractvalue operand must be aggregate type");
8514 return error(Loc,
"invalid indices for extractvalue");
8516 return AteExtraComma ? InstExtraComma : InstNormal;
8521int LLParser::parseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
8525 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8526 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8527 parseTypeAndValue(Val1, Loc1, PFS) ||
8528 parseIndexList(Indices, AteExtraComma))
8532 return error(Loc0,
"insertvalue operand must be aggregate type");
8536 return error(Loc0,
"invalid indices for insertvalue");
8537 if (IndexedType != Val1->
getType())
8538 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8542 return AteExtraComma ? InstExtraComma : InstNormal;
8568 if (parseMetadata(MD,
nullptr))
8573 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8582 return error(Loc,
"value has no uses");
8584 unsigned NumUses = 0;
8586 for (
const Use &U :
V->uses()) {
8587 if (++NumUses > Indexes.
size())
8589 Order[&
U] = Indexes[NumUses - 1];
8592 return error(Loc,
"value only has one use");
8593 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8595 "wrong number of indexes, expected " +
Twine(
V->getNumUses()));
8597 V->sortUseList([&](
const Use &L,
const Use &R) {
8610 return Lex.
Error(
"expected non-empty list of uselistorder indexes");
8617 bool IsOrdered =
true;
8618 assert(Indexes.
empty() &&
"Expected empty order vector");
8621 if (parseUInt32(
Index))
8635 if (Indexes.
size() < 2)
8636 return error(Loc,
"expected >= 2 uselistorder indexes");
8639 "expected distinct uselistorder indexes in range [0, size)");
8641 return error(Loc,
"expected uselistorder indexes to change the order");
8648bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8655 if (parseTypeAndValue(V, PFS) ||
8656 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
8657 parseUseListOrderIndexes(Indexes))
8660 return sortUseListOrder(V, Indexes, Loc);
8665bool LLParser::parseUseListOrderBB() {
8672 if (parseValID(Fn,
nullptr) ||
8673 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8674 parseValID(Label,
nullptr) ||
8675 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8676 parseUseListOrderIndexes(Indexes))
8682 GV =
M->getNamedValue(Fn.
StrVal);
8684 GV = NumberedVals.get(Fn.
UIntVal);
8686 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8689 "invalid function forward reference in uselistorder_bb");
8690 auto *
F = dyn_cast<Function>(GV);
8692 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8693 if (
F->isDeclaration())
8694 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
8698 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
8700 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
8701 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
8703 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
8704 if (!isa<BasicBlock>(V))
8705 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
8707 return sortUseListOrder(V, Indexes, Loc);
8713bool LLParser::parseModuleEntry(
unsigned ID) {
8722 parseStringConstant(Path) ||
8730 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
8731 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
8732 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
8733 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
8734 parseUInt32(Hash[4]))
8741 auto ModuleEntry =
Index->addModule(Path, Hash);
8742 ModuleIdMap[
ID] = ModuleEntry->first();
8749bool LLParser::parseTypeIdEntry(
unsigned ID) {
8758 parseStringConstant(
Name))
8763 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
8768 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8769 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8770 for (
auto TIDRef : FwdRefTIDs->second) {
8772 "Forward referenced type id GUID expected to be 0");
8775 ForwardRefTypeIds.erase(FwdRefTIDs);
8787 parseTypeTestResolution(TIS.
TTRes))
8792 if (parseOptionalWpdResolutions(TIS.
WPDRes))
8803 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
8809bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
8818 parseStringConstant(
Name))
8822 Index->getOrInsertTypeIdCompatibleVtableSummary(
Name);
8829 IdToIndexMapType IdToIndexMap;
8842 if (parseGVReference(VI, GVId))
8849 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8850 TI.push_back({
Offset, VI});
8858 for (
auto I : IdToIndexMap) {
8859 auto &Infos = ForwardRefValueInfos[
I.first];
8860 for (
auto P :
I.second) {
8862 "Forward referenced ValueInfo expected to be empty");
8863 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
8873 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8874 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8875 for (
auto TIDRef : FwdRefTIDs->second) {
8877 "Forward referenced type id GUID expected to be 0");
8880 ForwardRefTypeIds.erase(FwdRefTIDs);
8920 return error(Lex.
getLoc(),
"unexpected TypeTestResolution kind");
8947 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
8960 return error(Lex.
getLoc(),
"expected optional TypeTestResolution field");
8973bool LLParser::parseOptionalWpdResolutions(
8974 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8986 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
8989 WPDResMap[
Offset] = WPDRes;
9025 return error(Lex.
getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9039 if (parseOptionalResByArg(WPDRes.
ResByArg))
9044 "expected optional WholeProgramDevirtResolution field");
9061bool LLParser::parseOptionalResByArg(
9070 std::vector<uint64_t>
Args;
9071 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9095 "unexpected WholeProgramDevirtResolution::ByArg kind");
9105 parseUInt64(ByArg.
Info))
9111 parseUInt32(ByArg.
Byte))
9117 parseUInt32(ByArg.
Bit))
9122 "expected optional whole program devirt field");
9129 ResByArg[
Args] = ByArg;
9140bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9148 if (parseUInt64(Val))
9150 Args.push_back(Val);
9159static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9164 assert(!(ReadOnly && WriteOnly));
9174bool LLParser::addGlobalValueToIndex(
9176 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9181 VI =
Index->getOrInsertValueInfo(GUID);
9185 auto *GV =
M->getNamedValue(
Name);
9187 return error(Loc,
"Reference to undefined global \"" +
Name +
"\"");
9189 VI =
Index->getOrInsertValueInfo(GV);
9193 "Need a source_filename to compute GUID for local");
9201 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9202 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9203 for (
auto VIRef : FwdRefVIs->second) {
9205 "Forward referenced ValueInfo expected to be empty");
9208 ForwardRefValueInfos.erase(FwdRefVIs);
9212 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9213 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9214 for (
auto AliaseeRef : FwdRefAliasees->second) {
9215 assert(!AliaseeRef.first->hasAliasee() &&
9216 "Forward referencing alias already has aliasee");
9217 assert(Summary &&
"Aliasee must be a definition");
9218 AliaseeRef.first->setAliasee(VI,
Summary.get());
9220 ForwardRefAliasees.erase(FwdRefAliasees);
9225 Index->addGlobalValueSummary(VI, std::move(Summary));
9228 if (
ID == NumberedValueInfos.size())
9229 NumberedValueInfos.push_back(VI);
9232 if (
ID > NumberedValueInfos.size())
9233 NumberedValueInfos.resize(
ID + 1);
9234 NumberedValueInfos[
ID] =
VI;
9242bool LLParser::parseSummaryIndexFlags() {
9249 if (parseUInt64(Flags))
9252 Index->setFlags(Flags);
9258bool LLParser::parseBlockCount() {
9265 if (parseUInt64(BlockCount))
9268 Index->setBlockCount(BlockCount);
9276bool LLParser::parseGVEntry(
unsigned ID) {
9291 parseStringConstant(
Name))
9297 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9301 return error(Lex.
getLoc(),
"expected name or guid tag");
9326 if (parseFunctionSummary(
Name, GUID,
ID))
9330 if (parseVariableSummary(
Name, GUID,
ID))
9334 if (parseAliasSummary(
Name, GUID,
ID))
9338 return error(Lex.
getLoc(),
"expected summary type");
9364 false,
false,
false,
9367 std::vector<FunctionSummary::EdgeTy> Calls;
9369 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9370 std::vector<ValueInfo> Refs;
9371 std::vector<CallsiteInfo> Callsites;
9372 std::vector<AllocInfo> Allocs;
9377 parseModuleReference(ModulePath) ||
9378 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9381 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9388 if (parseOptionalFFlags(FFlags))
9392 if (parseOptionalCalls(Calls))
9396 if (parseOptionalTypeIdInfo(TypeIdInfo))
9400 if (parseOptionalRefs(Refs))
9404 if (parseOptionalParamAccesses(ParamAccesses))
9408 if (parseOptionalAllocs(Allocs))
9412 if (parseOptionalCallsites(Callsites))
9416 return error(Lex.
getLoc(),
"expected optional function summary field");
9423 auto FS = std::make_unique<FunctionSummary>(
9424 GVFlags, InstCount, FFlags, 0, std::move(Refs),
9425 std::move(Calls), std::move(TypeIdInfo.
TypeTests),
9430 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9432 FS->setModulePath(ModulePath);
9434 return addGlobalValueToIndex(
Name, GUID,
9436 std::move(FS), Loc);
9452 false,
false,
false,
9458 std::vector<ValueInfo> Refs;
9462 parseModuleReference(ModulePath) ||
9463 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9465 parseGVarFlags(GVarFlags))
9472 if (parseOptionalVTableFuncs(VTableFuncs))
9476 if (parseOptionalRefs(Refs))
9480 return error(Lex.
getLoc(),
"expected optional variable summary field");
9488 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9490 GS->setModulePath(ModulePath);
9491 GS->setVTableFuncs(std::move(VTableFuncs));
9493 return addGlobalValueToIndex(
Name, GUID,
9495 std::move(GS), Loc);
9511 false,
false,
false,
9515 parseModuleReference(ModulePath) ||
9516 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9524 if (parseGVReference(AliaseeVI, GVId))
9530 auto AS = std::make_unique<AliasSummary>(GVFlags);
9532 AS->setModulePath(ModulePath);
9536 ForwardRefAliasees[GVId].emplace_back(AS.
get(), Loc);
9538 auto Summary =
Index->findSummaryInModule(AliaseeVI, ModulePath);
9539 assert(Summary &&
"Aliasee must be a definition");
9540 AS->setAliasee(AliaseeVI, Summary);
9543 return addGlobalValueToIndex(
Name, GUID,
9545 std::move(AS), Loc);
9550bool LLParser::parseFlag(
unsigned &Val) {
9552 return tokError(
"expected integer");
9573 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9582 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9588 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9594 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9600 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9606 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9612 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9618 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9624 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9630 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9636 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9641 return error(Lex.
getLoc(),
"expected function flag type");
9656bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9660 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
9664 IdToIndexMapType IdToIndexMap;
9675 if (parseGVReference(VI, GVId))
9680 unsigned HasTailCall =
false;
9687 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
9692 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
9697 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
9701 return error(Lex.
getLoc(),
"expected hotness, relbf, or tail");
9705 return tokError(
"Expected only one of hotness or relbf");
9710 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9720 for (
auto I : IdToIndexMap) {
9721 auto &Infos = ForwardRefValueInfos[
I.first];
9722 for (
auto P :
I.second) {
9724 "Forward referenced ValueInfo expected to be empty");
9725 Infos.emplace_back(&Calls[
P.first].first,
P.second);
9742 case lltok::kw_cold:
9755 return error(Lex.
getLoc(),
"invalid call edge hotness");
9764bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
9768 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
9772 IdToIndexMapType IdToIndexMap;
9776 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
9783 if (parseGVReference(VI, GVId))
9796 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9797 VTableFuncs.push_back({
VI,
Offset});
9799 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
9805 for (
auto I : IdToIndexMap) {
9806 auto &Infos = ForwardRefValueInfos[
I.first];
9807 for (
auto P :
I.second) {
9809 "Forward referenced ValueInfo expected to be empty");
9810 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
9814 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
9821bool LLParser::parseParamNo(
uint64_t &ParamNo) {
9823 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
9832 auto ParseAPSInt = [&](
APSInt &Val) {
9834 return tokError(
"expected integer");
9837 Val.setIsSigned(
true);
9860 IdLocListType &IdLocList) {
9869 if (parseGVReference(VI, GVId))
9873 IdLocList.emplace_back(GVId, Loc);
9876 parseParamNo(
Call.ParamNo) ||
9878 parseParamAccessOffset(
Call.Offsets))
9891 IdLocListType &IdLocList) {
9893 parseParamNo(
Param.ParamNo) ||
9895 parseParamAccessOffset(
Param.Use))
9905 if (parseParamAccessCall(Call, IdLocList))
9907 Param.Calls.push_back(Call);
9922bool LLParser::parseOptionalParamAccesses(
9923 std::vector<FunctionSummary::ParamAccess> &Params) {
9931 IdLocListType VContexts;
9932 size_t CallsNum = 0;
9935 if (parseParamAccess(ParamAccess, VContexts))
9937 CallsNum += ParamAccess.
Calls.size();
9938 assert(VContexts.size() == CallsNum);
9940 Params.emplace_back(std::move(ParamAccess));
9948 IdLocListType::const_iterator ItContext = VContexts.begin();
9949 for (
auto &PA : Params) {
9950 for (
auto &
C : PA.Calls) {
9952 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
9957 assert(ItContext == VContexts.end());
9964bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9968 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
9972 struct ValueContext {
9977 std::vector<ValueContext> VContexts;
9982 if (parseGVReference(
VC.VI,
VC.GVId))
9984 VContexts.push_back(VC);
9990 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
9991 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9994 IdToIndexMapType IdToIndexMap;
9995 for (
auto &VC : VContexts) {
10000 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.size(),
VC.Loc));
10001 Refs.push_back(
VC.VI);
10006 for (
auto I : IdToIndexMap) {
10007 auto &Infos = ForwardRefValueInfos[
I.first];
10008 for (
auto P :
I.second) {
10010 "Forward referenced ValueInfo expected to be empty");
10011 Infos.emplace_back(&Refs[
P.first],
P.second);
10025bool LLParser::parseOptionalTypeIdInfo(
10037 if (parseTypeTests(TypeIdInfo.
TypeTests))
10061 return error(Lex.
getLoc(),
"invalid typeIdInfo list type");
10065 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10074bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10082 IdToIndexMapType IdToIndexMap;
10091 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10093 }
else if (parseUInt64(GUID))
10095 TypeTests.push_back(GUID);
10100 for (
auto I : IdToIndexMap) {
10101 auto &Ids = ForwardRefTypeIds[
I.first];
10102 for (
auto P :
I.second) {
10103 assert(TypeTests[
P.first] == 0 &&
10104 "Forward referenced type id GUID expected to be 0");
10105 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10109 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10117bool LLParser::parseVFuncIdList(
10118 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10126 IdToIndexMapType IdToIndexMap;
10129 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10131 VFuncIdList.push_back(VFuncId);
10139 for (
auto I : IdToIndexMap) {
10140 auto &Ids = ForwardRefTypeIds[
I.first];
10141 for (
auto P :
I.second) {
10142 assert(VFuncIdList[
P.first].GUID == 0 &&
10143 "Forward referenced type id GUID expected to be 0");
10144 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10153bool LLParser::parseConstVCallList(
10155 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10163 IdToIndexMapType IdToIndexMap;
10166 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10168 ConstVCallList.push_back(ConstVCall);
10176 for (
auto I : IdToIndexMap) {
10177 auto &Ids = ForwardRefTypeIds[
I.first];
10178 for (
auto P :
I.second) {
10179 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10180 "Forward referenced type id GUID expected to be 0");
10181 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10191 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10193 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap,
Index))
10197 if (parseArgs(ConstVCall.
Args))
10210 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10225 IdToIndexMap[
ID].push_back(std::make_pair(
Index, Loc));
10227 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10229 parseUInt64(VFuncId.
GUID))
10235 parseUInt64(VFuncId.
Offset) ||
10264 assert(HasLinkage &&
"Linkage not optional in summary entry");
10271 parseOptionalVisibility(Flag);
10276 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10282 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10288 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10294 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10303 if (parseOptionalImportType(Lex.
getKind(), IK))
10305 GVFlags.
ImportType =
static_cast<unsigned>(IK);
10309 return error(Lex.
getLoc(),
"expected gv flag type");
10331 auto ParseRest = [
this](
unsigned int &Val) {
10335 return parseFlag(Val);
10341 case lltok::kw_readonly:
10342 if (ParseRest(Flag))
10346 case lltok::kw_writeonly:
10347 if (ParseRest(Flag))
10352 if (ParseRest(Flag))
10357 if (ParseRest(Flag))
10362 return error(Lex.
getLoc(),
"expected gvar flag type");
10370bool LLParser::parseModuleReference(
StringRef &ModulePath) {
10378 auto I = ModuleIdMap.find(ModuleID);
10380 assert(
I != ModuleIdMap.end());
10381 ModulePath =
I->second;
10387bool LLParser::parseGVReference(
ValueInfo &VI,
unsigned &GVId) {
10390 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10396 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10398 VI = NumberedValueInfos[GVId];
10415bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10419 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10434 if (parseAllocType(V))
10439 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10443 std::vector<MIBInfo> MIBs;
10444 if (parseMemProfs(MIBs))
10447 Allocs.push_back({Versions, MIBs});
10464bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10468 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10474 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10483 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10492 if (parseUInt64(StackId))
10514bool LLParser::parseAllocType(uint8_t &
AllocType) {
10522 case lltok::kw_cold:
10525 case lltok::kw_hot:
10529 return error(Lex.
getLoc(),
"invalid alloc type");
10542bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10546 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10550 IdToIndexMapType IdToIndexMap;
10553 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10562 if (parseGVReference(VI, GVId))
10566 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10575 if (parseUInt32(V))
10581 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10590 if (parseUInt64(StackId))
10602 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10603 Callsites.push_back({
VI, Clones, StackIdIndices});
10611 for (
auto I : IdToIndexMap) {
10612 auto &Infos = ForwardRefValueInfos[
I.first];
10613 for (
auto P :
I.second) {
10615 "Forward referenced ValueInfo expected to be empty");
10616 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10620 if (parseToken(
lltok::rparen,
"expected ')' in callsites"))
static int64_t upperBound(StackOffset Size)
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Expand Atomic instructions
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live value
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
DenseMap< Block *, BlockRelaxAux > Blocks
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
cl::opt< bool > WriteNewDbgInfoFormat
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
bool WriteNewDbgInfoFormatToBitcode
static unsigned keywordToFPClassTest(lltok::Kind Tok)
llvm::cl::opt< bool > UseNewDbgInfoFormat
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Module.h This file contains the declarations for the Module class.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
PowerPC Reduce CR logical Operation
llvm::cl::opt< bool > UseNewDbgInfoFormat
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
static SymbolRef::Type getType(const Symbol *Sym)
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Class for arbitrary precision integers.
uint64_t getZExtValue() const
Get zero extended value.
unsigned getBitWidth() const
Return the number of bits in the APInt.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
bool getBoolValue() const
Convert APInt to a boolean value.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
An arbitrary precision integer that knows its signedness.
APSInt extOrTrunc(uint32_t width) const
APSInt extend(uint32_t width) const
an instruction to allocate memory on the stack
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
An instruction that atomically checks whether a specified value is in a memory location,...
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
an instruction that atomically reads a memory location, combines it with another value,...
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Min
*p = old <signed v ? old : v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
static StringRef getOperationName(BinOp Op)
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeList removeAttribute(LLVMContext &C, unsigned Index, StringRef Kind) const
AttributeList addFnAttributes(LLVMContext &C, const AttrBuilder &B) const
Add function attribute to the list.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
AttributeList removeFnAttributes(LLVMContext &C, const AttributeMask &AttrsToRemove) const
Remove the specified attribute at the function index from this attribute list.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the parameter 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)
static 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 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=std::nullopt, 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 Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static 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 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 ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
static 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 Constant * get(StructType *T, ArrayRef< Constant * > V)
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
Basic type, like 'int' or 'float'.
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations)
Build a DICompositeType with the given ODR identifier.
static std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Tagged DWARF-like metadata node.
static DIFlags getFlag(StringRef Flag)
String type, Fortran CHARACTER(n)
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
Type array for a subprogram.
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
This class represents an Operation in the Expression.
static Expected< DataLayout > parse(StringRef LayoutDescription)
Parse a data layout string and return the layout.
static DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Base class for non-instruction debug metadata records that have positions within IR.
Kind
Subclass discriminator.
static DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static constexpr ElementCount getFixed(ScalarTy MinVal)
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
Class representing an expression and its matching format.
This instruction compares its operands according to the predicate given to the constructor.
Convenience struct for specifying and reasoning about fast-math flags.
An instruction for ordering other memory operations.
This class represents a freeze function that returns random concrete value if an operand is either a ...
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
Type::subtype_iterator param_iterator
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setPrefixData(Constant *PrefixData)
static Intrinsic::ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
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 Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
void setComdat(Comdat *C)
void setSection(StringRef S)
Change the section for this global.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
void setDSOLocal(bool Local)
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
void setVisibility(VisibilityTypes V)
void setSanitizerMetadata(SanitizerMetadata Meta)
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e....
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
void setPartition(StringRef Part)
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
static Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
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
bool Error(LocTy ErrorLoc, const Twine &Msg) const
const std::string & getStrVal() const
const APSInt & getAPSIntVal() const
void setIgnoreColonInIdentifiers(bool val)
const APFloat & getAPFloatVal() const
LLVMContext & getContext()
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", 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 MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
static MemoryEffectsBase readOnly()
Create MemoryEffectsBase that can read any memory.
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access argument memory.
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible memory.
static MemoryEffectsBase writeOnly()
Create MemoryEffectsBase that can write any memory.
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible or argument memory.
static MemoryEffectsBase none()
Create MemoryEffectsBase that cannot read or write any memory.
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
A Module instance is used to store all the information related to an LLVM module.
void addOperand(MDNode *M)
static NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Resume the propagation of an exception.
static ResumeInst * Create(Value *Exn, 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 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 bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
iterator find(StringRef Key)
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Class to represent struct types.
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
bool containsScalableVectorType(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
static TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types=std::nullopt, ArrayRef< unsigned > Ints=std::nullopt)
Return a target extension type having the specified name and optional type and integer parameters.
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
static IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
TypeID
Definitions of all of the base types for the Type system.
static Type * getLabelTy(LLVMContext &C)
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isAggregateType() const
Return true if the type is an aggregate type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static IntegerType * getInt8Ty(LLVMContext &C)
static Type * getTokenTy(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVoidTy() const
Return true if this is 'void'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
void setName(const Twine &Name)
Change the name of the value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void deleteValue()
Delete a pointer to a generic Value.
StringRef getName() const
Return a constant reference to the value's name.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
unsigned getOperationEncoding(StringRef OperationEncodingString)
unsigned getAttributeEncoding(StringRef EncodingString)
unsigned getTag(StringRef TagString)
unsigned getCallingConvention(StringRef LanguageString)
unsigned getLanguage(StringRef LanguageString)
unsigned getVirtuality(StringRef VirtualityString)
unsigned getMacinfo(StringRef MacinfoString)
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
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.
bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
initializer< Ty > init(const Ty &Val)
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Linkage
Describes symbol linkage. This can be used to resolve definition clashes.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_no_sanitize_hwaddress
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_dso_local_equivalent
@ kw_aarch64_sme_preservemost_from_x2
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
void UpgradeSectionAttributes(Module &M)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
bool isPointerTy(const Type *T)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
@ ArgMem
Access to memory via argument pointers.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
Implement std::hash so that hash_code can be used in STL containers.
static const fltSemantics & IEEEsingle() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToEven
static const fltSemantics & IEEEdouble() LLVM_READNONE
static const fltSemantics & IEEEhalf() LLVM_READNONE
static const fltSemantics & BFloat() LLVM_READNONE
This struct is a compact representation of a valid (non-zero power of two) alignment.
Class to accumulate and hold information about a callee.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
A specification for a virtual function call with all constant integer arguments.
std::vector< uint64_t > Args
Flags specific to function summaries.
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
Describes the use of a value in a call instruction, specifying the call's target, the value's paramet...
Describes the uses of a parameter by the function.
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
All type identifier related information.
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
An "identifier" for a virtual function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
A utility class that uses RAII to save and restore the value of a variable.
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
std::map< unsigned, Type * > Types
StringMap< Type * > NamedTypes
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
NumberedValues< GlobalValue * > GlobalValues
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
enum llvm::ValID::@38 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.