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();
129 restoreParsingState(Slots);
135 bool Status = parseDIExpressionBody(Result,
false);
137 Read =
End.getPointer() - Start.getPointer();
142void LLParser::restoreParsingState(
const SlotMapping *Slots) {
149 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
150 for (
const auto &
I : Slots->
Types)
151 NumberedTypes.insert(
152 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
157 if (!isa<DbgInfoIntrinsic>(
II) &&
158 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
163 if (
auto *MV = dyn_cast<MetadataAsValue>(V))
164 if (
auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
165 if (MD->isTemporary())
169 assert(
II->use_empty() &&
"Cannot have uses");
170 II->eraseFromParent();
179void LLParser::dropUnknownMetadataReferences() {
180 auto Pred = [](
unsigned MDKind,
MDNode *
Node) {
return Node->isTemporary(); };
182 F.eraseMetadataIf(Pred);
184 I.eraseMetadataIf(Pred);
186 if (
auto *
II = dyn_cast<IntrinsicInst>(&
I))
192 GV.eraseMetadataIf(Pred);
197 if (
Info.first->getNumTemporaryUses() == 1) {
198 NumberedMetadata.erase(
ID);
199 ForwardRefMDNodes.erase(
ID);
212 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
213 "Mixed debug intrinsics/records seen without a parsing error?");
218 M->setNewDbgInfoFormatFlag(SeenNewDbgInfoFormat);
222 for (
const auto &RAG : ForwardRefAttrGroups) {
224 const std::vector<unsigned> &
Attrs = RAG.second;
227 for (
const auto &Attr : Attrs) {
228 auto R = NumberedAttrBuilders.find(Attr);
229 if (R != NumberedAttrBuilders.end())
233 if (
Function *Fn = dyn_cast<Function>(V)) {
243 Fn->setAlignment(*
A);
248 Fn->setAttributes(AS);
249 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
255 CI->setAttributes(AS);
262 II->setAttributes(AS);
263 }
else if (
CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
269 CBI->setAttributes(AS);
270 }
else if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
281 if (!ForwardRefBlockAddresses.empty())
282 return error(ForwardRefBlockAddresses.begin()->first.Loc,
283 "expected function name in blockaddress");
285 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
289 GV =
M->getNamedValue(GVRef.
StrVal);
291 GV = NumberedVals.get(GVRef.
UIntVal);
296 "' referenced by dso_local_equivalent");
300 "expected a function, alias to function, or ifunc "
301 "in dso_local_equivalent");
304 FwdRef->replaceAllUsesWith(Equiv);
305 FwdRef->eraseFromParent();
312 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
313 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
316 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
317 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
320 ForwardRefDSOLocalEquivalentIDs.clear();
321 ForwardRefDSOLocalEquivalentNames.clear();
323 for (
const auto &NT : NumberedTypes)
324 if (
NT.second.second.isValid())
326 "use of undefined type '%" +
Twine(
NT.first) +
"'");
328 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
329 NamedTypes.begin(), E = NamedTypes.end();
I != E; ++
I)
330 if (
I->second.second.isValid())
331 return error(
I->second.second,
332 "use of undefined type named '" +
I->getKey() +
"'");
334 if (!ForwardRefComdats.empty())
335 return error(ForwardRefComdats.begin()->second,
336 "use of undefined comdat '$" +
337 ForwardRefComdats.begin()->first +
"'");
354 auto *CB = dyn_cast<CallBase>(
U.getUser());
355 if (!CB || !CB->isCallee(&U))
356 return error(
Info.second,
"intrinsic can only be used as callee");
361 return error(
Info.second,
"invalid intrinsic signature");
366 Info.first->eraseFromParent();
367 ForwardRefVals.erase(
Name);
378 for (
Use &U :
V->uses()) {
379 auto *CB = dyn_cast<CallBase>(
U.getUser());
380 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
382 FTy = CB->getFunctionType();
390 Type *Ty = GetCommonFunctionType(
Info.first);
395 if (
auto *FTy = dyn_cast<FunctionType>(Ty))
401 Info.first->replaceAllUsesWith(GV);
402 Info.first->eraseFromParent();
403 ForwardRefVals.erase(
Name);
406 if (!ForwardRefVals.empty())
407 return error(ForwardRefVals.begin()->second.second,
408 "use of undefined value '@" + ForwardRefVals.begin()->first +
411 if (!ForwardRefValIDs.empty())
412 return error(ForwardRefValIDs.begin()->second.second,
413 "use of undefined value '@" +
414 Twine(ForwardRefValIDs.begin()->first) +
"'");
417 dropUnknownMetadataReferences();
419 if (!ForwardRefMDNodes.empty())
420 return error(ForwardRefMDNodes.begin()->second.second,
421 "use of undefined metadata '!" +
422 Twine(ForwardRefMDNodes.begin()->first) +
"'");
425 for (
auto &
N : NumberedMetadata) {
426 if (
N.second && !
N.second->isResolved())
427 N.second->resolveCycles();
430 for (
auto *Inst : InstsWithTBAATag) {
431 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
434 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
437 if (MD != UpgradedMD)
438 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
447 if (UpgradeDebugInfo)
463 for (
const auto &
I : NamedTypes)
464 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
465 for (
const auto &
I : NumberedTypes)
466 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
472bool LLParser::validateEndOfIndex() {
476 if (!ForwardRefValueInfos.empty())
477 return error(ForwardRefValueInfos.begin()->second.front().second,
478 "use of undefined summary '^" +
479 Twine(ForwardRefValueInfos.begin()->first) +
"'");
481 if (!ForwardRefAliasees.empty())
482 return error(ForwardRefAliasees.begin()->second.front().second,
483 "use of undefined summary '^" +
484 Twine(ForwardRefAliasees.begin()->first) +
"'");
486 if (!ForwardRefTypeIds.empty())
487 return error(ForwardRefTypeIds.begin()->second.front().second,
488 "use of undefined type id summary '^" +
489 Twine(ForwardRefTypeIds.begin()->first) +
"'");
503 std::string TentativeDLStr =
M->getDataLayoutStr();
510 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
514 if (parseSourceFileName())
523 if (
auto LayoutOverride =
524 DataLayoutCallback(
M->getTargetTriple(), TentativeDLStr)) {
525 TentativeDLStr = *LayoutOverride;
531 M->setDataLayout(MaybeDL.
get());
535bool LLParser::parseTopLevelEntities() {
543 if (parseSummaryEntry())
547 if (parseSourceFileName())
559 return tokError(
"expected top-level entity");
570 if (parseModuleAsm())
574 if (parseUnnamedType())
578 if (parseNamedType())
582 if (parseUnnamedGlobal())
586 if (parseNamedGlobal())
591 if (parseStandaloneMetadata())
595 if (parseSummaryEntry())
599 if (parseNamedMetadata())
603 if (parseUnnamedAttrGrp())
607 if (parseUseListOrder())
611 if (parseUseListOrderBB())
620bool LLParser::parseModuleAsm() {
626 parseStringConstant(AsmStr))
629 M->appendModuleInlineAsm(AsmStr);
636bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
642 return tokError(
"unknown target property");
645 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
646 parseStringConstant(Str))
648 M->setTargetTriple(Str);
652 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
655 if (parseStringConstant(TentativeDLStr))
663bool LLParser::parseSourceFileName() {
666 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
667 parseStringConstant(SourceFileName))
670 M->setSourceFileName(SourceFileName);
676bool LLParser::parseUnnamedType() {
681 if (parseToken(
lltok::equal,
"expected '=' after name") ||
686 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
689 if (!isa<StructType>(Result)) {
690 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
692 return error(TypeLoc,
"non-struct types may not be recursive");
702bool LLParser::parseNamedType() {
707 if (parseToken(
lltok::equal,
"expected '=' after name") ||
712 if (parseStructDefinition(NameLoc,
Name, NamedTypes[
Name], Result))
715 if (!isa<StructType>(Result)) {
716 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
718 return error(NameLoc,
"non-struct types may not be recursive");
728bool LLParser::parseDeclare() {
732 std::vector<std::pair<unsigned, MDNode *>> MDs;
736 if (parseMetadataAttachment(MDK,
N))
738 MDs.push_back({MDK,
N});
742 unsigned FunctionNumber = -1;
744 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
747 F->addMetadata(MD.first, *MD.second);
753bool LLParser::parseDefine() {
758 unsigned FunctionNumber = -1;
760 return parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
761 parseOptionalFunctionMetadata(*
F) ||
762 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
768bool LLParser::parseGlobalType(
bool &IsConstant) {
775 return tokError(
"expected 'global' or 'constant'");
781bool LLParser::parseOptionalUnnamedAddr(
802bool LLParser::parseUnnamedGlobal() {
810 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(), VarID))
814 if (parseToken(
lltok::equal,
"expected '=' after name"))
817 VarID = NumberedVals.getNext();
821 unsigned Linkage, Visibility, DLLStorageClass;
825 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
827 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
832 return parseGlobal(
Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
833 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
836 return parseAliasOrIFunc(
Name, VarID, NameLoc, Linkage, Visibility,
837 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
846bool LLParser::parseNamedGlobal() {
853 unsigned Linkage, Visibility, DLLStorageClass;
857 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
858 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
860 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
865 return parseGlobal(
Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
866 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
869 return parseAliasOrIFunc(
Name, -1, NameLoc, Linkage, Visibility,
870 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
874bool LLParser::parseComdat() {
884 return tokError(
"expected comdat type");
889 return tokError(
"unknown selection kind");
911 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(
Name))
912 return error(NameLoc,
"redefinition of comdat '$" +
Name +
"'");
915 if (
I != ComdatSymTab.
end())
918 C =
M->getOrInsertComdat(
Name);
919 C->setSelectionKind(SK);
926bool LLParser::parseMDString(
MDString *&Result) {
928 if (parseStringConstant(Str))
936bool LLParser::parseMDNodeID(
MDNode *&Result) {
940 if (parseUInt32(MID))
944 if (NumberedMetadata.count(MID)) {
945 Result = NumberedMetadata[MID];
950 auto &FwdRef = ForwardRefMDNodes[MID];
953 Result = FwdRef.first.get();
954 NumberedMetadata[MID].reset(Result);
960bool LLParser::parseNamedMetadata() {
979 if (parseDIExpression(
N,
false))
985 return tokError(
"found DIArgList outside of function");
993 return parseToken(
lltok::rbrace,
"expected end of metadata node");
998bool LLParser::parseStandaloneMetadata() {
1001 unsigned MetadataID = 0;
1004 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1009 return tokError(
"unexpected type in metadata definition");
1013 if (parseSpecializedMDNode(
Init, IsDistinct))
1016 parseMDTuple(
Init, IsDistinct))
1020 auto FI = ForwardRefMDNodes.find(MetadataID);
1021 if (FI != ForwardRefMDNodes.end()) {
1022 auto *ToReplace = FI->second.first.get();
1025 if (isa<DIAssignID>(
Init)) {
1026 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1027 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1028 "Inst unexpectedly already has DIAssignID attachment");
1029 Inst->setMetadata(LLVMContext::MD_DIAssignID,
Init);
1033 ToReplace->replaceAllUsesWith(
Init);
1034 ForwardRefMDNodes.erase(FI);
1036 assert(NumberedMetadata[MetadataID] ==
Init &&
"Tracking VH didn't work");
1038 if (NumberedMetadata.count(MetadataID))
1039 return tokError(
"Metadata id is already used");
1040 NumberedMetadata[MetadataID].reset(
Init);
1047bool LLParser::skipModuleSummaryEntry() {
1057 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1058 "start of summary entry");
1060 return parseSummaryIndexFlags();
1062 return parseBlockCount();
1064 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1065 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1069 unsigned NumOpenParen = 1;
1079 return tokError(
"found end of file while parsing summary entry");
1085 }
while (NumOpenParen > 0);
1091bool LLParser::parseSummaryEntry() {
1105 return skipModuleSummaryEntry();
1107 bool result =
false;
1110 result = parseGVEntry(SummaryID);
1113 result = parseModuleEntry(SummaryID);
1116 result = parseTypeIdEntry(SummaryID);
1119 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1122 result = parseSummaryIndexFlags();
1125 result = parseBlockCount();
1128 result =
error(Lex.
getLoc(),
"unexpected summary kind");
1165bool LLParser::parseAliasOrIFunc(
const std::string &
Name,
unsigned NameID,
1166 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1167 unsigned DLLStorageClass,
bool DSOLocal,
1182 return error(NameLoc,
"invalid linkage type for alias");
1185 return error(NameLoc,
1186 "symbol with local linkage must have default visibility");
1189 return error(NameLoc,
1190 "symbol with local linkage cannot have a DLL storage class");
1194 if (parseType(Ty) ||
1195 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1204 if (parseGlobalTypeAndValue(Aliasee))
1209 if (parseValID(
ID,
nullptr))
1212 return error(AliaseeLoc,
"invalid aliasee");
1213 Aliasee =
ID.ConstantVal;
1217 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1219 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1220 unsigned AddrSpace = PTy->getAddressSpace();
1226 if (!
Name.empty()) {
1227 auto I = ForwardRefVals.find(
Name);
1228 if (
I != ForwardRefVals.end()) {
1229 GVal =
I->second.first;
1230 ForwardRefVals.erase(
Name);
1231 }
else if (
M->getNamedValue(
Name)) {
1232 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1235 auto I = ForwardRefValIDs.find(NameID);
1236 if (
I != ForwardRefValIDs.end()) {
1237 GVal =
I->second.first;
1238 ForwardRefValIDs.erase(
I);
1243 std::unique_ptr<GlobalAlias> GA;
1244 std::unique_ptr<GlobalIFunc> GI;
1274 return tokError(
"unknown alias or ifunc property!");
1279 NumberedVals.add(NameID, GV);
1286 "forward reference and definition of alias have different types");
1296 M->insertAlias(GA.release());
1298 M->insertIFunc(GI.release());
1308 case lltok::kw_sanitize_memtag:
1324 Meta.NoAddress =
true;
1327 Meta.NoHWAddress =
true;
1329 case lltok::kw_sanitize_memtag:
1333 Meta.IsDynInit =
true;
1336 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1356bool LLParser::parseGlobal(
const std::string &
Name,
unsigned NameID,
1357 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1358 unsigned Visibility,
unsigned DLLStorageClass,
1362 return error(NameLoc,
1363 "symbol with local linkage must have default visibility");
1366 return error(NameLoc,
1367 "symbol with local linkage cannot have a DLL storage class");
1371 LocTy IsExternallyInitializedLoc;
1375 if (parseOptionalAddrSpace(AddrSpace) ||
1377 IsExternallyInitialized,
1378 &IsExternallyInitializedLoc) ||
1379 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1388 if (parseGlobalValue(Ty,
Init))
1393 return error(TyLoc,
"invalid type for global variable");
1398 if (!
Name.empty()) {
1399 auto I = ForwardRefVals.find(
Name);
1400 if (
I != ForwardRefVals.end()) {
1401 GVal =
I->second.first;
1402 ForwardRefVals.erase(
I);
1403 }
else if (
M->getNamedValue(
Name)) {
1404 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1409 if (NameID == (
unsigned)-1)
1410 NameID = NumberedVals.getNext();
1412 auto I = ForwardRefValIDs.find(NameID);
1413 if (
I != ForwardRefValIDs.end()) {
1414 GVal =
I->second.first;
1415 ForwardRefValIDs.erase(
I);
1424 NumberedVals.add(NameID, GV);
1442 "forward reference and definition of global have different types");
1462 }
else if (Lex.
getKind() == lltok::kw_align) {
1464 if (parseOptionalAlignment(Alignment))
1470 if (parseOptionalCodeModel(CodeModel))
1474 if (parseGlobalObjectMetadataAttachment(*GV))
1477 if (parseSanitizer(GV))
1481 if (parseOptionalComdat(
Name,
C))
1486 return tokError(
"unknown global variable property!");
1492 std::vector<unsigned> FwdRefAttrGrps;
1493 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1495 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1497 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1505bool LLParser::parseUnnamedAttrGrp() {
1511 return tokError(
"expected attribute group id");
1514 std::vector<unsigned> unused;
1522 auto R = NumberedAttrBuilders.find(VarID);
1523 if (R == NumberedAttrBuilders.end())
1524 R = NumberedAttrBuilders.emplace(VarID,
AttrBuilder(
M->getContext())).first;
1526 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1527 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1530 if (!
R->second.hasAttributes())
1531 return error(AttrGrpLoc,
"attribute group has no attributes");
1538#define GET_ATTR_NAMES
1539#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1540 case lltok::kw_##DISPLAY_NAME: \
1541 return Attribute::ENUM_NAME;
1542#include "llvm/IR/Attributes.inc"
1551 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1554 case Attribute::Alignment: {
1563 if (parseOptionalAlignment(Alignment,
true))
1566 B.addAlignmentAttr(Alignment);
1569 case Attribute::StackAlignment: {
1574 parseUInt32(Alignment))
1577 if (parseOptionalStackAlignment(Alignment))
1580 B.addStackAlignmentAttr(Alignment);
1583 case Attribute::AllocSize: {
1584 unsigned ElemSizeArg;
1585 std::optional<unsigned> NumElemsArg;
1586 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1588 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1591 case Attribute::VScaleRange: {
1592 unsigned MinValue, MaxValue;
1593 if (parseVScaleRangeArguments(MinValue, MaxValue))
1595 B.addVScaleRangeAttr(MinValue,
1596 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1599 case Attribute::Dereferenceable: {
1601 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1603 B.addDereferenceableAttr(Bytes);
1606 case Attribute::DereferenceableOrNull: {
1608 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1610 B.addDereferenceableOrNullAttr(Bytes);
1613 case Attribute::UWTable: {
1615 if (parseOptionalUWTableKind(Kind))
1617 B.addUWTableAttr(Kind);
1620 case Attribute::AllocKind: {
1622 if (parseAllocKind(Kind))
1624 B.addAllocKindAttr(Kind);
1627 case Attribute::Memory: {
1628 std::optional<MemoryEffects> ME = parseMemoryAttr();
1631 B.addMemoryAttr(*ME);
1634 case Attribute::NoFPClass: {
1637 B.addNoFPClassAttr(NoFPClass);
1643 case Attribute::Range:
1644 return parseRangeAttr(
B);
1645 case Attribute::Initializes:
1646 return parseInitializesAttr(
B);
1648 B.addAttribute(Attr);
1656 case lltok::kw_readnone:
1659 case lltok::kw_readonly:
1662 case lltok::kw_writeonly:
1681bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1682 std::vector<unsigned> &FwdRefAttrGrps,
1683 bool InAttrGrp, LocTy &BuiltinLoc) {
1684 bool HaveError =
false;
1695 if (parseStringAttribute(
B))
1707 "cannot have an attribute group reference in an attribute group");
1717 if (Token == lltok::kw_builtin)
1729 return error(Lex.
getLoc(),
"unterminated attribute group");
1732 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1739 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1743 B.addMemoryAttr(ME);
1757 PTy->getAddressSpace());
1766 error(Loc,
"'" +
Name +
"' is not a basic block");
1768 error(Loc,
"'" +
Name +
"' defined with type '" +
1781 error(Loc,
"global variable reference must have pointer type");
1787 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1792 auto I = ForwardRefVals.find(
Name);
1793 if (
I != ForwardRefVals.end())
1794 Val =
I->second.first;
1799 return cast_or_null<GlobalValue>(
1800 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1804 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1811 error(Loc,
"global variable reference must have pointer type");
1820 auto I = ForwardRefValIDs.find(
ID);
1821 if (
I != ForwardRefValIDs.end())
1822 Val =
I->second.first;
1827 return cast_or_null<GlobalValue>(
1828 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1832 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1840Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1844 if (
I != ComdatSymTab.
end())
1849 ForwardRefComdats[
Name] = Loc;
1859bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1861 return tokError(ErrMsg);
1868bool LLParser::parseStringConstant(std::string &Result) {
1870 return tokError(
"expected string constant");
1878bool LLParser::parseUInt32(
uint32_t &Val) {
1880 return tokError(
"expected integer");
1882 if (Val64 !=
unsigned(Val64))
1883 return tokError(
"expected 32-bit integer (too large)");
1891bool LLParser::parseUInt64(
uint64_t &Val) {
1893 return tokError(
"expected integer");
1906 return tokError(
"expected localdynamic, initialexec or localexec");
1934 return parseTLSModel(TLM) ||
1935 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1943bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1944 AddrSpace = DefaultAS;
1948 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1951 if (AddrSpaceStr ==
"A") {
1952 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1953 }
else if (AddrSpaceStr ==
"G") {
1954 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1955 }
else if (AddrSpaceStr ==
"P") {
1956 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1958 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1964 return tokError(
"expected integer or string constant");
1966 if (parseUInt32(AddrSpace))
1968 if (!isUInt<24>(AddrSpace))
1969 return error(Loc,
"invalid address space, must be a 24-bit integer");
1973 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1974 ParseAddrspaceValue(AddrSpace) ||
1985 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1987 B.addAttribute(Attr, Val);
1992bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1993 bool HaveError =
false;
2000 if (parseStringAttribute(
B))
2010 if (parseEnumAttribute(Attr,
B,
false))
2014 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2016 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2064bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2065 unsigned &Visibility,
2066 unsigned &DLLStorageClass,
bool &DSOLocal) {
2070 parseOptionalDSOLocal(DSOLocal);
2071 parseOptionalVisibility(Visibility);
2072 parseOptionalDLLStorageClass(DLLStorageClass);
2075 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2081void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2103void LLParser::parseOptionalVisibility(
unsigned &Res) {
2121bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2125 return tokError(
"unknown import kind. Expect definition or declaration.");
2140void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2210bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2286 return parseUInt32(
CC);
2296bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2303 return parseMDNode(MD);
2308bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2311 return tokError(
"expected metadata after comma");
2315 if (parseMetadataAttachment(MDK,
N))
2318 if (MDK == LLVMContext::MD_DIAssignID)
2319 TempDIAssignIDAttachments[
N].push_back(&Inst);
2323 if (MDK == LLVMContext::MD_tbaa)
2324 InstsWithTBAATag.push_back(&Inst);
2333bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2336 if (parseMetadataAttachment(MDK,
N))
2345bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2347 if (parseGlobalObjectMetadataAttachment(
F))
2355bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2356 Alignment = std::nullopt;
2357 if (!EatIfPresent(lltok::kw_align))
2363 bool HaveParens =
false;
2369 if (parseUInt64(
Value))
2373 return error(ParenLoc,
"expected ')'");
2376 return error(AlignLoc,
"alignment is not a power of two");
2378 return error(AlignLoc,
"huge alignments are not supported yet");
2389 auto ErrMsg =
"expected global code model string";
2390 if (StrVal ==
"tiny")
2392 else if (StrVal ==
"small")
2394 else if (StrVal ==
"kernel")
2396 else if (StrVal ==
"medium")
2398 else if (StrVal ==
"large")
2401 return tokError(ErrMsg);
2412bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2414 assert((AttrKind == lltok::kw_dereferenceable ||
2415 AttrKind == lltok::kw_dereferenceable_or_null) &&
2419 if (!EatIfPresent(AttrKind))
2423 return error(ParenLoc,
"expected '('");
2425 if (parseUInt64(Bytes))
2429 return error(ParenLoc,
"expected ')'");
2431 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2435bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2446 return error(KindLoc,
"expected unwind table kind");
2455 return error(ParenLoc,
"expected '('");
2458 if (parseStringConstant(Arg))
2459 return error(KindLoc,
"expected allockind value");
2463 }
else if (
A ==
"realloc") {
2465 }
else if (
A ==
"free") {
2467 }
else if (
A ==
"uninitialized") {
2469 }
else if (
A ==
"zeroed") {
2471 }
else if (
A ==
"aligned") {
2474 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2479 return error(ParenLoc,
"expected ')'");
2481 return error(KindLoc,
"expected allockind value");
2492 return std::nullopt;
2507 return std::nullopt;
2511std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2521 tokError(
"expected '('");
2522 return std::nullopt;
2525 bool SeenLoc =
false;
2531 tokError(
"expected ':' after location");
2532 return std::nullopt;
2539 tokError(
"expected memory location (argmem, inaccessiblemem) "
2540 "or access kind (none, read, write, readwrite)");
2542 tokError(
"expected access kind (none, read, write, readwrite)");
2543 return std::nullopt;
2552 tokError(
"default access kind must be specified first");
2553 return std::nullopt;
2562 tokError(
"unterminated memory attribute");
2563 return std::nullopt;
2605unsigned LLParser::parseNoFPClassAttr() {
2610 tokError(
"expected '('");
2617 if (TestMask != 0) {
2621 !parseUInt64(
Value)) {
2623 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2634 error(Lex.
getLoc(),
"expected nofpclass test mask");
2652bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2653 bool &AteExtraComma) {
2654 AteExtraComma =
false;
2658 AteExtraComma =
true;
2662 if (Lex.
getKind() != lltok::kw_align)
2663 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2665 if (parseOptionalAlignment(Alignment))
2678bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2679 bool &AteExtraComma) {
2680 AteExtraComma =
false;
2684 AteExtraComma =
true;
2690 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2692 if (parseOptionalAddrSpace(AddrSpace))
2699bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2700 std::optional<unsigned> &HowManyArg) {
2703 auto StartParen = Lex.
getLoc();
2705 return error(StartParen,
"expected '('");
2707 if (parseUInt32(BaseSizeArg))
2711 auto HowManyAt = Lex.
getLoc();
2713 if (parseUInt32(HowMany))
2715 if (HowMany == BaseSizeArg)
2716 return error(HowManyAt,
2717 "'allocsize' indices can't refer to the same parameter");
2718 HowManyArg = HowMany;
2720 HowManyArg = std::nullopt;
2722 auto EndParen = Lex.
getLoc();
2724 return error(EndParen,
"expected ')'");
2728bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2729 unsigned &MaxValue) {
2732 auto StartParen = Lex.
getLoc();
2734 return error(StartParen,
"expected '('");
2736 if (parseUInt32(MinValue))
2740 if (parseUInt32(MaxValue))
2743 MaxValue = MinValue;
2745 auto EndParen = Lex.
getLoc();
2747 return error(EndParen,
"expected ')'");
2756bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2761 return parseScope(SSID) || parseOrdering(Ordering);
2771 auto StartParenAt = Lex.
getLoc();
2773 return error(StartParenAt,
"Expected '(' in syncscope");
2776 auto SSNAt = Lex.
getLoc();
2777 if (parseStringConstant(SSN))
2778 return error(SSNAt,
"Expected synchronization scope name");
2780 auto EndParenAt = Lex.
getLoc();
2782 return error(EndParenAt,
"Expected ')' in syncscope");
2797 return tokError(
"Expected ordering on atomic instruction");
2816bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2818 if (!EatIfPresent(lltok::kw_alignstack))
2822 return error(ParenLoc,
"expected '('");
2824 if (parseUInt32(Alignment))
2828 return error(ParenLoc,
"expected ')'");
2830 return error(AlignLoc,
"stack alignment is not a power of two");
2844 bool &AteExtraComma) {
2845 AteExtraComma =
false;
2848 return tokError(
"expected ',' as start of index list");
2852 if (Indices.
empty())
2853 return tokError(
"expected index");
2854 AteExtraComma =
true;
2858 if (parseUInt32(
Idx))
2871bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2875 return tokError(Msg);
2884 if (
Result->isPointerTy()) {
2886 if (parseOptionalAddrSpace(AddrSpace))
2892 return tokError(
"ptr* is invalid - use ptr instead");
2903 if (parseTargetExtType(Result))
2909 if (parseAnonStructType(Result,
false))
2915 if (parseArrayVectorType(Result,
false))
2922 if (parseAnonStructType(Result,
true) ||
2923 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2925 }
else if (parseArrayVectorType(Result,
true))
2964 if (!AllowVoid &&
Result->isVoidTy())
2965 return error(TypeLoc,
"void type only allowed for function results");
2971 return tokError(
"basic block pointers are invalid");
2973 return tokError(
"pointers to void are invalid - use i8* instead");
2975 return tokError(
"pointer to this type is invalid");
2983 return tokError(
"basic block pointers are invalid");
2985 return tokError(
"pointers to void are invalid; use i8* instead");
2987 return tokError(
"pointer to this type is invalid");
2989 if (parseOptionalAddrSpace(AddrSpace) ||
2990 parseToken(
lltok::star,
"expected '*' in address space"))
2999 if (parseFunctionType(Result))
3012 PerFunctionState &PFS,
bool IsMustTailCall,
3013 bool InVarArgsFunc) {
3019 if (!ArgList.
empty() &&
3020 parseToken(
lltok::comma,
"expected ',' in argument list"))
3025 const char *Msg =
"unexpected ellipsis in argument list for ";
3026 if (!IsMustTailCall)
3027 return tokError(
Twine(Msg) +
"non-musttail call");
3029 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
3031 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3036 Type *ArgTy =
nullptr;
3038 if (parseType(ArgTy, ArgLoc))
3044 if (parseMetadataAsValue(V, PFS))
3048 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3055 if (IsMustTailCall && InVarArgsFunc)
3056 return tokError(
"expected '...' at end of argument list for musttail call "
3057 "in varargs function");
3068 if (!EatIfPresent(AttrToken))
3077 B.addTypeAttr(AttrKind, Ty);
3093 return tokError(
"expected integer");
3096 "integer is too large for the bit width of specified type");
3102 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3105 return error(TyLoc,
"the range must have integer type!");
3113 return tokError(
"the range represent the empty set but limits aren't 0!");
3127 auto ParseAPSInt = [&](
APInt &Val) {
3129 return tokError(
"expected integer");
3150 return tokError(
"the range should not represent the full or empty set!");
3162 if (!CRLOrNull.has_value())
3163 return tokError(
"Invalid (unordered or overlapping) range list");
3164 B.addInitializesAttr(*CRLOrNull);
3177bool LLParser::parseOptionalOperandBundles(
3185 if (!BundleList.
empty() &&
3186 parseToken(
lltok::comma,
"expected ',' in input list"))
3190 if (parseStringConstant(
Tag))
3193 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3196 std::vector<Value *> Inputs;
3199 if (!Inputs.empty() &&
3200 parseToken(
lltok::comma,
"expected ',' in input list"))
3204 Value *Input =
nullptr;
3205 if (parseType(Ty) || parseValue(Ty, Input, PFS))
3207 Inputs.push_back(Input);
3215 if (BundleList.
empty())
3216 return error(BeginLoc,
"operand bundle set must not be empty");
3223 unsigned NextID,
unsigned ID)
const {
3225 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3226 Twine(NextID) +
"' or greater");
3243 unsigned CurValID = 0;
3258 Type *ArgTy =
nullptr;
3260 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3264 return error(TypeLoc,
"argument can not have void type");
3274 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3281 CurValID = ArgID + 1;
3285 return error(TypeLoc,
"invalid type for function argument");
3293 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3298bool LLParser::parseFunctionType(
Type *&Result) {
3302 return tokError(
"invalid function return type");
3307 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3311 for (
const ArgInfo &Arg : ArgList) {
3312 if (!Arg.Name.empty())
3313 return error(Arg.Loc,
"argument name invalid in function type");
3314 if (Arg.Attrs.hasAttributes())
3315 return error(Arg.Loc,
"argument attributes invalid in function type");
3319 for (
const ArgInfo &Arg : ArgList)
3328bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3330 if (parseStructBody(Elts))
3339 std::pair<Type *, LocTy> &Entry,
3343 return error(TypeLoc,
"redefinition of type");
3354 ResultTy =
Entry.first;
3366 return error(TypeLoc,
"forward references to non-struct type");
3370 return parseArrayVectorType(ResultTy,
true);
3371 return parseType(ResultTy);
3384 if (parseStructBody(Body) ||
3385 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3414 return error(EltTyLoc,
"invalid element type for struct");
3422 return error(EltTyLoc,
"invalid element type for struct");
3427 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3436bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3437 bool Scalable =
false;
3441 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3449 return tokError(
"expected number in address space");
3455 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3459 Type *EltTy =
nullptr;
3460 if (parseType(EltTy))
3464 "expected end of sequential type"))
3469 return error(SizeLoc,
"zero element vector is illegal");
3471 return error(SizeLoc,
"size too large for vector");
3473 return error(TypeLoc,
"invalid vector element type");
3477 return error(TypeLoc,
"invalid array element type");
3494bool LLParser::parseTargetExtType(
Type *&Result) {
3499 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3500 parseStringConstant(TypeName))
3508 bool SeenInt =
false;
3515 if (parseUInt32(IntVal))
3518 }
else if (SeenInt) {
3521 return tokError(
"expected uint32 param");
3524 if (parseType(TypeParam,
true))
3530 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3544 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3547 auto It = UnnamedArgNums.
begin();
3550 unsigned ArgNum = *It++;
3551 NumberedVals.add(ArgNum, &
A);
3556LLParser::PerFunctionState::~PerFunctionState() {
3559 for (
const auto &
P : ForwardRefVals) {
3560 if (isa<BasicBlock>(
P.second.first))
3562 P.second.first->replaceAllUsesWith(
3564 P.second.first->deleteValue();
3567 for (
const auto &
P : ForwardRefValIDs) {
3568 if (isa<BasicBlock>(
P.second.first))
3570 P.second.first->replaceAllUsesWith(
3572 P.second.first->deleteValue();
3576bool LLParser::PerFunctionState::finishFunction() {
3577 if (!ForwardRefVals.empty())
3578 return P.error(ForwardRefVals.begin()->second.second,
3579 "use of undefined value '%" + ForwardRefVals.begin()->first +
3581 if (!ForwardRefValIDs.empty())
3582 return P.error(ForwardRefValIDs.begin()->second.second,
3583 "use of undefined value '%" +
3584 Twine(ForwardRefValIDs.begin()->first) +
"'");
3591Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3594 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3599 auto I = ForwardRefVals.find(
Name);
3600 if (
I != ForwardRefVals.end())
3601 Val =
I->second.first;
3606 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3610 P.error(Loc,
"invalid use of a non-first-class type");
3622 P.error(Loc,
"name is too long which can result in name collisions, "
3623 "consider making the name shorter or "
3624 "increasing -non-global-value-max-name-size");
3628 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3632Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3634 Value *Val = NumberedVals.get(
ID);
3639 auto I = ForwardRefValIDs.find(
ID);
3640 if (
I != ForwardRefValIDs.end())
3641 Val =
I->second.first;
3646 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3649 P.error(Loc,
"invalid use of a non-first-class type");
3661 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3667bool LLParser::PerFunctionState::setInstName(
int NameID,
3668 const std::string &NameStr,
3672 if (NameID != -1 || !NameStr.empty())
3673 return P.error(NameLoc,
"instructions returning void cannot have a name");
3679 if (NameStr.empty()) {
3682 NameID = NumberedVals.getNext();
3684 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3688 auto FI = ForwardRefValIDs.find(NameID);
3689 if (FI != ForwardRefValIDs.end()) {
3692 return P.error(NameLoc,
"instruction forward referenced with type '" +
3696 Sentinel->replaceAllUsesWith(Inst);
3698 ForwardRefValIDs.erase(FI);
3701 NumberedVals.add(NameID, Inst);
3706 auto FI = ForwardRefVals.find(NameStr);
3707 if (FI != ForwardRefVals.end()) {
3710 return P.error(NameLoc,
"instruction forward referenced with type '" +
3714 Sentinel->replaceAllUsesWith(Inst);
3716 ForwardRefVals.erase(FI);
3722 if (Inst->
getName() != NameStr)
3723 return P.error(NameLoc,
"multiple definition of local value named '" +
3730BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3732 return dyn_cast_or_null<BasicBlock>(
3736BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3737 return dyn_cast_or_null<BasicBlock>(
3744BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3745 int NameID, LocTy Loc) {
3749 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3752 NameID = NumberedVals.getNext();
3754 BB = getBB(NameID, Loc);
3756 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3760 BB = getBB(
Name, Loc);
3762 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3773 ForwardRefValIDs.erase(NameID);
3774 NumberedVals.add(NameID, BB);
3777 ForwardRefVals.erase(
Name);
3794bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3798 return tokError(
"expected value token");
3841 if (parseGlobalValueVector(Elts) ||
3842 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3845 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3846 ID.UIntVal = Elts.
size();
3847 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3848 Elts.
size() *
sizeof(Elts[0]));
3860 if (parseGlobalValueVector(Elts) ||
3862 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3866 if (isPackedStruct) {
3867 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3868 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3869 Elts.
size() *
sizeof(Elts[0]));
3870 ID.UIntVal = Elts.
size();
3876 return error(
ID.Loc,
"constant vector must not be empty");
3878 if (!Elts[0]->
getType()->isIntegerTy() &&
3879 !Elts[0]->
getType()->isFloatingPointTy() &&
3883 "vector elements must have integer, pointer or floating point type");
3886 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3888 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3889 " is not of type '" +
3900 if (parseGlobalValueVector(Elts) ||
3912 if (!Elts[0]->
getType()->isFirstClassType())
3913 return error(FirstEltLoc,
"invalid array element type: " +
3919 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3921 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3922 " is not of type '" +
3942 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3945 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3948 parseStringConstant(
ID.StrVal) ||
3949 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3954 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
3965 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3966 parseValID(Fn, PFS) ||
3968 "expected comma in block address expression") ||
3969 parseValID(Label, PFS) ||
3970 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
3974 return error(Fn.
Loc,
"expected function name in blockaddress");
3976 return error(
Label.Loc,
"expected basic block name in blockaddress");
3981 GV = NumberedVals.get(Fn.
UIntVal);
3982 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3983 GV =
M->getNamedValue(Fn.
StrVal);
3988 if (!isa<Function>(GV))
3989 return error(Fn.
Loc,
"expected function name in blockaddress");
3990 F = cast<Function>(GV);
3991 if (
F->isDeclaration())
3992 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
3998 ForwardRefBlockAddresses.insert(std::make_pair(
4000 std::map<ValID, GlobalValue *>()))
4001 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
4010 "type of blockaddress must be a pointer and not '" +
4015 FwdDeclAS = PFS->getFunction().getAddressSpace();
4024 ID.ConstantVal = FwdRef;
4032 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4034 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4036 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4038 return error(
Label.Loc,
"referenced value is not a basic block");
4041 return error(
Label.Loc,
"cannot take address of numeric label after "
4042 "the function is defined");
4043 BB = dyn_cast_or_null<BasicBlock>(
4044 F->getValueSymbolTable()->lookup(
Label.StrVal));
4046 return error(
Label.Loc,
"referenced value is not a basic block");
4060 if (parseValID(Fn, PFS))
4065 "expected global value name in dso_local_equivalent");
4070 GV = NumberedVals.get(Fn.
UIntVal);
4071 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4072 GV =
M->getNamedValue(Fn.
StrVal);
4078 ? ForwardRefDSOLocalEquivalentIDs
4079 : ForwardRefDSOLocalEquivalentNames;
4080 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn,
nullptr).first->second;
4087 ID.ConstantVal = FwdRef;
4093 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4094 "in dso_local_equivalent");
4105 if (parseValID(
ID, PFS))
4109 return error(
ID.Loc,
"expected global value name in no_cfi");
4120 Constant *Disc =
nullptr, *AddrDisc =
nullptr;
4123 "expected '(' in constant ptrauth expression") ||
4124 parseGlobalTypeAndValue(
Ptr) ||
4126 "expected comma in constant ptrauth expression") ||
4127 parseGlobalTypeAndValue(Key))
4131 if (parseGlobalTypeAndValue(Disc) ||
4132 (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4135 "expected ')' in constant ptrauth expression"))
4138 if (!
Ptr->getType()->isPointerTy())
4139 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4141 auto *KeyC = dyn_cast<ConstantInt>(Key);
4142 if (!KeyC || KeyC->getBitWidth() != 32)
4143 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4147 DiscC = dyn_cast<ConstantInt>(Disc);
4151 "constant ptrauth integer discriminator must be i64 constant");
4157 if (!AddrDisc->getType()->isPointerTy())
4159 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4175 Type *DestTy =
nullptr;
4178 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4179 parseGlobalTypeAndValue(SrcVal) ||
4180 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4181 parseType(DestTy) ||
4182 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4185 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4194 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4196 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4198 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4200 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4202 return error(
ID.Loc,
"urem constexprs are no longer supported");
4204 return error(
ID.Loc,
"srem constexprs are no longer supported");
4206 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4208 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4210 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4212 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4214 return error(
ID.Loc,
"frem constexprs are no longer supported");
4216 return error(
ID.Loc,
"and constexprs are no longer supported");
4218 return error(
ID.Loc,
"or constexprs are no longer supported");
4220 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4222 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4224 return error(
ID.Loc,
"shl constexprs are no longer supported");
4226 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4228 return error(
ID.Loc,
"select constexprs are no longer supported");
4230 return error(
ID.Loc,
"zext constexprs are no longer supported");
4232 return error(
ID.Loc,
"sext constexprs are no longer supported");
4234 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4236 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4238 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4240 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4242 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4244 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4246 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4248 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4260 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4261 Opc == Instruction::Mul) {
4270 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4271 parseGlobalTypeAndValue(Val0) ||
4272 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4273 parseGlobalTypeAndValue(Val1) ||
4274 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4277 return error(
ID.Loc,
"operands of constexpr must have same type");
4281 "constexpr requires integer or integer vector operands");
4292 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4295 if (parseGlobalTypeAndValue(
C))
4297 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4312 bool HasInRange =
false;
4318 if (Opc == Instruction::GetElementPtr) {
4334 return tokError(
"expected integer");
4340 return tokError(
"expected integer");
4349 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4352 if (Opc == Instruction::GetElementPtr) {
4353 if (parseType(Ty) ||
4354 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4358 if (parseGlobalValueVector(Elts) ||
4362 if (Opc == Instruction::GetElementPtr) {
4363 if (Elts.
size() == 0 ||
4364 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4365 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4368 std::optional<ConstantRange>
InRange;
4370 unsigned IndexWidth =
4371 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4372 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4373 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4374 if (InRangeStart.
sge(InRangeEnd))
4375 return error(
ID.Loc,
"expected end to be larger than start");
4381 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4388 return error(
ID.Loc,
"getelementptr index must be an integer");
4389 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4390 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4391 if (GEPWidth && (ValNumEl != GEPWidth))
4394 "getelementptr vector index has a wrong number of elements");
4397 GEPWidth = ValNumEl;
4402 if (!Indices.empty() && !Ty->
isSized(&Visited))
4403 return error(
ID.Loc,
"base element of getelementptr must be sized");
4406 return error(
ID.Loc,
"invalid getelementptr indices");
4410 }
else if (Opc == Instruction::ShuffleVector) {
4411 if (Elts.
size() != 3)
4412 return error(
ID.Loc,
"expected three operands to shufflevector");
4414 return error(
ID.Loc,
"invalid operands to shufflevector");
4418 }
else if (Opc == Instruction::ExtractElement) {
4419 if (Elts.
size() != 2)
4420 return error(
ID.Loc,
"expected two operands to extractelement");
4422 return error(
ID.Loc,
"invalid extractelement operands");
4425 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4426 if (Elts.
size() != 3)
4427 return error(
ID.Loc,
"expected three operands to insertelement");
4429 return error(
ID.Loc,
"invalid insertelement operands");
4448 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4449 convertValIDToValue(Ty,
ID, V,
nullptr);
4450 if (V && !(
C = dyn_cast<Constant>(V)))
4451 return error(
ID.Loc,
"global values must be constants");
4455bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4457 return parseType(Ty) || parseGlobalValue(Ty, V);
4469 return tokError(
"expected comdat variable");
4472 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4475 if (GlobalName.
empty())
4476 return tokError(
"comdat cannot be unnamed");
4477 C = getComdat(std::string(GlobalName), KwLoc);
4500 if (parseGlobalTypeAndValue(
C))
4508bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4510 if (parseMDNodeVector(Elts))
4521bool LLParser::parseMDNode(
MDNode *&
N) {
4523 return parseSpecializedMDNode(
N);
4525 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4528bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4531 return parseMDTuple(
N);
4534 return parseMDNodeID(
N);
4540template <
class FieldTy>
struct MDFieldImpl {
4541 typedef MDFieldImpl ImplTy;
4545 void assign(FieldTy Val) {
4547 this->Val = std::move(Val);
4550 explicit MDFieldImpl(FieldTy
Default)
4558template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4559 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4570 void assign(FieldTypeA
A) {
4572 this->A = std::move(
A);
4576 void assign(FieldTypeB
B) {
4578 this->B = std::move(
B);
4582 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4584 WhatIs(IsInvalid) {}
4587struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4594struct LineField :
public MDUnsignedField {
4595 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4598struct ColumnField :
public MDUnsignedField {
4599 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4602struct DwarfTagField :
public MDUnsignedField {
4608struct DwarfMacinfoTypeField :
public MDUnsignedField {
4614struct DwarfAttEncodingField :
public MDUnsignedField {
4615 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4618struct DwarfVirtualityField :
public MDUnsignedField {
4622struct DwarfLangField :
public MDUnsignedField {
4626struct DwarfCCField :
public MDUnsignedField {
4627 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4630struct EmissionKindField :
public MDUnsignedField {
4631 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4634struct NameTableKindField :
public MDUnsignedField {
4635 NameTableKindField()
4638 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4641struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4642 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4645struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4646 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4649struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4650 MDAPSIntField() : ImplTy(
APSInt()) {}
4653struct MDSignedField :
public MDFieldImpl<int64_t> {
4657 MDSignedField(int64_t
Default = 0)
4659 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4663struct MDBoolField :
public MDFieldImpl<bool> {
4667struct MDField :
public MDFieldImpl<Metadata *> {
4670 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4673struct MDStringField :
public MDFieldImpl<MDString *> {
4675 MDStringField(
bool AllowEmpty =
true)
4676 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4679struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4683struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4687struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4688 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4689 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4691 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4692 bool AllowNull =
true)
4693 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4695 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4696 bool isMDField()
const {
return WhatIs == IsTypeB; }
4697 int64_t getMDSignedValue()
const {
4698 assert(isMDSignedField() &&
"Wrong field type");
4701 Metadata *getMDFieldValue()
const {
4702 assert(isMDField() &&
"Wrong field type");
4714 return tokError(
"expected integer");
4723 MDUnsignedField &Result) {
4725 return tokError(
"expected unsigned integer");
4728 if (U.ugt(Result.Max))
4729 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4731 Result.assign(U.getZExtValue());
4732 assert(Result.Val <= Result.Max &&
"Expected value in range");
4739 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4743 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4749 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4752 return tokError(
"expected DWARF tag");
4756 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4757 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4766 DwarfMacinfoTypeField &Result) {
4768 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4771 return tokError(
"expected DWARF macinfo type");
4775 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4777 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4779 Result.assign(Macinfo);
4786 DwarfVirtualityField &Result) {
4788 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4791 return tokError(
"expected DWARF virtuality code");
4795 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4797 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4798 Result.assign(Virtuality);
4806 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4809 return tokError(
"expected DWARF language");
4813 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4815 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4816 Result.assign(Lang);
4824 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4827 return tokError(
"expected DWARF calling convention");
4831 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4833 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4841 EmissionKindField &Result) {
4843 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4846 return tokError(
"expected emission kind");
4850 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4852 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4853 Result.assign(*Kind);
4860 NameTableKindField &Result) {
4862 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4865 return tokError(
"expected nameTable kind");
4869 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4871 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4872 Result.assign((
unsigned)*Kind);