73 "Can't read textual IR with a Context that discards named Values");
76 if (parseTargetDefinitions(DataLayoutCallback))
86 restoreParsingState(Slots);
90 if (parseType(Ty) || parseConstantValue(Ty,
C))
93 return error(Lex.
getLoc(),
"expected end of string");
99 restoreParsingState(Slots);
108 Read =
End.getPointer() - Start.getPointer();
113void LLParser::restoreParsingState(
const SlotMapping *Slots) {
120 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
121 for (
const auto &
I : Slots->
Types)
122 NumberedTypes.insert(
123 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
132 for (
const auto &RAG : ForwardRefAttrGroups) {
133 Value *V = RAG.first;
134 const std::vector<unsigned> &Attrs = RAG.second;
137 for (
const auto &Attr : Attrs) {
138 auto R = NumberedAttrBuilders.find(Attr);
139 if (R != NumberedAttrBuilders.end())
143 if (
Function *Fn = dyn_cast<Function>(V)) {
153 Fn->setAlignment(*
A);
158 Fn->setAttributes(AS);
159 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
165 CI->setAttributes(AS);
166 }
else if (
InvokeInst *II = dyn_cast<InvokeInst>(V)) {
172 II->setAttributes(AS);
173 }
else if (
CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
179 CBI->setAttributes(AS);
180 }
else if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
191 if (!ForwardRefBlockAddresses.empty())
192 return error(ForwardRefBlockAddresses.begin()->first.Loc,
193 "expected function name in blockaddress");
195 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
200 }
else if (GVRef.
UIntVal < NumberedVals.size()) {
201 GV = dyn_cast<GlobalValue>(NumberedVals[GVRef.
UIntVal]);
206 "' referenced by dso_local_equivalent");
210 "expected a function, alias to function, or ifunc "
211 "in dso_local_equivalent");
214 FwdRef->replaceAllUsesWith(Equiv);
215 FwdRef->eraseFromParent();
222 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
223 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
226 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
227 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
230 ForwardRefDSOLocalEquivalentIDs.clear();
231 ForwardRefDSOLocalEquivalentNames.clear();
233 for (
const auto &NT : NumberedTypes)
234 if (
NT.second.second.isValid())
236 "use of undefined type '%" +
Twine(
NT.first) +
"'");
238 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
239 NamedTypes.begin(),
E = NamedTypes.end();
I !=
E; ++
I)
240 if (
I->second.second.isValid())
241 return error(
I->second.second,
242 "use of undefined type named '" +
I->getKey() +
"'");
244 if (!ForwardRefComdats.empty())
245 return error(ForwardRefComdats.begin()->second,
246 "use of undefined comdat '$" +
247 ForwardRefComdats.begin()->first +
"'");
249 if (!ForwardRefVals.empty())
250 return error(ForwardRefVals.begin()->second.second,
251 "use of undefined value '@" + ForwardRefVals.begin()->first +
254 if (!ForwardRefValIDs.empty())
255 return error(ForwardRefValIDs.begin()->second.second,
256 "use of undefined value '@" +
257 Twine(ForwardRefValIDs.begin()->first) +
"'");
259 if (!ForwardRefMDNodes.empty())
260 return error(ForwardRefMDNodes.begin()->second.second,
261 "use of undefined metadata '!" +
262 Twine(ForwardRefMDNodes.begin()->first) +
"'");
265 for (
auto &
N : NumberedMetadata) {
266 if (
N.second && !
N.second->isResolved())
267 N.second->resolveCycles();
270 for (
auto *Inst : InstsWithTBAATag) {
271 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
272 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
274 if (MD != UpgradedMD)
275 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
283 if (UpgradeDebugInfo)
296 for (
const auto &
I : NamedTypes)
297 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
298 for (
const auto &
I : NumberedTypes)
299 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
305bool LLParser::validateEndOfIndex() {
309 if (!ForwardRefValueInfos.empty())
310 return error(ForwardRefValueInfos.begin()->second.front().second,
311 "use of undefined summary '^" +
312 Twine(ForwardRefValueInfos.begin()->first) +
"'");
314 if (!ForwardRefAliasees.empty())
315 return error(ForwardRefAliasees.begin()->second.front().second,
316 "use of undefined summary '^" +
317 Twine(ForwardRefAliasees.begin()->first) +
"'");
319 if (!ForwardRefTypeIds.empty())
320 return error(ForwardRefTypeIds.begin()->second.front().second,
321 "use of undefined type id summary '^" +
322 Twine(ForwardRefTypeIds.begin()->first) +
"'");
343 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
347 if (parseSourceFileName())
356 if (
auto LayoutOverride =
358 TentativeDLStr = *LayoutOverride;
368bool LLParser::parseTopLevelEntities() {
376 if (parseSummaryEntry())
380 if (parseSourceFileName())
392 return tokError(
"expected top-level entity");
403 if (parseModuleAsm())
407 if (parseUnnamedType())
411 if (parseNamedType())
415 if (parseUnnamedGlobal())
419 if (parseNamedGlobal())
424 if (parseStandaloneMetadata())
428 if (parseSummaryEntry())
432 if (parseNamedMetadata())
436 if (parseUnnamedAttrGrp())
440 if (parseUseListOrder())
444 if (parseUseListOrderBB())
453bool LLParser::parseModuleAsm() {
459 parseStringConstant(AsmStr))
469bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
475 return tokError(
"unknown target property");
478 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
479 parseStringConstant(Str))
485 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
488 if (parseStringConstant(TentativeDLStr))
496bool LLParser::parseSourceFileName() {
499 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
500 parseStringConstant(SourceFileName))
509bool LLParser::parseUnnamedType() {
514 if (parseToken(
lltok::equal,
"expected '=' after name") ||
519 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
522 if (!isa<StructType>(Result)) {
523 std::pair<Type*, LocTy> &Entry = NumberedTypes[
TypeID];
525 return error(TypeLoc,
"non-struct types may not be recursive");
527 Entry.second =
SMLoc();
535bool LLParser::parseNamedType() {
540 if (parseToken(
lltok::equal,
"expected '=' after name") ||
545 if (parseStructDefinition(NameLoc,
Name, NamedTypes[
Name], Result))
548 if (!isa<StructType>(Result)) {
549 std::pair<Type*, LocTy> &Entry = NamedTypes[
Name];
551 return error(NameLoc,
"non-struct types may not be recursive");
553 Entry.second =
SMLoc();
561bool LLParser::parseDeclare() {
565 std::vector<std::pair<unsigned, MDNode *>> MDs;
569 if (parseMetadataAttachment(MDK,
N))
571 MDs.push_back({MDK,
N});
575 if (parseFunctionHeader(
F,
false))
578 F->addMetadata(MD.first, *MD.second);
584bool LLParser::parseDefine() {
589 return parseFunctionHeader(
F,
true) || parseOptionalFunctionMetadata(*
F) ||
590 parseFunctionBody(*
F);
596bool LLParser::parseGlobalType(
bool &IsConstant) {
603 return tokError(
"expected 'global' or 'constant'");
609bool LLParser::parseOptionalUnnamedAddr(
630bool LLParser::parseUnnamedGlobal() {
631 unsigned VarID = NumberedVals.size();
639 "variable expected to be numbered '%" +
Twine(VarID) +
"'");
642 if (parseToken(
lltok::equal,
"expected '=' after name"))
647 unsigned Linkage, Visibility, DLLStorageClass;
651 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
653 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
658 return parseGlobal(
Name, NameLoc, Linkage, HasLinkage, Visibility,
659 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
662 return parseAliasOrIFunc(
Name, NameLoc, Linkage, Visibility,
663 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
672bool LLParser::parseNamedGlobal() {
679 unsigned Linkage, Visibility, DLLStorageClass;
683 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
684 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
686 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
691 return parseGlobal(
Name, NameLoc, Linkage, HasLinkage, Visibility,
692 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
695 return parseAliasOrIFunc(
Name, NameLoc, Linkage, Visibility,
696 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
700bool LLParser::parseComdat() {
710 return tokError(
"expected comdat type");
715 return tokError(
"unknown selection kind");
737 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(
Name))
738 return error(NameLoc,
"redefinition of comdat '$" +
Name +
"'");
741 if (
I != ComdatSymTab.
end())
745 C->setSelectionKind(SK);
752bool LLParser::parseMDString(
MDString *&Result) {
754 if (parseStringConstant(Str))
762bool LLParser::parseMDNodeID(
MDNode *&Result) {
766 if (parseUInt32(MID))
770 if (NumberedMetadata.count(MID)) {
771 Result = NumberedMetadata[MID];
776 auto &FwdRef = ForwardRefMDNodes[MID];
779 Result = FwdRef.first.get();
780 NumberedMetadata[MID].reset(Result);
786bool LLParser::parseNamedMetadata() {
805 if (parseDIExpression(
N,
false))
811 return tokError(
"found DIArgList outside of function");
819 return parseToken(
lltok::rbrace,
"expected end of metadata node");
824bool LLParser::parseStandaloneMetadata() {
827 unsigned MetadataID = 0;
830 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
835 return tokError(
"unexpected type in metadata definition");
839 if (parseSpecializedMDNode(
Init, IsDistinct))
842 parseMDTuple(
Init, IsDistinct))
846 auto FI = ForwardRefMDNodes.find(MetadataID);
847 if (FI != ForwardRefMDNodes.end()) {
848 auto *ToReplace = FI->second.first.get();
851 if (isa<DIAssignID>(
Init)) {
852 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
853 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
854 "Inst unexpectedly already has DIAssignID attachment");
855 Inst->setMetadata(LLVMContext::MD_DIAssignID,
Init);
859 ToReplace->replaceAllUsesWith(
Init);
860 ForwardRefMDNodes.erase(FI);
862 assert(NumberedMetadata[MetadataID] ==
Init &&
"Tracking VH didn't work");
864 if (NumberedMetadata.count(MetadataID))
865 return tokError(
"Metadata id is already used");
866 NumberedMetadata[MetadataID].reset(
Init);
873bool LLParser::skipModuleSummaryEntry() {
883 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
884 "start of summary entry");
886 return parseSummaryIndexFlags();
888 return parseBlockCount();
890 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
891 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
895 unsigned NumOpenParen = 1;
905 return tokError(
"found end of file while parsing summary entry");
911 }
while (NumOpenParen > 0);
917bool LLParser::parseSummaryEntry() {
931 return skipModuleSummaryEntry();
936 result = parseGVEntry(SummaryID);
939 result = parseModuleEntry(SummaryID);
942 result = parseTypeIdEntry(SummaryID);
945 result = parseTypeIdCompatibleVtableEntry(SummaryID);
948 result = parseSummaryIndexFlags();
951 result = parseBlockCount();
954 result =
error(Lex.
getLoc(),
"unexpected summary kind");
991bool LLParser::parseAliasOrIFunc(
const std::string &
Name, LocTy NameLoc,
992 unsigned L,
unsigned Visibility,
993 unsigned DLLStorageClass,
bool DSOLocal,
1008 return error(NameLoc,
"invalid linkage type for alias");
1011 return error(NameLoc,
1012 "symbol with local linkage must have default visibility");
1015 return error(NameLoc,
1016 "symbol with local linkage cannot have a DLL storage class");
1020 if (parseType(Ty) ||
1021 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1030 if (parseGlobalTypeAndValue(Aliasee))
1035 if (parseValID(
ID,
nullptr))
1038 return error(AliaseeLoc,
"invalid aliasee");
1039 Aliasee =
ID.ConstantVal;
1043 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1045 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1046 unsigned AddrSpace = PTy->getAddressSpace();
1052 if (!
Name.empty()) {
1053 auto I = ForwardRefVals.find(
Name);
1054 if (
I != ForwardRefVals.end()) {
1055 GVal =
I->second.first;
1056 ForwardRefVals.erase(
Name);
1058 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1061 auto I = ForwardRefValIDs.find(NumberedVals.size());
1062 if (
I != ForwardRefValIDs.end()) {
1063 GVal =
I->second.first;
1064 ForwardRefValIDs.erase(
I);
1069 std::unique_ptr<GlobalAlias> GA;
1070 std::unique_ptr<GlobalIFunc> GI;
1100 return tokError(
"unknown alias or ifunc property!");
1105 NumberedVals.push_back(GV);
1112 "forward reference and definition of alias have different types");
1134 case lltok::kw_sanitize_memtag:
1150 Meta.NoAddress =
true;
1153 Meta.NoHWAddress =
true;
1155 case lltok::kw_sanitize_memtag:
1159 Meta.IsDynInit =
true;
1162 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1182bool LLParser::parseGlobal(
const std::string &
Name, LocTy NameLoc,
1183 unsigned Linkage,
bool HasLinkage,
1184 unsigned Visibility,
unsigned DLLStorageClass,
1188 return error(NameLoc,
1189 "symbol with local linkage must have default visibility");
1192 return error(NameLoc,
1193 "symbol with local linkage cannot have a DLL storage class");
1197 LocTy IsExternallyInitializedLoc;
1201 if (parseOptionalAddrSpace(AddrSpace) ||
1203 IsExternallyInitialized,
1204 &IsExternallyInitializedLoc) ||
1205 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1214 if (parseGlobalValue(Ty,
Init))
1219 return error(TyLoc,
"invalid type for global variable");
1224 if (!
Name.empty()) {
1225 auto I = ForwardRefVals.find(
Name);
1226 if (
I != ForwardRefVals.end()) {
1227 GVal =
I->second.first;
1228 ForwardRefVals.erase(
I);
1230 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1233 auto I = ForwardRefValIDs.find(NumberedVals.size());
1234 if (
I != ForwardRefValIDs.end()) {
1235 GVal =
I->second.first;
1236 ForwardRefValIDs.erase(
I);
1245 NumberedVals.push_back(GV);
1263 "forward reference and definition of global have different types");
1283 }
else if (Lex.
getKind() == lltok::kw_align) {
1285 if (parseOptionalAlignment(Alignment))
1290 if (parseGlobalObjectMetadataAttachment(*GV))
1293 if (parseSanitizer(GV))
1297 if (parseOptionalComdat(
Name,
C))
1302 return tokError(
"unknown global variable property!");
1308 std::vector<unsigned> FwdRefAttrGrps;
1309 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1311 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1313 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1321bool LLParser::parseUnnamedAttrGrp() {
1327 return tokError(
"expected attribute group id");
1330 std::vector<unsigned> unused;
1338 auto R = NumberedAttrBuilders.find(VarID);
1339 if (R == NumberedAttrBuilders.end())
1342 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1343 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1346 if (!
R->second.hasAttributes())
1347 return error(AttrGrpLoc,
"attribute group has no attributes");
1354#define GET_ATTR_NAMES
1355#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1356 case lltok::kw_##DISPLAY_NAME: \
1357 return Attribute::ENUM_NAME;
1358#include "llvm/IR/Attributes.inc"
1367 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1370 case Attribute::Alignment: {
1379 if (parseOptionalAlignment(Alignment,
true))
1382 B.addAlignmentAttr(Alignment);
1385 case Attribute::StackAlignment: {
1390 parseUInt32(Alignment))
1393 if (parseOptionalStackAlignment(Alignment))
1396 B.addStackAlignmentAttr(Alignment);
1399 case Attribute::AllocSize: {
1400 unsigned ElemSizeArg;
1401 std::optional<unsigned> NumElemsArg;
1402 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1404 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1407 case Attribute::VScaleRange: {
1408 unsigned MinValue, MaxValue;
1409 if (parseVScaleRangeArguments(MinValue, MaxValue))
1411 B.addVScaleRangeAttr(MinValue,
1412 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1415 case Attribute::Dereferenceable: {
1417 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1419 B.addDereferenceableAttr(Bytes);
1422 case Attribute::DereferenceableOrNull: {
1424 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1426 B.addDereferenceableOrNullAttr(Bytes);
1429 case Attribute::UWTable: {
1431 if (parseOptionalUWTableKind(Kind))
1433 B.addUWTableAttr(Kind);
1436 case Attribute::AllocKind: {
1438 if (parseAllocKind(Kind))
1440 B.addAllocKindAttr(Kind);
1443 case Attribute::Memory: {
1444 std::optional<MemoryEffects> ME = parseMemoryAttr();
1447 B.addMemoryAttr(*ME);
1450 case Attribute::NoFPClass: {
1453 B.addNoFPClassAttr(NoFPClass);
1460 B.addAttribute(Attr);
1468 case lltok::kw_readnone:
1471 case lltok::kw_readonly:
1474 case lltok::kw_writeonly:
1493bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1494 std::vector<unsigned> &FwdRefAttrGrps,
1495 bool InAttrGrp, LocTy &BuiltinLoc) {
1496 bool HaveError =
false;
1507 if (parseStringAttribute(
B))
1519 "cannot have an attribute group reference in an attribute group");
1529 if (Token == lltok::kw_builtin)
1541 return error(Lex.
getLoc(),
"unterminated attribute group");
1544 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1551 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1555 B.addMemoryAttr(ME);
1569 PTy->getAddressSpace());
1578 error(Loc,
"'" +
Name +
"' is not a basic block");
1580 error(Loc,
"'" +
Name +
"' defined with type '" +
1593 error(Loc,
"global variable reference must have pointer type");
1604 auto I = ForwardRefVals.find(
Name);
1605 if (
I != ForwardRefVals.end())
1606 Val =
I->second.first;
1611 return cast_or_null<GlobalValue>(
1612 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1616 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1623 error(Loc,
"global variable reference must have pointer type");
1627 GlobalValue *Val =
ID < NumberedVals.size() ? NumberedVals[
ID] :
nullptr;
1632 auto I = ForwardRefValIDs.find(
ID);
1633 if (
I != ForwardRefValIDs.end())
1634 Val =
I->second.first;
1639 return cast_or_null<GlobalValue>(
1640 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1644 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1652Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1656 if (
I != ComdatSymTab.
end())
1661 ForwardRefComdats[
Name] = Loc;
1671bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1673 return tokError(ErrMsg);
1680bool LLParser::parseStringConstant(std::string &Result) {
1682 return tokError(
"expected string constant");
1690bool LLParser::parseUInt32(
uint32_t &Val) {
1692 return tokError(
"expected integer");
1694 if (Val64 !=
unsigned(Val64))
1695 return tokError(
"expected 32-bit integer (too large)");
1703bool LLParser::parseUInt64(
uint64_t &Val) {
1705 return tokError(
"expected integer");
1718 return tokError(
"expected localdynamic, initialexec or localexec");
1746 return parseTLSModel(TLM) ||
1747 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1755bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1756 AddrSpace = DefaultAS;
1760 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1763 if (AddrSpaceStr ==
"A") {
1765 }
else if (AddrSpaceStr ==
"G") {
1767 }
else if (AddrSpaceStr ==
"P") {
1770 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1776 return tokError(
"expected integer or string constant");
1778 if (parseUInt32(AddrSpace))
1780 if (!isUInt<24>(AddrSpace))
1781 return error(Loc,
"invalid address space, must be a 24-bit integer");
1785 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1786 ParseAddrspaceValue(AddrSpace) ||
1797 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1799 B.addAttribute(Attr, Val);
1804bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1805 bool HaveError =
false;
1812 if (parseStringAttribute(
B))
1822 if (parseEnumAttribute(Attr,
B,
false))
1826 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
1828 HaveError |=
error(Loc,
"this attribute does not apply to return values");
1876bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
1877 unsigned &Visibility,
1878 unsigned &DLLStorageClass,
bool &DSOLocal) {
1882 parseOptionalDSOLocal(DSOLocal);
1883 parseOptionalVisibility(Visibility);
1884 parseOptionalDLLStorageClass(DLLStorageClass);
1887 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
1893void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
1915void LLParser::parseOptionalVisibility(
unsigned &Res) {
1938void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2004bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2072 return parseUInt32(
CC);
2082bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2089 return parseMDNode(MD);
2094bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2097 return tokError(
"expected metadata after comma");
2101 if (parseMetadataAttachment(MDK,
N))
2104 if (MDK == LLVMContext::MD_DIAssignID)
2105 TempDIAssignIDAttachments[
N].push_back(&Inst);
2109 if (MDK == LLVMContext::MD_tbaa)
2110 InstsWithTBAATag.push_back(&Inst);
2119bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2122 if (parseMetadataAttachment(MDK,
N))
2131bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2133 if (parseGlobalObjectMetadataAttachment(
F))
2141bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2142 Alignment = std::nullopt;
2143 if (!EatIfPresent(lltok::kw_align))
2149 bool HaveParens =
false;
2155 if (parseUInt64(
Value))
2159 return error(ParenLoc,
"expected ')'");
2162 return error(AlignLoc,
"alignment is not a power of two");
2164 return error(AlignLoc,
"huge alignments are not supported yet");
2174bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2176 assert((AttrKind == lltok::kw_dereferenceable ||
2177 AttrKind == lltok::kw_dereferenceable_or_null) &&
2181 if (!EatIfPresent(AttrKind))
2185 return error(ParenLoc,
"expected '('");
2187 if (parseUInt64(Bytes))
2191 return error(ParenLoc,
"expected ')'");
2193 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2197bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2208 return error(KindLoc,
"expected unwind table kind");
2217 return error(ParenLoc,
"expected '('");
2220 if (parseStringConstant(Arg))
2221 return error(KindLoc,
"expected allockind value");
2225 }
else if (
A ==
"realloc") {
2227 }
else if (
A ==
"free") {
2229 }
else if (
A ==
"uninitialized") {
2231 }
else if (
A ==
"zeroed") {
2233 }
else if (
A ==
"aligned") {
2236 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2241 return error(ParenLoc,
"expected ')'");
2243 return error(KindLoc,
"expected allockind value");
2254 return std::nullopt;
2269 return std::nullopt;
2273std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2283 tokError(
"expected '('");
2284 return std::nullopt;
2287 bool SeenLoc =
false;
2293 tokError(
"expected ':' after location");
2294 return std::nullopt;
2301 tokError(
"expected memory location (argmem, inaccessiblemem) "
2302 "or access kind (none, read, write, readwrite)");
2304 tokError(
"expected access kind (none, read, write, readwrite)");
2305 return std::nullopt;
2314 tokError(
"default access kind must be specified first");
2315 return std::nullopt;
2324 tokError(
"unterminated memory attribute");
2325 return std::nullopt;
2367unsigned LLParser::parseNoFPClassAttr() {
2372 tokError(
"expected '('");
2379 if (TestMask != 0) {
2383 !parseUInt64(
Value)) {
2385 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2396 error(Lex.
getLoc(),
"expected nofpclass test mask");
2414bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2415 bool &AteExtraComma) {
2416 AteExtraComma =
false;
2420 AteExtraComma =
true;
2424 if (Lex.
getKind() != lltok::kw_align)
2425 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2427 if (parseOptionalAlignment(Alignment))
2440bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2441 bool &AteExtraComma) {
2442 AteExtraComma =
false;
2446 AteExtraComma =
true;
2452 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2454 if (parseOptionalAddrSpace(AddrSpace))
2461bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2462 std::optional<unsigned> &HowManyArg) {
2465 auto StartParen = Lex.
getLoc();
2467 return error(StartParen,
"expected '('");
2469 if (parseUInt32(BaseSizeArg))
2473 auto HowManyAt = Lex.
getLoc();
2475 if (parseUInt32(HowMany))
2477 if (HowMany == BaseSizeArg)
2478 return error(HowManyAt,
2479 "'allocsize' indices can't refer to the same parameter");
2480 HowManyArg = HowMany;
2482 HowManyArg = std::nullopt;
2484 auto EndParen = Lex.
getLoc();
2486 return error(EndParen,
"expected ')'");
2490bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2491 unsigned &MaxValue) {
2494 auto StartParen = Lex.
getLoc();
2496 return error(StartParen,
"expected '('");
2498 if (parseUInt32(MinValue))
2502 if (parseUInt32(MaxValue))
2505 MaxValue = MinValue;
2507 auto EndParen = Lex.
getLoc();
2509 return error(EndParen,
"expected ')'");
2518bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2523 return parseScope(SSID) || parseOrdering(Ordering);
2533 auto StartParenAt = Lex.
getLoc();
2535 return error(StartParenAt,
"Expected '(' in syncscope");
2538 auto SSNAt = Lex.
getLoc();
2539 if (parseStringConstant(SSN))
2540 return error(SSNAt,
"Expected synchronization scope name");
2542 auto EndParenAt = Lex.
getLoc();
2544 return error(EndParenAt,
"Expected ')' in syncscope");
2559 return tokError(
"Expected ordering on atomic instruction");
2578bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2580 if (!EatIfPresent(lltok::kw_alignstack))
2584 return error(ParenLoc,
"expected '('");
2586 if (parseUInt32(Alignment))
2590 return error(ParenLoc,
"expected ')'");
2592 return error(AlignLoc,
"stack alignment is not a power of two");
2606 bool &AteExtraComma) {
2607 AteExtraComma =
false;
2610 return tokError(
"expected ',' as start of index list");
2614 if (Indices.
empty())
2615 return tokError(
"expected index");
2616 AteExtraComma =
true;
2620 if (parseUInt32(
Idx))
2633bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2637 return tokError(Msg);
2646 if (
Result->isPointerTy()) {
2648 if (parseOptionalAddrSpace(AddrSpace))
2654 return tokError(
"ptr* is invalid - use ptr instead");
2665 if (parseTargetExtType(Result))
2671 if (parseAnonStructType(Result,
false))
2677 if (parseArrayVectorType(Result,
false))
2684 if (parseAnonStructType(Result,
true) ||
2685 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2687 }
else if (parseArrayVectorType(Result,
true))
2692 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.
getStrVal()];
2698 Entry.second = Lex.
getLoc();
2707 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.
getUIntVal()];
2713 Entry.second = Lex.
getLoc();
2726 if (!AllowVoid &&
Result->isVoidTy())
2727 return error(TypeLoc,
"void type only allowed for function results");
2733 return tokError(
"basic block pointers are invalid");
2735 return tokError(
"pointers to void are invalid - use i8* instead");
2737 return tokError(
"pointer to this type is invalid");
2745 return tokError(
"basic block pointers are invalid");
2747 return tokError(
"pointers to void are invalid; use i8* instead");
2749 return tokError(
"pointer to this type is invalid");
2751 if (parseOptionalAddrSpace(AddrSpace) ||
2752 parseToken(
lltok::star,
"expected '*' in address space"))
2761 if (parseFunctionType(Result))
2774 PerFunctionState &PFS,
bool IsMustTailCall,
2775 bool InVarArgsFunc) {
2781 if (!ArgList.
empty() &&
2782 parseToken(
lltok::comma,
"expected ',' in argument list"))
2787 const char *
Msg =
"unexpected ellipsis in argument list for ";
2788 if (!IsMustTailCall)
2789 return tokError(
Twine(Msg) +
"non-musttail call");
2791 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
2793 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
2798 Type *ArgTy =
nullptr;
2800 if (parseType(ArgTy, ArgLoc))
2806 if (parseMetadataAsValue(V, PFS))
2810 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2817 if (IsMustTailCall && InVarArgsFunc)
2818 return tokError(
"expected '...' at end of argument list for musttail call "
2819 "in varargs function");
2830 if (!EatIfPresent(AttrToken))
2839 B.addTypeAttr(AttrKind, Ty);
2852bool LLParser::parseOptionalOperandBundles(
2860 if (!BundleList.
empty() &&
2861 parseToken(
lltok::comma,
"expected ',' in input list"))
2865 if (parseStringConstant(
Tag))
2868 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
2871 std::vector<Value *> Inputs;
2874 if (!Inputs.empty() &&
2875 parseToken(
lltok::comma,
"expected ',' in input list"))
2879 Value *Input =
nullptr;
2880 if (parseType(Ty) || parseValue(Ty, Input, PFS))
2882 Inputs.push_back(Input);
2890 if (BundleList.
empty())
2891 return error(BeginLoc,
"operand bundle set must not be empty");
2908 unsigned CurValID = 0;
2920 Type *ArgTy =
nullptr;
2924 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2928 return error(TypeLoc,
"argument can not have void type");
2935 return error(TypeLoc,
"argument expected to be numbered '%" +
2936 Twine(CurValID) +
"'");
2942 return error(TypeLoc,
"invalid type for function argument");
2957 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2961 return error(TypeLoc,
"argument can not have void type");
2969 return error(TypeLoc,
"argument expected to be numbered '%" +
2970 Twine(CurValID) +
"'");
2978 return error(TypeLoc,
"invalid type for function argument");
2986 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
2991bool LLParser::parseFunctionType(
Type *&Result) {
2995 return tokError(
"invalid function return type");
2999 if (parseArgumentList(ArgList, IsVarArg))
3003 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
3004 if (!ArgList[i].
Name.empty())
3005 return error(ArgList[i].Loc,
"argument name invalid in function type");
3006 if (ArgList[i].
Attrs.hasAttributes())
3007 return error(ArgList[i].Loc,
3008 "argument attributes invalid in function type");
3012 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
3021bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3023 if (parseStructBody(Elts))
3032 std::pair<Type *, LocTy> &Entry,
3035 if (Entry.first && !Entry.second.isValid())
3036 return error(TypeLoc,
"redefinition of type");
3042 Entry.second =
SMLoc();
3047 ResultTy = Entry.first;
3059 return error(TypeLoc,
"forward references to non-struct type");
3063 return parseArrayVectorType(ResultTy,
true);
3064 return parseType(ResultTy);
3068 Entry.second =
SMLoc();
3074 StructType *STy = cast<StructType>(Entry.first);
3077 if (parseStructBody(Body) ||
3078 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3107 return error(EltTyLoc,
"invalid element type for struct");
3115 return error(EltTyLoc,
"invalid element type for struct");
3120 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3129bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3130 bool Scalable =
false;
3134 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3142 return tokError(
"expected number in address space");
3148 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3152 Type *EltTy =
nullptr;
3153 if (parseType(EltTy))
3157 "expected end of sequential type"))
3162 return error(SizeLoc,
"zero element vector is illegal");
3164 return error(SizeLoc,
"size too large for vector");
3166 return error(TypeLoc,
"invalid vector element type");
3170 return error(TypeLoc,
"invalid array element type");
3187bool LLParser::parseTargetExtType(
Type *&Result) {
3192 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3193 parseStringConstant(TypeName))
3201 bool SeenInt =
false;
3208 if (parseUInt32(IntVal))
3211 }
else if (SeenInt) {
3214 return tokError(
"expected uint32 param");
3217 if (parseType(TypeParam,
true))
3223 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3236 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3241 NumberedVals.push_back(&
A);
3244LLParser::PerFunctionState::~PerFunctionState() {
3247 for (
const auto &
P : ForwardRefVals) {
3248 if (isa<BasicBlock>(
P.second.first))
3250 P.second.first->replaceAllUsesWith(
3252 P.second.first->deleteValue();
3255 for (
const auto &
P : ForwardRefValIDs) {
3256 if (isa<BasicBlock>(
P.second.first))
3258 P.second.first->replaceAllUsesWith(
3260 P.second.first->deleteValue();
3264bool LLParser::PerFunctionState::finishFunction() {
3265 if (!ForwardRefVals.empty())
3266 return P.error(ForwardRefVals.begin()->second.second,
3267 "use of undefined value '%" + ForwardRefVals.begin()->first +
3269 if (!ForwardRefValIDs.empty())
3270 return P.error(ForwardRefValIDs.begin()->second.second,
3271 "use of undefined value '%" +
3272 Twine(ForwardRefValIDs.begin()->first) +
"'");
3279Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3282 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3287 auto I = ForwardRefVals.find(
Name);
3288 if (
I != ForwardRefVals.end())
3289 Val =
I->second.first;
3294 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3298 P.error(Loc,
"invalid use of a non-first-class type");
3310 P.error(Loc,
"name is too long which can result in name collisions, "
3311 "consider making the name shorter or "
3312 "increasing -non-global-value-max-name-size");
3316 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3320Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3322 Value *Val =
ID < NumberedVals.size() ? NumberedVals[
ID] :
nullptr;
3327 auto I = ForwardRefValIDs.find(
ID);
3328 if (
I != ForwardRefValIDs.end())
3329 Val =
I->second.first;
3334 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3337 P.error(Loc,
"invalid use of a non-first-class type");
3349 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3355bool LLParser::PerFunctionState::setInstName(
int NameID,
3356 const std::string &NameStr,
3360 if (NameID != -1 || !NameStr.empty())
3361 return P.error(NameLoc,
"instructions returning void cannot have a name");
3367 if (NameStr.empty()) {
3370 NameID = NumberedVals.size();
3372 if (
unsigned(NameID) != NumberedVals.size())
3373 return P.error(NameLoc,
"instruction expected to be numbered '%" +
3374 Twine(NumberedVals.size()) +
"'");
3376 auto FI = ForwardRefValIDs.find(NameID);
3377 if (FI != ForwardRefValIDs.end()) {
3380 return P.error(NameLoc,
"instruction forward referenced with type '" +
3384 Sentinel->replaceAllUsesWith(Inst);
3386 ForwardRefValIDs.erase(FI);
3389 NumberedVals.push_back(Inst);
3394 auto FI = ForwardRefVals.find(NameStr);
3395 if (FI != ForwardRefVals.end()) {
3398 return P.error(NameLoc,
"instruction forward referenced with type '" +
3402 Sentinel->replaceAllUsesWith(Inst);
3404 ForwardRefVals.erase(FI);
3410 if (Inst->
getName() != NameStr)
3411 return P.error(NameLoc,
"multiple definition of local value named '" +
3418BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3420 return dyn_cast_or_null<BasicBlock>(
3424BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3425 return dyn_cast_or_null<BasicBlock>(
3432BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3433 int NameID, LocTy Loc) {
3436 if (NameID != -1 &&
unsigned(NameID) != NumberedVals.size()) {
3437 P.error(Loc,
"label expected to be numbered '" +
3438 Twine(NumberedVals.size()) +
"'");
3441 BB = getBB(NumberedVals.size(), Loc);
3443 P.error(Loc,
"unable to create block numbered '" +
3444 Twine(NumberedVals.size()) +
"'");
3448 BB = getBB(
Name, Loc);
3450 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3461 ForwardRefValIDs.erase(NumberedVals.size());
3462 NumberedVals.push_back(BB);
3465 ForwardRefVals.erase(
Name);
3482bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3486 return tokError(
"expected value token");
3529 if (parseGlobalValueVector(Elts) ||
3530 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3533 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3534 ID.UIntVal = Elts.
size();
3535 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3536 Elts.
size() *
sizeof(Elts[0]));
3548 if (parseGlobalValueVector(Elts) ||
3550 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3554 if (isPackedStruct) {
3555 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3556 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3557 Elts.
size() *
sizeof(Elts[0]));
3558 ID.UIntVal = Elts.
size();
3564 return error(
ID.Loc,
"constant vector must not be empty");
3566 if (!Elts[0]->
getType()->isIntegerTy() &&
3567 !Elts[0]->
getType()->isFloatingPointTy() &&
3568 !Elts[0]->
getType()->isPointerTy())
3571 "vector elements must have integer, pointer or floating point type");
3574 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3576 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3577 " is not of type '" +
3588 if (parseGlobalValueVector(Elts) ||
3600 if (!Elts[0]->
getType()->isFirstClassType())
3601 return error(FirstEltLoc,
"invalid array element type: " +
3607 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3609 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3610 " is not of type '" +
3630 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3633 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3636 parseStringConstant(
ID.StrVal) ||
3637 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3642 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
3653 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3654 parseValID(Fn, PFS) ||
3656 "expected comma in block address expression") ||
3657 parseValID(Label, PFS) ||
3658 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
3662 return error(Fn.
Loc,
"expected function name in blockaddress");
3664 return error(
Label.Loc,
"expected basic block name in blockaddress");
3669 if (Fn.
UIntVal < NumberedVals.size())
3670 GV = NumberedVals[Fn.
UIntVal];
3671 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3677 if (!isa<Function>(GV))
3678 return error(Fn.
Loc,
"expected function name in blockaddress");
3679 F = cast<Function>(GV);
3680 if (
F->isDeclaration())
3681 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
3687 ForwardRefBlockAddresses.insert(std::make_pair(
3689 std::map<ValID, GlobalValue *>()))
3690 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
3699 "type of blockaddress must be a pointer and not '" +
3704 FwdDeclAS = PFS->getFunction().getAddressSpace();
3713 ID.ConstantVal = FwdRef;
3721 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
3723 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
3725 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
3727 return error(
Label.Loc,
"referenced value is not a basic block");
3730 return error(
Label.Loc,
"cannot take address of numeric label after "
3731 "the function is defined");
3732 BB = dyn_cast_or_null<BasicBlock>(
3733 F->getValueSymbolTable()->lookup(
Label.StrVal));
3735 return error(
Label.Loc,
"referenced value is not a basic block");
3749 if (parseValID(Fn, PFS))
3754 "expected global value name in dso_local_equivalent");
3759 if (Fn.
UIntVal < NumberedVals.size())
3760 GV = NumberedVals[Fn.
UIntVal];
3761 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3768 ? ForwardRefDSOLocalEquivalentIDs
3769 : ForwardRefDSOLocalEquivalentNames;
3770 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn,
nullptr).first->second;
3777 ID.ConstantVal = FwdRef;
3783 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
3784 "in dso_local_equivalent");
3795 if (parseValID(
ID, PFS))
3799 return error(
ID.Loc,
"expected global value name in no_cfi");
3819 Type *DestTy =
nullptr;
3822 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
3823 parseGlobalTypeAndValue(SrcVal) ||
3824 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
3825 parseType(DestTy) ||
3826 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
3829 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
3838 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
3840 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
3842 return error(
ID.Loc,
"udiv constexprs are no longer supported");
3844 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
3846 return error(
ID.Loc,
"urem constexprs are no longer supported");
3848 return error(
ID.Loc,
"srem constexprs are no longer supported");
3850 return error(
ID.Loc,
"fadd constexprs are no longer supported");
3852 return error(
ID.Loc,
"fsub constexprs are no longer supported");
3854 return error(
ID.Loc,
"fmul constexprs are no longer supported");
3856 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
3858 return error(
ID.Loc,
"frem constexprs are no longer supported");
3860 return error(
ID.Loc,
"and constexprs are no longer supported");
3862 return error(
ID.Loc,
"or constexprs are no longer supported");
3864 return error(
ID.Loc,
"fneg constexprs are no longer supported");
3866 return error(
ID.Loc,
"select constexprs are no longer supported");
3872 if (parseCmpPredicate(PredVal, Opc) ||
3873 parseToken(
lltok::lparen,
"expected '(' in compare constantexpr") ||
3874 parseGlobalTypeAndValue(Val0) ||
3875 parseToken(
lltok::comma,
"expected comma in compare constantexpr") ||
3876 parseGlobalTypeAndValue(Val1) ||
3877 parseToken(
lltok::rparen,
"expected ')' in compare constantexpr"))
3881 return error(
ID.Loc,
"compare operands must have the same type");
3885 if (Opc == Instruction::FCmp) {
3887 return error(
ID.Loc,
"fcmp requires floating point operands");
3890 assert(Opc == Instruction::ICmp &&
"Unexpected opcode for CmpInst!");
3893 return error(
ID.Loc,
"icmp requires pointer or integer operands");
3913 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3914 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3922 }
else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3923 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3927 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
3928 parseGlobalTypeAndValue(Val0) ||
3929 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
3930 parseGlobalTypeAndValue(Val1) ||
3931 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
3934 return error(
ID.Loc,
"operands of constexpr must have same type");
3937 return error(
ID.Loc,
"constexpr requires integer operands");
3953 if (parseToken(
lltok::lparen,
"expected '(' in logical constantexpr") ||
3954 parseGlobalTypeAndValue(Val0) ||
3955 parseToken(
lltok::comma,
"expected comma in logical constantexpr") ||
3956 parseGlobalTypeAndValue(Val1) ||
3957 parseToken(
lltok::rparen,
"expected ')' in logical constantexpr"))
3960 return error(
ID.Loc,
"operands of constexpr must have same type");
3963 "constexpr requires integer or integer vector operands");
3975 bool InBounds =
false;
3979 if (Opc == Instruction::GetElementPtr)
3982 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
3985 if (Opc == Instruction::GetElementPtr) {
3986 if (parseType(Ty) ||
3987 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
3991 std::optional<unsigned> InRangeOp;
3992 if (parseGlobalValueVector(
3993 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp :
nullptr) ||
3997 if (Opc == Instruction::GetElementPtr) {
3998 if (Elts.
size() == 0 ||
3999 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4000 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4005 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4012 return error(
ID.Loc,
"getelementptr index must be an integer");
4013 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4014 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4015 if (GEPWidth && (ValNumEl != GEPWidth))
4018 "getelementptr vector index has a wrong number of elements");
4021 GEPWidth = ValNumEl;
4026 if (!Indices.empty() && !Ty->
isSized(&Visited))
4027 return error(
ID.Loc,
"base element of getelementptr must be sized");
4030 return error(
ID.Loc,
"invalid getelementptr indices");
4033 if (*InRangeOp == 0)
4035 "inrange keyword may not appear on pointer operand");
4040 InBounds, InRangeOp);
4041 }
else if (Opc == Instruction::ShuffleVector) {
4042 if (Elts.
size() != 3)
4043 return error(
ID.Loc,
"expected three operands to shufflevector");
4045 return error(
ID.Loc,
"invalid operands to shufflevector");
4049 }
else if (Opc == Instruction::ExtractElement) {
4050 if (Elts.
size() != 2)
4051 return error(
ID.Loc,
"expected two operands to extractelement");
4053 return error(
ID.Loc,
"invalid extractelement operands");
4056 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4057 if (Elts.
size() != 3)
4058 return error(
ID.Loc,
"expected three operands to insertelement");
4060 return error(
ID.Loc,
"invalid insertelement operands");
4079 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4080 convertValIDToValue(Ty,
ID, V,
nullptr);
4081 if (V && !(
C = dyn_cast<Constant>(V)))
4082 return error(
ID.Loc,
"global values must be constants");
4086bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4088 return parseType(Ty) || parseGlobalValue(Ty, V);
4100 return tokError(
"expected comdat variable");
4103 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4106 if (GlobalName.
empty())
4107 return tokError(
"comdat cannot be unnamed");
4108 C = getComdat(std::string(GlobalName), KwLoc);
4118 std::optional<unsigned> *InRangeOp) {
4128 *InRangeOp = Elts.
size();
4131 if (parseGlobalTypeAndValue(
C))
4139bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4141 if (parseMDNodeVector(Elts))
4152bool LLParser::parseMDNode(
MDNode *&
N) {
4154 return parseSpecializedMDNode(
N);
4156 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4159bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4162 return parseMDTuple(
N);
4165 return parseMDNodeID(
N);
4171template <
class FieldTy>
struct MDFieldImpl {
4172 typedef MDFieldImpl ImplTy;
4176 void assign(FieldTy Val) {
4178 this->Val = std::move(Val);
4181 explicit MDFieldImpl(FieldTy
Default)
4189template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4190 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4201 void assign(FieldTypeA
A) {
4203 this->A = std::move(
A);
4207 void assign(FieldTypeB
B) {
4209 this->B = std::move(
B);
4213 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4215 WhatIs(IsInvalid) {}
4218struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4225struct LineField :
public MDUnsignedField {
4226 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4229struct ColumnField :
public MDUnsignedField {
4230 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4233struct DwarfTagField :
public MDUnsignedField {
4239struct DwarfMacinfoTypeField :
public MDUnsignedField {
4245struct DwarfAttEncodingField :
public MDUnsignedField {
4246 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4249struct DwarfVirtualityField :
public MDUnsignedField {
4253struct DwarfLangField :
public MDUnsignedField {
4257struct DwarfCCField :
public MDUnsignedField {
4258 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4261struct EmissionKindField :
public MDUnsignedField {
4262 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4265struct NameTableKindField :
public MDUnsignedField {
4266 NameTableKindField()
4269 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4272struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4273 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4276struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4277 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4280struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4281 MDAPSIntField() : ImplTy(
APSInt()) {}
4284struct MDSignedField :
public MDFieldImpl<int64_t> {
4288 MDSignedField(int64_t
Default = 0)
4290 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4294struct MDBoolField :
public MDFieldImpl<bool> {
4298struct MDField :
public MDFieldImpl<Metadata *> {
4301 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4304struct MDStringField :
public MDFieldImpl<MDString *> {
4306 MDStringField(
bool AllowEmpty =
true)
4307 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4310struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4314struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4318struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4319 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4320 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4322 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4323 bool AllowNull =
true)
4324 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4326 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4327 bool isMDField()
const {
return WhatIs == IsTypeB; }
4328 int64_t getMDSignedValue()
const {
4329 assert(isMDSignedField() &&
"Wrong field type");
4332 Metadata *getMDFieldValue()
const {
4333 assert(isMDField() &&
"Wrong field type");
4345 return tokError(
"expected integer");
4354 MDUnsignedField &Result) {
4356 return tokError(
"expected unsigned integer");
4359 if (U.ugt(Result.Max))
4360 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4362 Result.assign(U.getZExtValue());
4363 assert(Result.Val <= Result.Max &&
"Expected value in range");
4370 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4374 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4380 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4383 return tokError(
"expected DWARF tag");
4387 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4388 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4397 DwarfMacinfoTypeField &Result) {
4399 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4402 return tokError(
"expected DWARF macinfo type");
4406 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4408 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4410 Result.assign(Macinfo);
4417 DwarfVirtualityField &Result) {
4419 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4422 return tokError(
"expected DWARF virtuality code");
4426 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4428 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4429 Result.assign(Virtuality);
4437 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4440 return tokError(
"expected DWARF language");
4444 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4446 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4447 Result.assign(Lang);
4455 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4458 return tokError(
"expected DWARF calling convention");
4462 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4464 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4472 EmissionKindField &Result) {
4474 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4477 return tokError(
"expected emission kind");
4481 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4483 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4484 Result.assign(*Kind);
4491 NameTableKindField &Result) {
4493 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4496 return tokError(
"expected nameTable kind");
4500 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4502 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4503 Result.assign((
unsigned)*Kind);
4510 DwarfAttEncodingField &Result) {
4512 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4515 return tokError(
"expected DWARF type attribute encoding");
4519 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
4521 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
4522 Result.assign(Encoding);
4538 bool Res = parseUInt32(TempVal);
4544 return tokError(
"expected debug info flag");
4548 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
4563 Result.assign(Combined);
4578 bool Res = parseUInt32(TempVal);
4584 return tokError(
"expected debug info flag");
4588 return tokError(
Twine(
"invalid subprogram debug info flag '") +
4603 Result.assign(Combined);
4610 return tokError(
"expected signed integer");
4614 return tokError(
"value for '" +
Name +
"' too small, limit is " +
4617 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4619 Result.assign(S.getExtValue());
4620 assert(Result.Val >= Result.Min &&
"Expected value in range");
4621 assert(Result.Val <= Result.Max &&
"Expected value in range");
4630 return tokError(
"expected 'true' or 'false'");
4632 Result.assign(
true);
4635 Result.assign(
false);
4645 if (!Result.AllowNull)
4646 return tokError(
"'" +
Name +
"' cannot be null");
4648 Result.assign(
nullptr);
4653 if (parseMetadata(MD,
nullptr))
4662 MDSignedOrMDField &Result) {
4665 MDSignedField Res = Result.A;
4666 if (!parseMDField(Loc,
Name, Res)) {
4674 MDField Res = Result.B;
4675 if (!parseMDField(Loc,
Name, Res)) {
4687 if (parseStringConstant(S))
4690 if (!Result.AllowEmpty && S.empty())
4691 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
4693 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
4700 if (parseMDNodeVector(MDs))
4703 Result.assign(std::move(MDs));
4709 ChecksumKindField &Result) {
4710 std::optional<DIFile::ChecksumKind> CSKind =
4714 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
4717 Result.assign(*CSKind);
4724template <
class ParserTy>
4725bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4728 return tokError(
"expected field label here");
4737template <
class ParserTy>
4738bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4745 if (parseMDFieldsImplBody(ParseField))
4748 ClosingLoc = Lex.
getLoc();
4752template <
class FieldTy>
4753bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
4755 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
4759 return parseMDField(Loc,
Name, Result);
4762bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
4765#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4766 if (Lex.getStrVal() == #CLASS) \
4767 return parse##CLASS(N, IsDistinct);
4768#include "llvm/IR/Metadata.def"
4770 return tokError(
"expected metadata type");
4773#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4774#define NOP_FIELD(NAME, TYPE, INIT)
4775#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4777 return error(ClosingLoc, "missing required field '" #NAME "'");
4778#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4779 if (Lex.getStrVal() == #NAME) \
4780 return parseMDField(#NAME, NAME);
4781#define PARSE_MD_FIELDS() \
4782 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4785 if (parseMDFieldsImpl( \
4787 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4788 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4793 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4795#define GET_OR_DISTINCT(CLASS, ARGS) \
4796 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4801bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
4802#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4803 OPTIONAL(line, LineField, ); \
4804 OPTIONAL(column, ColumnField, ); \
4805 REQUIRED(scope, MDField, ( false)); \
4806 OPTIONAL(inlinedAt, MDField, ); \
4807 OPTIONAL(isImplicitCode, MDBoolField, (false));
4809#undef VISIT_MD_FIELDS
4813 inlinedAt.Val, isImplicitCode.Val));
4819bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
4821 return Lex.
Error(
"missing 'distinct', required for !DIAssignID()");
4837bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
4838#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4839 REQUIRED(tag, DwarfTagField, ); \
4840 OPTIONAL(header, MDStringField, ); \
4841 OPTIONAL(operands, MDFieldList, );
4843#undef VISIT_MD_FIELDS
4846 (Context, tag.Val, header.Val, operands.Val));
4854bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
4855#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4856 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4857 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4858 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4859 OPTIONAL(stride, MDSignedOrMDField, );
4861#undef VISIT_MD_FIELDS
4868 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
4869 if (Bound.isMDSignedField())
4872 if (Bound.isMDField())
4873 return Bound.getMDFieldValue();
4877 Count = convToMetadata(
count);
4878 LowerBound = convToMetadata(lowerBound);
4879 UpperBound = convToMetadata(upperBound);
4880 Stride = convToMetadata(stride);
4883 (Context, Count, LowerBound, UpperBound, Stride));
4891bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
4892#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4893 OPTIONAL(count, MDSignedOrMDField, ); \
4894 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4895 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4896 OPTIONAL(stride, MDSignedOrMDField, );
4898#undef VISIT_MD_FIELDS
4900 auto ConvToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
4901 if (Bound.isMDSignedField())
4903 Context, {dwarf::DW_OP_consts,
4904 static_cast<uint64_t>(Bound.getMDSignedValue())});
4905 if (Bound.isMDField())
4906 return Bound.getMDFieldValue();
4911 Metadata *LowerBound = ConvToMetadata(lowerBound);
4912 Metadata *UpperBound = ConvToMetadata(upperBound);
4913 Metadata *Stride = ConvToMetadata(stride);
4916 (Context, Count, LowerBound, UpperBound, Stride));
4923bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
4924#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4925 REQUIRED(name, MDStringField, ); \
4926 REQUIRED(value, MDAPSIntField, ); \
4927 OPTIONAL(isUnsigned, MDBoolField, (false));
4929#undef VISIT_MD_FIELDS
4931 if (isUnsigned.Val &&
value.Val.isNegative())
4932 return tokError(
"unsigned enumerator with negative value");
4937 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())