62 "Allow incomplete IR on a best effort basis (references to unknown "
63 "metadata will be dropped)"));
79 M->setIsNewDbgInfoFormat(
false);
92 "Can't read textual IR with a Context that discards named Values");
95 if (parseTargetDefinitions(DataLayoutCallback))
105 restoreParsingState(Slots);
109 if (parseType(Ty) || parseConstantValue(Ty,
C))
112 return error(Lex.
getLoc(),
"expected end of string");
118 restoreParsingState(Slots);
127 Read =
End.getPointer() - Start.getPointer();
132void LLParser::restoreParsingState(
const SlotMapping *Slots) {
139 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
140 for (
const auto &
I : Slots->
Types)
141 NumberedTypes.insert(
142 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
147 if (!isa<DbgInfoIntrinsic>(II) &&
148 II->
getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
153 if (
auto *MV = dyn_cast<MetadataAsValue>(V))
154 if (
auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
155 if (MD->isTemporary())
169void LLParser::dropUnknownMetadataReferences() {
170 auto Pred = [](
unsigned MDKind,
MDNode *
Node) {
return Node->isTemporary(); };
172 F.eraseMetadataIf(Pred);
174 I.eraseMetadataIf(Pred);
176 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
182 GV.eraseMetadataIf(Pred);
187 if (
Info.first->getNumTemporaryUses() == 1) {
188 NumberedMetadata.erase(
ID);
189 ForwardRefMDNodes.erase(
ID);
200 for (
const auto &RAG : ForwardRefAttrGroups) {
202 const std::vector<unsigned> &
Attrs = RAG.second;
205 for (
const auto &Attr : Attrs) {
206 auto R = NumberedAttrBuilders.find(Attr);
207 if (R != NumberedAttrBuilders.end())
211 if (
Function *Fn = dyn_cast<Function>(V)) {
221 Fn->setAlignment(*
A);
226 Fn->setAttributes(AS);
227 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
233 CI->setAttributes(AS);
234 }
else if (
InvokeInst *II = dyn_cast<InvokeInst>(V)) {
240 II->setAttributes(AS);
241 }
else if (
CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
247 CBI->setAttributes(AS);
248 }
else if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
259 if (!ForwardRefBlockAddresses.empty())
260 return error(ForwardRefBlockAddresses.begin()->first.Loc,
261 "expected function name in blockaddress");
263 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
267 GV =
M->getNamedValue(GVRef.
StrVal);
269 GV = NumberedVals.get(GVRef.
UIntVal);
274 "' referenced by dso_local_equivalent");
278 "expected a function, alias to function, or ifunc "
279 "in dso_local_equivalent");
282 FwdRef->replaceAllUsesWith(Equiv);
283 FwdRef->eraseFromParent();
290 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
291 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
294 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
295 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
298 ForwardRefDSOLocalEquivalentIDs.clear();
299 ForwardRefDSOLocalEquivalentNames.clear();
301 for (
const auto &NT : NumberedTypes)
302 if (
NT.second.second.isValid())
304 "use of undefined type '%" +
Twine(
NT.first) +
"'");
306 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
307 NamedTypes.begin(), E = NamedTypes.end();
I != E; ++
I)
308 if (
I->second.second.isValid())
309 return error(
I->second.second,
310 "use of undefined type named '" +
I->getKey() +
"'");
312 if (!ForwardRefComdats.empty())
313 return error(ForwardRefComdats.begin()->second,
314 "use of undefined comdat '$" +
315 ForwardRefComdats.begin()->first +
"'");
320 for (
Use &U :
V->uses()) {
321 auto *CB = dyn_cast<CallBase>(
U.getUser());
322 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
324 FTy = CB->getFunctionType();
333 if (
Name.starts_with(
"llvm."))
336 return GetCommonFunctionType(V);
342 if (
auto *Ty = GetCommonFunctionType(V))
353 if (
auto *FTy = dyn_cast<FunctionType>(Ty))
359 Info.first->replaceAllUsesWith(GV);
360 Info.first->eraseFromParent();
361 ForwardRefVals.erase(
Name);
365 if (!ForwardRefVals.empty())
366 return error(ForwardRefVals.begin()->second.second,
367 "use of undefined value '@" + ForwardRefVals.begin()->first +
370 if (!ForwardRefValIDs.empty())
371 return error(ForwardRefValIDs.begin()->second.second,
372 "use of undefined value '@" +
373 Twine(ForwardRefValIDs.begin()->first) +
"'");
376 dropUnknownMetadataReferences();
378 if (!ForwardRefMDNodes.empty())
379 return error(ForwardRefMDNodes.begin()->second.second,
380 "use of undefined metadata '!" +
381 Twine(ForwardRefMDNodes.begin()->first) +
"'");
384 for (
auto &
N : NumberedMetadata) {
385 if (
N.second && !
N.second->isResolved())
386 N.second->resolveCycles();
389 for (
auto *Inst : InstsWithTBAATag) {
390 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
393 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
396 if (MD != UpgradedMD)
397 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
406 if (UpgradeDebugInfo)
419 for (
const auto &
I : NamedTypes)
420 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
421 for (
const auto &
I : NumberedTypes)
422 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
428bool LLParser::validateEndOfIndex() {
432 if (!ForwardRefValueInfos.empty())
433 return error(ForwardRefValueInfos.begin()->second.front().second,
434 "use of undefined summary '^" +
435 Twine(ForwardRefValueInfos.begin()->first) +
"'");
437 if (!ForwardRefAliasees.empty())
438 return error(ForwardRefAliasees.begin()->second.front().second,
439 "use of undefined summary '^" +
440 Twine(ForwardRefAliasees.begin()->first) +
"'");
442 if (!ForwardRefTypeIds.empty())
443 return error(ForwardRefTypeIds.begin()->second.front().second,
444 "use of undefined type id summary '^" +
445 Twine(ForwardRefTypeIds.begin()->first) +
"'");
459 std::string TentativeDLStr =
M->getDataLayoutStr();
466 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
470 if (parseSourceFileName())
479 if (
auto LayoutOverride =
480 DataLayoutCallback(
M->getTargetTriple(), TentativeDLStr)) {
481 TentativeDLStr = *LayoutOverride;
487 M->setDataLayout(MaybeDL.
get());
491bool LLParser::parseTopLevelEntities() {
499 if (parseSummaryEntry())
503 if (parseSourceFileName())
515 return tokError(
"expected top-level entity");
526 if (parseModuleAsm())
530 if (parseUnnamedType())
534 if (parseNamedType())
538 if (parseUnnamedGlobal())
542 if (parseNamedGlobal())
547 if (parseStandaloneMetadata())
551 if (parseSummaryEntry())
555 if (parseNamedMetadata())
559 if (parseUnnamedAttrGrp())
563 if (parseUseListOrder())
567 if (parseUseListOrderBB())
576bool LLParser::parseModuleAsm() {
582 parseStringConstant(AsmStr))
585 M->appendModuleInlineAsm(AsmStr);
592bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
598 return tokError(
"unknown target property");
601 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
602 parseStringConstant(Str))
604 M->setTargetTriple(Str);
608 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
611 if (parseStringConstant(TentativeDLStr))
619bool LLParser::parseSourceFileName() {
622 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
623 parseStringConstant(SourceFileName))
626 M->setSourceFileName(SourceFileName);
632bool LLParser::parseUnnamedType() {
637 if (parseToken(
lltok::equal,
"expected '=' after name") ||
642 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
645 if (!isa<StructType>(Result)) {
646 std::pair<Type*, LocTy> &Entry = NumberedTypes[
TypeID];
648 return error(TypeLoc,
"non-struct types may not be recursive");
650 Entry.second =
SMLoc();
658bool LLParser::parseNamedType() {
663 if (parseToken(
lltok::equal,
"expected '=' after name") ||
668 if (parseStructDefinition(NameLoc,
Name, NamedTypes[
Name], Result))
671 if (!isa<StructType>(Result)) {
672 std::pair<Type*, LocTy> &Entry = NamedTypes[
Name];
674 return error(NameLoc,
"non-struct types may not be recursive");
676 Entry.second =
SMLoc();
684bool LLParser::parseDeclare() {
688 std::vector<std::pair<unsigned, MDNode *>> MDs;
692 if (parseMetadataAttachment(MDK,
N))
694 MDs.push_back({MDK,
N});
698 unsigned FunctionNumber = -1;
700 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
703 F->addMetadata(MD.first, *MD.second);
709bool LLParser::parseDefine() {
714 unsigned FunctionNumber = -1;
716 return parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
717 parseOptionalFunctionMetadata(*
F) ||
718 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
724bool LLParser::parseGlobalType(
bool &IsConstant) {
731 return tokError(
"expected 'global' or 'constant'");
737bool LLParser::parseOptionalUnnamedAddr(
758bool LLParser::parseUnnamedGlobal() {
766 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(), VarID))
770 if (parseToken(
lltok::equal,
"expected '=' after name"))
773 VarID = NumberedVals.getNext();
777 unsigned Linkage, Visibility, DLLStorageClass;
781 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
783 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
788 return parseGlobal(
Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
789 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
792 return parseAliasOrIFunc(
Name, VarID, NameLoc, Linkage, Visibility,
793 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
802bool LLParser::parseNamedGlobal() {
809 unsigned Linkage, Visibility, DLLStorageClass;
813 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
814 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
816 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
821 return parseGlobal(
Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
822 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
825 return parseAliasOrIFunc(
Name, -1, NameLoc, Linkage, Visibility,
826 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
830bool LLParser::parseComdat() {
840 return tokError(
"expected comdat type");
845 return tokError(
"unknown selection kind");
867 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(
Name))
868 return error(NameLoc,
"redefinition of comdat '$" +
Name +
"'");
871 if (
I != ComdatSymTab.
end())
874 C =
M->getOrInsertComdat(
Name);
875 C->setSelectionKind(SK);
882bool LLParser::parseMDString(
MDString *&Result) {
884 if (parseStringConstant(Str))
892bool LLParser::parseMDNodeID(
MDNode *&Result) {
896 if (parseUInt32(MID))
900 if (NumberedMetadata.count(MID)) {
901 Result = NumberedMetadata[MID];
906 auto &FwdRef = ForwardRefMDNodes[MID];
909 Result = FwdRef.first.get();
910 NumberedMetadata[MID].reset(Result);
916bool LLParser::parseNamedMetadata() {
935 if (parseDIExpression(
N,
false))
941 return tokError(
"found DIArgList outside of function");
949 return parseToken(
lltok::rbrace,
"expected end of metadata node");
954bool LLParser::parseStandaloneMetadata() {
957 unsigned MetadataID = 0;
960 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
965 return tokError(
"unexpected type in metadata definition");
969 if (parseSpecializedMDNode(
Init, IsDistinct))
972 parseMDTuple(
Init, IsDistinct))
976 auto FI = ForwardRefMDNodes.find(MetadataID);
977 if (FI != ForwardRefMDNodes.end()) {
978 auto *ToReplace = FI->second.first.get();
981 if (isa<DIAssignID>(
Init)) {
982 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
983 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
984 "Inst unexpectedly already has DIAssignID attachment");
985 Inst->setMetadata(LLVMContext::MD_DIAssignID,
Init);
989 ToReplace->replaceAllUsesWith(
Init);
990 ForwardRefMDNodes.erase(FI);
992 assert(NumberedMetadata[MetadataID] ==
Init &&
"Tracking VH didn't work");
994 if (NumberedMetadata.count(MetadataID))
995 return tokError(
"Metadata id is already used");
996 NumberedMetadata[MetadataID].reset(
Init);
1003bool LLParser::skipModuleSummaryEntry() {
1013 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1014 "start of summary entry");
1016 return parseSummaryIndexFlags();
1018 return parseBlockCount();
1020 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1021 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1025 unsigned NumOpenParen = 1;
1035 return tokError(
"found end of file while parsing summary entry");
1041 }
while (NumOpenParen > 0);
1047bool LLParser::parseSummaryEntry() {
1061 return skipModuleSummaryEntry();
1063 bool result =
false;
1066 result = parseGVEntry(SummaryID);
1069 result = parseModuleEntry(SummaryID);
1072 result = parseTypeIdEntry(SummaryID);
1075 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1078 result = parseSummaryIndexFlags();
1081 result = parseBlockCount();
1084 result =
error(Lex.
getLoc(),
"unexpected summary kind");
1121bool LLParser::parseAliasOrIFunc(
const std::string &
Name,
unsigned NameID,
1122 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1123 unsigned DLLStorageClass,
bool DSOLocal,
1138 return error(NameLoc,
"invalid linkage type for alias");
1141 return error(NameLoc,
1142 "symbol with local linkage must have default visibility");
1145 return error(NameLoc,
1146 "symbol with local linkage cannot have a DLL storage class");
1150 if (parseType(Ty) ||
1151 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1160 if (parseGlobalTypeAndValue(Aliasee))
1165 if (parseValID(
ID,
nullptr))
1168 return error(AliaseeLoc,
"invalid aliasee");
1169 Aliasee =
ID.ConstantVal;
1173 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1175 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1176 unsigned AddrSpace = PTy->getAddressSpace();
1182 if (!
Name.empty()) {
1183 auto I = ForwardRefVals.find(
Name);
1184 if (
I != ForwardRefVals.end()) {
1185 GVal =
I->second.first;
1186 ForwardRefVals.erase(
Name);
1187 }
else if (
M->getNamedValue(
Name)) {
1188 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1191 auto I = ForwardRefValIDs.find(NameID);
1192 if (
I != ForwardRefValIDs.end()) {
1193 GVal =
I->second.first;
1194 ForwardRefValIDs.erase(
I);
1199 std::unique_ptr<GlobalAlias> GA;
1200 std::unique_ptr<GlobalIFunc> GI;
1230 return tokError(
"unknown alias or ifunc property!");
1235 NumberedVals.add(NameID, GV);
1242 "forward reference and definition of alias have different types");
1252 M->insertAlias(GA.release());
1254 M->insertIFunc(GI.release());
1264 case lltok::kw_sanitize_memtag:
1280 Meta.NoAddress =
true;
1283 Meta.NoHWAddress =
true;
1285 case lltok::kw_sanitize_memtag:
1289 Meta.IsDynInit =
true;
1292 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1312bool LLParser::parseGlobal(
const std::string &
Name,
unsigned NameID,
1313 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1314 unsigned Visibility,
unsigned DLLStorageClass,
1318 return error(NameLoc,
1319 "symbol with local linkage must have default visibility");
1322 return error(NameLoc,
1323 "symbol with local linkage cannot have a DLL storage class");
1327 LocTy IsExternallyInitializedLoc;
1331 if (parseOptionalAddrSpace(AddrSpace) ||
1333 IsExternallyInitialized,
1334 &IsExternallyInitializedLoc) ||
1335 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1344 if (parseGlobalValue(Ty,
Init))
1349 return error(TyLoc,
"invalid type for global variable");
1354 if (!
Name.empty()) {
1355 auto I = ForwardRefVals.find(
Name);
1356 if (
I != ForwardRefVals.end()) {
1357 GVal =
I->second.first;
1358 ForwardRefVals.erase(
I);
1359 }
else if (
M->getNamedValue(
Name)) {
1360 return error(NameLoc,
"redefinition of global '@" +
Name +
"'");
1365 if (NameID == (
unsigned)-1)
1366 NameID = NumberedVals.getNext();
1368 auto I = ForwardRefValIDs.find(NameID);
1369 if (
I != ForwardRefValIDs.end()) {
1370 GVal =
I->second.first;
1371 ForwardRefValIDs.erase(
I);
1380 NumberedVals.add(NameID, GV);
1398 "forward reference and definition of global have different types");
1418 }
else if (Lex.
getKind() == lltok::kw_align) {
1420 if (parseOptionalAlignment(Alignment))
1426 if (parseOptionalCodeModel(CodeModel))
1430 if (parseGlobalObjectMetadataAttachment(*GV))
1433 if (parseSanitizer(GV))
1437 if (parseOptionalComdat(
Name,
C))
1442 return tokError(
"unknown global variable property!");
1448 std::vector<unsigned> FwdRefAttrGrps;
1449 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1451 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1453 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1461bool LLParser::parseUnnamedAttrGrp() {
1467 return tokError(
"expected attribute group id");
1470 std::vector<unsigned> unused;
1478 auto R = NumberedAttrBuilders.find(VarID);
1479 if (R == NumberedAttrBuilders.end())
1480 R = NumberedAttrBuilders.emplace(VarID,
AttrBuilder(
M->getContext())).first;
1482 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1483 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1486 if (!
R->second.hasAttributes())
1487 return error(AttrGrpLoc,
"attribute group has no attributes");
1494#define GET_ATTR_NAMES
1495#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1496 case lltok::kw_##DISPLAY_NAME: \
1497 return Attribute::ENUM_NAME;
1498#include "llvm/IR/Attributes.inc"
1507 return parseRequiredTypeAttr(
B, Lex.
getKind(), Attr);
1510 case Attribute::Alignment: {
1519 if (parseOptionalAlignment(Alignment,
true))
1522 B.addAlignmentAttr(Alignment);
1525 case Attribute::StackAlignment: {
1530 parseUInt32(Alignment))
1533 if (parseOptionalStackAlignment(Alignment))
1536 B.addStackAlignmentAttr(Alignment);
1539 case Attribute::AllocSize: {
1540 unsigned ElemSizeArg;
1541 std::optional<unsigned> NumElemsArg;
1542 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1544 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1547 case Attribute::VScaleRange: {
1548 unsigned MinValue, MaxValue;
1549 if (parseVScaleRangeArguments(MinValue, MaxValue))
1551 B.addVScaleRangeAttr(MinValue,
1552 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1555 case Attribute::Dereferenceable: {
1557 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1559 B.addDereferenceableAttr(Bytes);
1562 case Attribute::DereferenceableOrNull: {
1564 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1566 B.addDereferenceableOrNullAttr(Bytes);
1569 case Attribute::UWTable: {
1571 if (parseOptionalUWTableKind(Kind))
1573 B.addUWTableAttr(Kind);
1576 case Attribute::AllocKind: {
1578 if (parseAllocKind(Kind))
1580 B.addAllocKindAttr(Kind);
1583 case Attribute::Memory: {
1584 std::optional<MemoryEffects> ME = parseMemoryAttr();
1587 B.addMemoryAttr(*ME);
1590 case Attribute::NoFPClass: {
1593 B.addNoFPClassAttr(NoFPClass);
1599 case Attribute::Range:
1600 return parseRangeAttr(
B);
1602 B.addAttribute(Attr);
1610 case lltok::kw_readnone:
1613 case lltok::kw_readonly:
1616 case lltok::kw_writeonly:
1635bool LLParser::parseFnAttributeValuePairs(
AttrBuilder &
B,
1636 std::vector<unsigned> &FwdRefAttrGrps,
1637 bool InAttrGrp, LocTy &BuiltinLoc) {
1638 bool HaveError =
false;
1649 if (parseStringAttribute(
B))
1661 "cannot have an attribute group reference in an attribute group");
1671 if (Token == lltok::kw_builtin)
1683 return error(Lex.
getLoc(),
"unterminated attribute group");
1686 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1693 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1697 B.addMemoryAttr(ME);
1711 PTy->getAddressSpace());
1720 error(Loc,
"'" +
Name +
"' is not a basic block");
1722 error(Loc,
"'" +
Name +
"' defined with type '" +
1735 error(Loc,
"global variable reference must have pointer type");
1741 cast_or_null<GlobalValue>(
M->getValueSymbolTable().lookup(
Name));
1746 auto I = ForwardRefVals.find(
Name);
1747 if (
I != ForwardRefVals.end())
1748 Val =
I->second.first;
1753 return cast_or_null<GlobalValue>(
1754 checkValidVariableType(Loc,
"@" +
Name, Ty, Val));
1758 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1765 error(Loc,
"global variable reference must have pointer type");
1774 auto I = ForwardRefValIDs.find(
ID);
1775 if (
I != ForwardRefValIDs.end())
1776 Val =
I->second.first;
1781 return cast_or_null<GlobalValue>(
1782 checkValidVariableType(Loc,
"@" +
Twine(
ID), Ty, Val));
1786 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1794Comdat *LLParser::getComdat(
const std::string &
Name, LocTy Loc) {
1798 if (
I != ComdatSymTab.
end())
1803 ForwardRefComdats[
Name] = Loc;
1813bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1815 return tokError(ErrMsg);
1822bool LLParser::parseStringConstant(std::string &Result) {
1824 return tokError(
"expected string constant");
1832bool LLParser::parseUInt32(
uint32_t &Val) {
1834 return tokError(
"expected integer");
1836 if (Val64 !=
unsigned(Val64))
1837 return tokError(
"expected 32-bit integer (too large)");
1845bool LLParser::parseUInt64(
uint64_t &Val) {
1847 return tokError(
"expected integer");
1860 return tokError(
"expected localdynamic, initialexec or localexec");
1888 return parseTLSModel(TLM) ||
1889 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1897bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1898 AddrSpace = DefaultAS;
1902 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1905 if (AddrSpaceStr ==
"A") {
1906 AddrSpace =
M->getDataLayout().getAllocaAddrSpace();
1907 }
else if (AddrSpaceStr ==
"G") {
1908 AddrSpace =
M->getDataLayout().getDefaultGlobalsAddressSpace();
1909 }
else if (AddrSpaceStr ==
"P") {
1910 AddrSpace =
M->getDataLayout().getProgramAddressSpace();
1912 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
1918 return tokError(
"expected integer or string constant");
1920 if (parseUInt32(AddrSpace))
1922 if (!isUInt<24>(AddrSpace))
1923 return error(Loc,
"invalid address space, must be a 24-bit integer");
1927 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
1928 ParseAddrspaceValue(AddrSpace) ||
1939 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
1941 B.addAttribute(Attr, Val);
1946bool LLParser::parseOptionalParamOrReturnAttrs(
AttrBuilder &
B,
bool IsParam) {
1947 bool HaveError =
false;
1954 if (parseStringAttribute(
B))
1964 if (parseEnumAttribute(Attr,
B,
false))
1968 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
1970 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2018bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2019 unsigned &Visibility,
2020 unsigned &DLLStorageClass,
bool &DSOLocal) {
2024 parseOptionalDSOLocal(DSOLocal);
2025 parseOptionalVisibility(Visibility);
2026 parseOptionalDLLStorageClass(DLLStorageClass);
2029 return error(Lex.
getLoc(),
"dso_location and DLL-StorageClass mismatch");
2035void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2057void LLParser::parseOptionalVisibility(
unsigned &Res) {
2080void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2148bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2218 return parseUInt32(
CC);
2228bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2235 return parseMDNode(MD);
2240bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2243 return tokError(
"expected metadata after comma");
2247 if (parseMetadataAttachment(MDK,
N))
2250 if (MDK == LLVMContext::MD_DIAssignID)
2251 TempDIAssignIDAttachments[
N].push_back(&Inst);
2255 if (MDK == LLVMContext::MD_tbaa)
2256 InstsWithTBAATag.push_back(&Inst);
2265bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2268 if (parseMetadataAttachment(MDK,
N))
2277bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2279 if (parseGlobalObjectMetadataAttachment(
F))
2287bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2288 Alignment = std::nullopt;
2289 if (!EatIfPresent(lltok::kw_align))
2295 bool HaveParens =
false;
2301 if (parseUInt64(
Value))
2305 return error(ParenLoc,
"expected ')'");
2308 return error(AlignLoc,
"alignment is not a power of two");
2310 return error(AlignLoc,
"huge alignments are not supported yet");
2321 auto ErrMsg =
"expected global code model string";
2322 if (StrVal ==
"tiny")
2324 else if (StrVal ==
"small")
2326 else if (StrVal ==
"kernel")
2328 else if (StrVal ==
"medium")
2330 else if (StrVal ==
"large")
2333 return tokError(ErrMsg);
2344bool LLParser::parseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
2346 assert((AttrKind == lltok::kw_dereferenceable ||
2347 AttrKind == lltok::kw_dereferenceable_or_null) &&
2351 if (!EatIfPresent(AttrKind))
2355 return error(ParenLoc,
"expected '('");
2357 if (parseUInt64(Bytes))
2361 return error(ParenLoc,
"expected ')'");
2363 return error(DerefLoc,
"dereferenceable bytes must be non-zero");
2367bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2378 return error(KindLoc,
"expected unwind table kind");
2387 return error(ParenLoc,
"expected '('");
2390 if (parseStringConstant(Arg))
2391 return error(KindLoc,
"expected allockind value");
2395 }
else if (
A ==
"realloc") {
2397 }
else if (
A ==
"free") {
2399 }
else if (
A ==
"uninitialized") {
2401 }
else if (
A ==
"zeroed") {
2403 }
else if (
A ==
"aligned") {
2406 return error(KindLoc,
Twine(
"unknown allockind ") +
A);
2411 return error(ParenLoc,
"expected ')'");
2413 return error(KindLoc,
"expected allockind value");
2424 return std::nullopt;
2439 return std::nullopt;
2443std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2453 tokError(
"expected '('");
2454 return std::nullopt;
2457 bool SeenLoc =
false;
2463 tokError(
"expected ':' after location");
2464 return std::nullopt;
2471 tokError(
"expected memory location (argmem, inaccessiblemem) "
2472 "or access kind (none, read, write, readwrite)");
2474 tokError(
"expected access kind (none, read, write, readwrite)");
2475 return std::nullopt;
2484 tokError(
"default access kind must be specified first");
2485 return std::nullopt;
2494 tokError(
"unterminated memory attribute");
2495 return std::nullopt;
2537unsigned LLParser::parseNoFPClassAttr() {
2542 tokError(
"expected '('");
2549 if (TestMask != 0) {
2553 !parseUInt64(
Value)) {
2555 error(Lex.
getLoc(),
"invalid mask value for 'nofpclass'");
2566 error(Lex.
getLoc(),
"expected nofpclass test mask");
2584bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2585 bool &AteExtraComma) {
2586 AteExtraComma =
false;
2590 AteExtraComma =
true;
2594 if (Lex.
getKind() != lltok::kw_align)
2595 return error(Lex.
getLoc(),
"expected metadata or 'align'");
2597 if (parseOptionalAlignment(Alignment))
2610bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &Loc,
2611 bool &AteExtraComma) {
2612 AteExtraComma =
false;
2616 AteExtraComma =
true;
2622 return error(Lex.
getLoc(),
"expected metadata or 'addrspace'");
2624 if (parseOptionalAddrSpace(AddrSpace))
2631bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2632 std::optional<unsigned> &HowManyArg) {
2635 auto StartParen = Lex.
getLoc();
2637 return error(StartParen,
"expected '('");
2639 if (parseUInt32(BaseSizeArg))
2643 auto HowManyAt = Lex.
getLoc();
2645 if (parseUInt32(HowMany))
2647 if (HowMany == BaseSizeArg)
2648 return error(HowManyAt,
2649 "'allocsize' indices can't refer to the same parameter");
2650 HowManyArg = HowMany;
2652 HowManyArg = std::nullopt;
2654 auto EndParen = Lex.
getLoc();
2656 return error(EndParen,
"expected ')'");
2660bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2661 unsigned &MaxValue) {
2664 auto StartParen = Lex.
getLoc();
2666 return error(StartParen,
"expected '('");
2668 if (parseUInt32(MinValue))
2672 if (parseUInt32(MaxValue))
2675 MaxValue = MinValue;
2677 auto EndParen = Lex.
getLoc();
2679 return error(EndParen,
"expected ')'");
2688bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
2693 return parseScope(SSID) || parseOrdering(Ordering);
2703 auto StartParenAt = Lex.
getLoc();
2705 return error(StartParenAt,
"Expected '(' in syncscope");
2708 auto SSNAt = Lex.
getLoc();
2709 if (parseStringConstant(SSN))
2710 return error(SSNAt,
"Expected synchronization scope name");
2712 auto EndParenAt = Lex.
getLoc();
2714 return error(EndParenAt,
"Expected ')' in syncscope");
2729 return tokError(
"Expected ordering on atomic instruction");
2748bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
2750 if (!EatIfPresent(lltok::kw_alignstack))
2754 return error(ParenLoc,
"expected '('");
2756 if (parseUInt32(Alignment))
2760 return error(ParenLoc,
"expected ')'");
2762 return error(AlignLoc,
"stack alignment is not a power of two");
2776 bool &AteExtraComma) {
2777 AteExtraComma =
false;
2780 return tokError(
"expected ',' as start of index list");
2784 if (Indices.
empty())
2785 return tokError(
"expected index");
2786 AteExtraComma =
true;
2790 if (parseUInt32(
Idx))
2803bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
2807 return tokError(Msg);
2816 if (
Result->isPointerTy()) {
2818 if (parseOptionalAddrSpace(AddrSpace))
2824 return tokError(
"ptr* is invalid - use ptr instead");
2835 if (parseTargetExtType(Result))
2841 if (parseAnonStructType(Result,
false))
2847 if (parseArrayVectorType(Result,
false))
2854 if (parseAnonStructType(Result,
true) ||
2855 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2857 }
else if (parseArrayVectorType(Result,
true))
2862 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.
getStrVal()];
2868 Entry.second = Lex.
getLoc();
2877 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.
getUIntVal()];
2883 Entry.second = Lex.
getLoc();
2896 if (!AllowVoid &&
Result->isVoidTy())
2897 return error(TypeLoc,
"void type only allowed for function results");
2903 return tokError(
"basic block pointers are invalid");
2905 return tokError(
"pointers to void are invalid - use i8* instead");
2907 return tokError(
"pointer to this type is invalid");
2915 return tokError(
"basic block pointers are invalid");
2917 return tokError(
"pointers to void are invalid; use i8* instead");
2919 return tokError(
"pointer to this type is invalid");
2921 if (parseOptionalAddrSpace(AddrSpace) ||
2922 parseToken(
lltok::star,
"expected '*' in address space"))
2931 if (parseFunctionType(Result))
2944 PerFunctionState &PFS,
bool IsMustTailCall,
2945 bool InVarArgsFunc) {
2951 if (!ArgList.
empty() &&
2952 parseToken(
lltok::comma,
"expected ',' in argument list"))
2957 const char *
Msg =
"unexpected ellipsis in argument list for ";
2958 if (!IsMustTailCall)
2959 return tokError(
Twine(Msg) +
"non-musttail call");
2961 return tokError(
Twine(Msg) +
"musttail call in non-varargs function");
2963 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
2968 Type *ArgTy =
nullptr;
2970 if (parseType(ArgTy, ArgLoc))
2976 if (parseMetadataAsValue(V, PFS))
2980 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2987 if (IsMustTailCall && InVarArgsFunc)
2988 return tokError(
"expected '...' at end of argument list for musttail call "
2989 "in varargs function");
3000 if (!EatIfPresent(AttrToken))
3009 B.addTypeAttr(AttrKind, Ty);
3025 return tokError(
"expected integer");
3028 "integer is too large for the bit width of specified type");
3034 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3037 return error(TyLoc,
"the range must have integer type!");
3045 return tokError(
"the range should not represent the full or empty set!");
3063bool LLParser::parseOptionalOperandBundles(
3071 if (!BundleList.
empty() &&
3072 parseToken(
lltok::comma,
"expected ',' in input list"))
3076 if (parseStringConstant(
Tag))
3079 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3082 std::vector<Value *> Inputs;
3085 if (!Inputs.empty() &&
3086 parseToken(
lltok::comma,
"expected ',' in input list"))
3090 Value *Input =
nullptr;
3091 if (parseType(Ty) || parseValue(Ty, Input, PFS))
3093 Inputs.push_back(Input);
3101 if (BundleList.
empty())
3102 return error(BeginLoc,
"operand bundle set must not be empty");
3109 unsigned NextID,
unsigned ID)
const {
3111 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3112 Twine(NextID) +
"' or greater");
3129 unsigned CurValID = 0;
3144 Type *ArgTy =
nullptr;
3146 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3150 return error(TypeLoc,
"argument can not have void type");
3160 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3167 CurValID = ArgID + 1;
3171 return error(TypeLoc,
"invalid type for function argument");
3179 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3184bool LLParser::parseFunctionType(
Type *&Result) {
3188 return tokError(
"invalid function return type");
3193 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3197 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
3198 if (!ArgList[i].
Name.empty())
3199 return error(ArgList[i].Loc,
"argument name invalid in function type");
3200 if (ArgList[i].
Attrs.hasAttributes())
3201 return error(ArgList[i].Loc,
3202 "argument attributes invalid in function type");
3206 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
3215bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3217 if (parseStructBody(Elts))
3226 std::pair<Type *, LocTy> &Entry,
3229 if (Entry.first && !Entry.second.isValid())
3230 return error(TypeLoc,
"redefinition of type");
3236 Entry.second =
SMLoc();
3241 ResultTy = Entry.first;
3253 return error(TypeLoc,
"forward references to non-struct type");
3257 return parseArrayVectorType(ResultTy,
true);
3258 return parseType(ResultTy);
3262 Entry.second =
SMLoc();
3268 StructType *STy = cast<StructType>(Entry.first);
3271 if (parseStructBody(Body) ||
3272 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3301 return error(EltTyLoc,
"invalid element type for struct");
3309 return error(EltTyLoc,
"invalid element type for struct");
3314 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3323bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3324 bool Scalable =
false;
3328 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3336 return tokError(
"expected number in address space");
3342 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3346 Type *EltTy =
nullptr;
3347 if (parseType(EltTy))
3351 "expected end of sequential type"))
3356 return error(SizeLoc,
"zero element vector is illegal");
3358 return error(SizeLoc,
"size too large for vector");
3360 return error(TypeLoc,
"invalid vector element type");
3364 return error(TypeLoc,
"invalid array element type");
3381bool LLParser::parseTargetExtType(
Type *&Result) {
3386 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3387 parseStringConstant(TypeName))
3395 bool SeenInt =
false;
3402 if (parseUInt32(IntVal))
3405 }
else if (SeenInt) {
3408 return tokError(
"expected uint32 param");
3411 if (parseType(TypeParam,
true))
3417 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3431 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3434 auto It = UnnamedArgNums.
begin();
3437 unsigned ArgNum = *It++;
3438 NumberedVals.add(ArgNum, &
A);
3443LLParser::PerFunctionState::~PerFunctionState() {
3446 for (
const auto &
P : ForwardRefVals) {
3447 if (isa<BasicBlock>(
P.second.first))
3449 P.second.first->replaceAllUsesWith(
3451 P.second.first->deleteValue();
3454 for (
const auto &
P : ForwardRefValIDs) {
3455 if (isa<BasicBlock>(
P.second.first))
3457 P.second.first->replaceAllUsesWith(
3459 P.second.first->deleteValue();
3463bool LLParser::PerFunctionState::finishFunction() {
3464 if (!ForwardRefVals.empty())
3465 return P.error(ForwardRefVals.begin()->second.second,
3466 "use of undefined value '%" + ForwardRefVals.begin()->first +
3468 if (!ForwardRefValIDs.empty())
3469 return P.error(ForwardRefValIDs.begin()->second.second,
3470 "use of undefined value '%" +
3471 Twine(ForwardRefValIDs.begin()->first) +
"'");
3478Value *LLParser::PerFunctionState::getVal(
const std::string &
Name,
Type *Ty,
3481 Value *Val =
F.getValueSymbolTable()->lookup(
Name);
3486 auto I = ForwardRefVals.find(
Name);
3487 if (
I != ForwardRefVals.end())
3488 Val =
I->second.first;
3493 return P.checkValidVariableType(Loc,
"%" +
Name, Ty, Val);
3497 P.error(Loc,
"invalid use of a non-first-class type");
3509 P.error(Loc,
"name is too long which can result in name collisions, "
3510 "consider making the name shorter or "
3511 "increasing -non-global-value-max-name-size");
3515 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3519Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty, LocTy Loc) {
3521 Value *Val = NumberedVals.get(
ID);
3526 auto I = ForwardRefValIDs.find(
ID);
3527 if (
I != ForwardRefValIDs.end())
3528 Val =
I->second.first;
3533 return P.checkValidVariableType(Loc,
"%" +
Twine(
ID), Ty, Val);
3536 P.error(Loc,
"invalid use of a non-first-class type");
3548 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3554bool LLParser::PerFunctionState::setInstName(
int NameID,
3555 const std::string &NameStr,
3559 if (NameID != -1 || !NameStr.empty())
3560 return P.error(NameLoc,
"instructions returning void cannot have a name");
3566 if (NameStr.empty()) {
3569 NameID = NumberedVals.getNext();
3571 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
3575 auto FI = ForwardRefValIDs.find(NameID);
3576 if (FI != ForwardRefValIDs.end()) {
3579 return P.error(NameLoc,
"instruction forward referenced with type '" +
3583 Sentinel->replaceAllUsesWith(Inst);
3585 ForwardRefValIDs.erase(FI);
3588 NumberedVals.add(NameID, Inst);
3593 auto FI = ForwardRefVals.find(NameStr);
3594 if (FI != ForwardRefVals.end()) {
3597 return P.error(NameLoc,
"instruction forward referenced with type '" +
3601 Sentinel->replaceAllUsesWith(Inst);
3603 ForwardRefVals.erase(FI);
3609 if (Inst->
getName() != NameStr)
3610 return P.error(NameLoc,
"multiple definition of local value named '" +
3617BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &
Name,
3619 return dyn_cast_or_null<BasicBlock>(
3623BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID, LocTy Loc) {
3624 return dyn_cast_or_null<BasicBlock>(
3631BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &
Name,
3632 int NameID, LocTy Loc) {
3636 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
3639 NameID = NumberedVals.getNext();
3641 BB = getBB(NameID, Loc);
3643 P.error(Loc,
"unable to create block numbered '" +
Twine(NameID) +
"'");
3647 BB = getBB(
Name, Loc);
3649 P.error(Loc,
"unable to create block named '" +
Name +
"'");
3660 ForwardRefValIDs.erase(NameID);
3661 NumberedVals.add(NameID, BB);
3664 ForwardRefVals.erase(
Name);
3681bool LLParser::parseValID(
ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
3685 return tokError(
"expected value token");
3728 if (parseGlobalValueVector(Elts) ||
3729 parseToken(
lltok::rbrace,
"expected end of struct constant"))
3732 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3733 ID.UIntVal = Elts.
size();
3734 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3735 Elts.
size() *
sizeof(Elts[0]));
3747 if (parseGlobalValueVector(Elts) ||
3749 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
3753 if (isPackedStruct) {
3754 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
3755 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
3756 Elts.
size() *
sizeof(Elts[0]));
3757 ID.UIntVal = Elts.
size();
3763 return error(
ID.Loc,
"constant vector must not be empty");
3765 if (!Elts[0]->
getType()->isIntegerTy() &&
3766 !Elts[0]->
getType()->isFloatingPointTy() &&
3770 "vector elements must have integer, pointer or floating point type");
3773 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
3775 return error(FirstEltLoc,
"vector element #" +
Twine(i) +
3776 " is not of type '" +
3787 if (parseGlobalValueVector(Elts) ||
3799 if (!Elts[0]->
getType()->isFirstClassType())
3800 return error(FirstEltLoc,
"invalid array element type: " +
3806 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
3808 return error(FirstEltLoc,
"array element #" +
Twine(i) +
3809 " is not of type '" +
3829 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3832 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3835 parseStringConstant(
ID.StrVal) ||
3836 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
3841 (
unsigned(AsmDialect) << 2) | (
unsigned(CanThrow) << 3);
3852 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
3853 parseValID(Fn, PFS) ||
3855 "expected comma in block address expression") ||
3856 parseValID(Label, PFS) ||
3857 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
3861 return error(Fn.
Loc,
"expected function name in blockaddress");
3863 return error(
Label.Loc,
"expected basic block name in blockaddress");
3868 GV = NumberedVals.get(Fn.
UIntVal);
3869 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3870 GV =
M->getNamedValue(Fn.
StrVal);
3875 if (!isa<Function>(GV))
3876 return error(Fn.
Loc,
"expected function name in blockaddress");
3877 F = cast<Function>(GV);
3878 if (
F->isDeclaration())
3879 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
3885 ForwardRefBlockAddresses.insert(std::make_pair(
3887 std::map<ValID, GlobalValue *>()))
3888 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
3897 "type of blockaddress must be a pointer and not '" +
3902 FwdDeclAS = PFS->getFunction().getAddressSpace();
3911 ID.ConstantVal = FwdRef;
3919 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
3921 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
3923 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
3925 return error(
Label.Loc,
"referenced value is not a basic block");
3928 return error(
Label.Loc,
"cannot take address of numeric label after "
3929 "the function is defined");
3930 BB = dyn_cast_or_null<BasicBlock>(
3931 F->getValueSymbolTable()->lookup(
Label.StrVal));
3933 return error(
Label.Loc,
"referenced value is not a basic block");
3947 if (parseValID(Fn, PFS))
3952 "expected global value name in dso_local_equivalent");
3957 GV = NumberedVals.get(Fn.
UIntVal);
3958 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
3959 GV =
M->getNamedValue(Fn.
StrVal);
3965 ? ForwardRefDSOLocalEquivalentIDs
3966 : ForwardRefDSOLocalEquivalentNames;
3967 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn,
nullptr).first->second;
3974 ID.ConstantVal = FwdRef;
3980 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
3981 "in dso_local_equivalent");
3992 if (parseValID(
ID, PFS))
3996 return error(
ID.Loc,
"expected global value name in no_cfi");
4008 Type *DestTy =
nullptr;
4011 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4012 parseGlobalTypeAndValue(SrcVal) ||
4013 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4014 parseType(DestTy) ||
4015 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4018 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4027 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4029 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4031 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4033 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4035 return error(
ID.Loc,
"urem constexprs are no longer supported");
4037 return error(
ID.Loc,
"srem constexprs are no longer supported");
4039 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4041 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4043 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4045 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4047 return error(
ID.Loc,
"frem constexprs are no longer supported");
4049 return error(
ID.Loc,
"and constexprs are no longer supported");
4051 return error(
ID.Loc,
"or constexprs are no longer supported");
4053 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4055 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4057 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4059 return error(
ID.Loc,
"select constexprs are no longer supported");
4061 return error(
ID.Loc,
"zext constexprs are no longer supported");
4063 return error(
ID.Loc,
"sext constexprs are no longer supported");
4065 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4067 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4069 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4071 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4073 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4075 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4081 if (parseCmpPredicate(PredVal, Opc) ||
4082 parseToken(
lltok::lparen,
"expected '(' in compare constantexpr") ||
4083 parseGlobalTypeAndValue(Val0) ||
4084 parseToken(
lltok::comma,
"expected comma in compare constantexpr") ||
4085 parseGlobalTypeAndValue(Val1) ||
4086 parseToken(
lltok::rparen,
"expected ')' in compare constantexpr"))
4090 return error(
ID.Loc,
"compare operands must have the same type");
4094 if (Opc == Instruction::FCmp) {
4096 return error(
ID.Loc,
"fcmp requires floating point operands");
4099 assert(Opc == Instruction::ICmp &&
"Unexpected opcode for CmpInst!");
4102 return error(
ID.Loc,
"icmp requires pointer or integer operands");
4120 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4121 Opc == Instruction::Mul || Opc == Instruction::Shl) {
4130 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4131 parseGlobalTypeAndValue(Val0) ||
4132 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4133 parseGlobalTypeAndValue(Val1) ||
4134 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4137 return error(
ID.Loc,
"operands of constexpr must have same type");
4141 "constexpr requires integer or integer vector operands");
4152 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4155 if (parseGlobalTypeAndValue(
C))
4157 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4171 bool InBounds =
false;
4172 bool HasInRange =
false;
4178 if (Opc == Instruction::GetElementPtr) {
4184 return tokError(
"expected integer");
4190 return tokError(
"expected integer");
4199 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4202 if (Opc == Instruction::GetElementPtr) {
4203 if (parseType(Ty) ||
4204 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4208 if (parseGlobalValueVector(Elts) ||
4212 if (Opc == Instruction::GetElementPtr) {
4213 if (Elts.
size() == 0 ||
4214 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4215 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4218 std::optional<ConstantRange>
InRange;
4220 unsigned IndexWidth =
4221 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4222 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4223 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4224 if (InRangeStart.
sge(InRangeEnd))
4225 return error(
ID.Loc,
"expected end to be larger than start");
4231 ? cast<FixedVectorType>(
BaseType)->getNumElements()
4238 return error(
ID.Loc,
"getelementptr index must be an integer");
4239 if (
auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4240 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4241 if (GEPWidth && (ValNumEl != GEPWidth))
4244 "getelementptr vector index has a wrong number of elements");
4247 GEPWidth = ValNumEl;
4252 if (!Indices.empty() && !Ty->
isSized(&Visited))
4253 return error(
ID.Loc,
"base element of getelementptr must be sized");
4256 return error(
ID.Loc,
"invalid getelementptr indices");
4260 }
else if (Opc == Instruction::ShuffleVector) {
4261 if (Elts.
size() != 3)
4262 return error(
ID.Loc,
"expected three operands to shufflevector");
4264 return error(
ID.Loc,
"invalid operands to shufflevector");
4268 }
else if (Opc == Instruction::ExtractElement) {
4269 if (Elts.
size() != 2)
4270 return error(
ID.Loc,
"expected two operands to extractelement");
4272 return error(
ID.Loc,
"invalid extractelement operands");
4275 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
4276 if (Elts.
size() != 3)
4277 return error(
ID.Loc,
"expected three operands to insertelement");
4279 return error(
ID.Loc,
"invalid insertelement operands");
4298 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4299 convertValIDToValue(Ty,
ID, V,
nullptr);
4300 if (V && !(
C = dyn_cast<Constant>(V)))
4301 return error(
ID.Loc,
"global values must be constants");
4305bool LLParser::parseGlobalTypeAndValue(
Constant *&V) {
4307 return parseType(Ty) || parseGlobalValue(Ty, V);
4319 return tokError(
"expected comdat variable");
4322 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4325 if (GlobalName.
empty())
4326 return tokError(
"comdat cannot be unnamed");
4327 C = getComdat(std::string(GlobalName), KwLoc);
4350 if (parseGlobalTypeAndValue(
C))
4358bool LLParser::parseMDTuple(
MDNode *&MD,
bool IsDistinct) {
4360 if (parseMDNodeVector(Elts))
4371bool LLParser::parseMDNode(
MDNode *&
N) {
4373 return parseSpecializedMDNode(
N);
4375 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4378bool LLParser::parseMDNodeTail(
MDNode *&
N) {
4381 return parseMDTuple(
N);
4384 return parseMDNodeID(
N);
4390template <
class FieldTy>
struct MDFieldImpl {
4391 typedef MDFieldImpl ImplTy;
4395 void assign(FieldTy Val) {
4397 this->Val = std::move(Val);
4400 explicit MDFieldImpl(FieldTy
Default)
4408template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4409 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4420 void assign(FieldTypeA
A) {
4422 this->A = std::move(
A);
4426 void assign(FieldTypeB
B) {
4428 this->B = std::move(
B);
4432 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4434 WhatIs(IsInvalid) {}
4437struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4444struct LineField :
public MDUnsignedField {
4445 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4448struct ColumnField :
public MDUnsignedField {
4449 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4452struct DwarfTagField :
public MDUnsignedField {
4458struct DwarfMacinfoTypeField :
public MDUnsignedField {
4464struct DwarfAttEncodingField :
public MDUnsignedField {
4465 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4468struct DwarfVirtualityField :
public MDUnsignedField {
4472struct DwarfLangField :
public MDUnsignedField {
4476struct DwarfCCField :
public MDUnsignedField {
4477 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
4480struct EmissionKindField :
public MDUnsignedField {
4481 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
4484struct NameTableKindField :
public MDUnsignedField {
4485 NameTableKindField()
4488 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4491struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
4492 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
4495struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
4496 DISPFlagField() : MDFieldImpl(
DISubprogram::SPFlagZero) {}
4499struct MDAPSIntField :
public MDFieldImpl<APSInt> {
4500 MDAPSIntField() : ImplTy(
APSInt()) {}
4503struct MDSignedField :
public MDFieldImpl<int64_t> {
4507 MDSignedField(int64_t
Default = 0)
4509 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
4513struct MDBoolField :
public MDFieldImpl<bool> {
4517struct MDField :
public MDFieldImpl<Metadata *> {
4520 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4523struct MDStringField :
public MDFieldImpl<MDString *> {
4525 MDStringField(
bool AllowEmpty =
true)
4526 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4529struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
4533struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
4537struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4538 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
4539 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
4541 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
4542 bool AllowNull =
true)
4543 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
4545 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
4546 bool isMDField()
const {
return WhatIs == IsTypeB; }
4547 int64_t getMDSignedValue()
const {
4548 assert(isMDSignedField() &&
"Wrong field type");
4551 Metadata *getMDFieldValue()
const {
4552 assert(isMDField() &&
"Wrong field type");
4564 return tokError(
"expected integer");
4573 MDUnsignedField &Result) {
4575 return tokError(
"expected unsigned integer");
4578 if (U.ugt(Result.Max))
4579 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4581 Result.assign(U.getZExtValue());
4582 assert(Result.Val <= Result.Max &&
"Expected value in range");
4589 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4593 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4599 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4602 return tokError(
"expected DWARF tag");
4606 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
4607 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
4616 DwarfMacinfoTypeField &Result) {
4618 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4621 return tokError(
"expected DWARF macinfo type");
4625 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
4627 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
4629 Result.assign(Macinfo);
4636 DwarfVirtualityField &Result) {
4638 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4641 return tokError(
"expected DWARF virtuality code");
4645 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
4647 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
4648 Result.assign(Virtuality);
4656 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4659 return tokError(
"expected DWARF language");
4663 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
4665 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
4666 Result.assign(Lang);
4674 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4677 return tokError(
"expected DWARF calling convention");
4681 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
4683 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
4691 EmissionKindField &Result) {
4693 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4696 return tokError(
"expected emission kind");
4700 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
4702 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
4703 Result.assign(*Kind);
4710 NameTableKindField &Result) {
4712 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4715 return tokError(
"expected nameTable kind");
4719 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.
getStrVal() +
4721 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
4722 Result.assign((
unsigned)*Kind);
4729 DwarfAttEncodingField &Result) {
4731 return parseMDField(Loc,
Name,
static_cast<MDUnsignedField &
>(Result));
4734 return tokError(
"expected DWARF type attribute encoding");
4738 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
4740 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
4741 Result.assign(Encoding);
4757 bool Res = parseUInt32(TempVal);
4763 return tokError(
"expected debug info flag");
4767 return tokError(
Twine(
"invalid debug info flag '") + Lex.
getStrVal() +
4782 Result.assign(Combined);
4797 bool Res = parseUInt32(TempVal);
4803 return tokError(
"expected debug info flag");
4807 return tokError(
Twine(
"invalid subprogram debug info flag '") +
4822 Result.assign(Combined);
4829 return tokError(
"expected signed integer");
4833 return tokError(
"value for '" +
Name +
"' too small, limit is " +
4836 return tokError(
"value for '" +
Name +
"' too large, limit is " +
4838 Result.assign(S.getExtValue());
4839 assert(Result.Val >= Result.Min &&
"Expected value in range");
4840 assert(Result.Val <= Result.Max &&
"Expected value in range");
4849 return tokError(
"expected 'true' or 'false'");
4851 Result.assign(
true);
4854 Result.assign(
false);
4864 if (!Result.AllowNull)
4865 return tokError(
"'" +
Name +
"' cannot be null");
4867 Result.assign(
nullptr);
4872 if (parseMetadata(MD,
nullptr))
4881 MDSignedOrMDField &Result) {
4884 MDSignedField Res = Result.A;
4885 if (!parseMDField(Loc,
Name, Res)) {
4893 MDField Res = Result.B;
4894 if (!parseMDField(Loc,
Name, Res)) {
4906 if (parseStringConstant(S))
4909 if (!Result.AllowEmpty && S.empty())
4910 return error(ValueLoc,
"'" +
Name +
"' cannot be empty");
4912 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
4919 if (parseMDNodeVector(MDs))
4922 Result.assign(std::move(MDs));
4928 ChecksumKindField &Result) {
4929 std::optional<DIFile::ChecksumKind> CSKind =
4933 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.
getStrVal() +
4936 Result.assign(*CSKind);
4943template <
class ParserTy>
4944bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4947 return tokError(
"expected field label here");
4956template <
class ParserTy>
4957bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4964 if (parseMDFieldsImplBody(ParseField))
4967 ClosingLoc = Lex.
getLoc();
4971template <
class FieldTy>
4972bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
4974 return tokError(
"field '" +
Name +
"' cannot be specified more than once");
4978 return parseMDField(Loc,
Name, Result);
4981bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
4984#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4985 if (Lex.getStrVal() == #CLASS) \
4986 return parse##CLASS(N, IsDistinct);
4987#include "llvm/IR/Metadata.def"
4989 return tokError(
"expected metadata type");
4992#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4993#define NOP_FIELD(NAME, TYPE, INIT)
4994#define REQUIRE_FIELD(NAME, TYPE, INIT) \
4996 return error(ClosingLoc, "missing required field '" #NAME "'");
4997#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4998 if (Lex.getStrVal() == #NAME) \
4999 return parseMDField(#NAME, NAME);
5000#define PARSE_MD_FIELDS() \
5001 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5004 if (parseMDFieldsImpl( \
5006 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5007 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5012 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5014#define GET_OR_DISTINCT(CLASS, ARGS) \
5015 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5020bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5021#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5022 OPTIONAL(line, LineField, ); \
5023 OPTIONAL(column, ColumnField, ); \
5024 REQUIRED(scope, MDField, ( false)); \
5025 OPTIONAL(inlinedAt, MDField, ); \
5026 OPTIONAL(isImplicitCode, MDBoolField, (false));
5028#undef VISIT_MD_FIELDS
5032 inlinedAt.Val, isImplicitCode.Val));
5038bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5040 return Lex.
Error(
"missing 'distinct', required for !DIAssignID()");
5056bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5057#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5058 REQUIRED(tag, DwarfTagField, ); \
5059 OPTIONAL(header, MDStringField, ); \
5060 OPTIONAL(operands, MDFieldList, );
5062#undef VISIT_MD_FIELDS
5065 (Context, tag.Val, header.Val, operands.Val));
5073bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5074#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5075 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5076 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5077 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5078 OPTIONAL(stride, MDSignedOrMDField, );
5080#undef VISIT_MD_FIELDS
5087 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5088 if (Bound.isMDSignedField())
5091 if (Bound.isMDField())
5092 return Bound.getMDFieldValue();
5096 Count = convToMetadata(
count);
5097 LowerBound = convToMetadata(lowerBound);
5099 Stride = convToMetadata(stride);
5102 (Context, Count, LowerBound, UpperBound, Stride));
5110bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5111#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5112 OPTIONAL(count, MDSignedOrMDField, ); \
5113 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5114 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5115 OPTIONAL(stride, MDSignedOrMDField, );
5117#undef VISIT_MD_FIELDS
5119 auto ConvToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5120 if (Bound.isMDSignedField())
5122 Context, {dwarf::DW_OP_consts,
5123 static_cast<uint64_t>(Bound.getMDSignedValue())});
5124 if (Bound.isMDField())
5125 return Bound.getMDFieldValue();
5130 Metadata *LowerBound = ConvToMetadata(lowerBound);
5132 Metadata *Stride = ConvToMetadata(stride);
5135 (Context, Count, LowerBound, UpperBound, Stride));
5142bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5143#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5144 REQUIRED(name, MDStringField, ); \
5145 REQUIRED(value, MDAPSIntField, ); \
5146 OPTIONAL(isUnsigned, MDBoolField, (false));
5148#undef VISIT_MD_FIELDS
5150 if (isUnsigned.Val &&
value.Val.isNegative())
5151 return tokError(
"unsigned enumerator with negative value");
5156 if (!isUnsigned.Val &&
value.Val.isUnsigned() &&
value.Val.isSignBitSet())
5168bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5169#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5170 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5171 OPTIONAL(name, MDStringField, ); \
5172 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5173 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5174 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5175 OPTIONAL(flags, DIFlagField, );
5177#undef VISIT_MD_FIELDS
5180 align.Val, encoding.Val, flags.Val));
5186bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5187#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5188 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5189 OPTIONAL(name, MDStringField, ); \
5190 OPTIONAL(stringLength, MDField, ); \
5191 OPTIONAL(stringLengthExpression, MDField, ); \
5192 OPTIONAL(stringLocationExpression, MDField, ); \
5193 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5194 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5195 OPTIONAL(encoding, DwarfAttEncodingField, );
5197#undef VISIT_MD_FIELDS
5201 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5202 stringLocationExpression.Val,
size.Val, align.Val, encoding.Val));
5215bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5216#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5217 REQUIRED(tag, DwarfTagField, ); \
5218 OPTIONAL(name, MDStringField, ); \
5219 OPTIONAL(file, MDField, ); \
5220 OPTIONAL(line, LineField, ); \
5221 OPTIONAL(scope, MDField, ); \
5222 REQUIRED(baseType, MDField, ); \
5223 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5224 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5225 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5226 OPTIONAL(flags, DIFlagField, ); \
5227 OPTIONAL(extraData, MDField, ); \
5228 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5229 OPTIONAL(annotations, MDField, ); \
5230 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5231 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5232 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5233 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5234 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5236#undef VISIT_MD_FIELDS
5238 std::optional<unsigned> DWARFAddressSpace;
5239 if (dwarfAddressSpace.Val != UINT32_MAX)
5240 DWARFAddressSpace = dwarfAddressSpace.Val;
5241 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5243 PtrAuthData.emplace(
5244 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5245 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5246 ptrAuthAuthenticatesNullValues.Val);
5249 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5250 scope.Val, baseType.Val,
size.Val, align.Val,
5251 offset.Val, DWARFAddressSpace, PtrAuthData,
5252 flags.Val, extraData.Val, annotations.Val));
5256bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
5257#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5258 REQUIRED(tag, DwarfTagField, ); \
5259 OPTIONAL(name, MDStringField, ); \
5260 OPTIONAL(file, MDField, ); \
5261 OPTIONAL(line, LineField, ); \
5262 OPTIONAL(scope, MDField, ); \
5263 OPTIONAL(baseType, MDField, ); \
5264 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5265 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5266 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5267 OPTIONAL(flags, DIFlagField, ); \
5268 OPTIONAL(elements, MDField, ); \
5269 OPTIONAL(runtimeLang, DwarfLangField, ); \
5270 OPTIONAL(vtableHolder, MDField, ); \
5271 OPTIONAL(templateParams, MDField, ); \
5272 OPTIONAL(identifier, MDStringField, ); \
5273 OPTIONAL(discriminator, MDField, ); \
5274 OPTIONAL(dataLocation, MDField, ); \
5275 OPTIONAL(associated, MDField, ); \
5276 OPTIONAL(allocated, MDField, ); \
5277 OPTIONAL(rank, MDSignedOrMDField, ); \
5278 OPTIONAL(annotations, MDField, );
5280#undef VISIT_MD_FIELDS
5283 if (
rank.isMDSignedField())
5286 else if (
rank.isMDField())
5287 Rank =
rank.getMDFieldValue();
5292 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
5293 scope.Val, baseType.Val,
size.Val, align.Val, offset.Val, flags.Val,
5294 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5295 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5296 Rank, annotations.Val)) {
5305 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
5306 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5307 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5308 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5313bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
5314#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5315 OPTIONAL(flags, DIFlagField, ); \
5316 OPTIONAL(cc, DwarfCCField, ); \
5317 REQUIRED(types, MDField, );
5319#undef VISIT_MD_FIELDS
5322 (Context, flags.Val, cc.Val, types.Val));
5331bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
5335#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5336 REQUIRED(filename, MDStringField, ); \
5337 REQUIRED(directory, MDStringField, ); \
5338 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5339 OPTIONAL(checksum, MDStringField, ); \
5340 OPTIONAL(source, MDStringField, );
5342#undef VISIT_MD_FIELDS
5344 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5345 if (checksumkind.Seen && checksum.Seen)
5346 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5347 else if (checksumkind.Seen || checksum.Seen)
5348 return Lex.
Error(
"'checksumkind' and 'checksum' must be provided together");
5354 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
5365bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
5367 return Lex.
Error(
"missing 'distinct', required for !DICompileUnit");
5369#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5370 REQUIRED(language, DwarfLangField, ); \
5371 REQUIRED(file, MDField, ( false)); \
5372 OPTIONAL(producer, MDStringField, ); \
5373 OPTIONAL(isOptimized, MDBoolField, ); \
5374 OPTIONAL(flags, MDStringField, ); \
5375 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5376 OPTIONAL(splitDebugFilename, MDStringField, ); \
5377 OPTIONAL(emissionKind, EmissionKindField, ); \
5378 OPTIONAL(enums, MDField, ); \
5379 OPTIONAL(retainedTypes, MDField, ); \
5380 OPTIONAL(globals, MDField, ); \
5381 OPTIONAL(imports, MDField, ); \
5382 OPTIONAL(macros, MDField, ); \
5383 OPTIONAL(dwoId, MDUnsignedField, ); \
5384 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5385 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5386 OPTIONAL(nameTableKind, NameTableKindField, ); \
5387 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5388 OPTIONAL(sysroot, MDStringField, ); \
5389 OPTIONAL(sdk, MDStringField, );
5391#undef VISIT_MD_FIELDS
5394 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
5395 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5396 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
5397 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5398 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5411bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
5413#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5414 OPTIONAL(scope, MDField, ); \
5415 OPTIONAL(name, MDStringField, ); \
5416 OPTIONAL(linkageName, MDStringField, ); \
5417 OPTIONAL(file, MDField, ); \
5418 OPTIONAL(line, LineField, ); \
5419 OPTIONAL(type, MDField, ); \
5420 OPTIONAL(isLocal, MDBoolField, ); \
5421 OPTIONAL(isDefinition, MDBoolField, (true)); \
5422 OPTIONAL(scopeLine, LineField, ); \
5423 OPTIONAL(containingType, MDField, ); \
5424 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5425 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5426 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5427 OPTIONAL(flags, DIFlagField, ); \
5428 OPTIONAL(spFlags, DISPFlagField, ); \
5429 OPTIONAL(isOptimized, MDBoolField, ); \
5430 OPTIONAL(unit, MDField, ); \
5431 OPTIONAL(templateParams, MDField, ); \
5432 OPTIONAL(declaration, MDField, ); \
5433 OPTIONAL(retainedNodes, MDField, ); \
5434 OPTIONAL(thrownTypes, MDField, ); \
5435 OPTIONAL(annotations, MDField, ); \
5436 OPTIONAL(targetFuncName, MDStringField, );
5438#undef VISIT_MD_FIELDS
5443 spFlags.Seen ? spFlags.Val
5445 isOptimized.Val, virtuality.Val);
5446 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5449 "missing 'distinct', required for !DISubprogram that is a Definition");
5452 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
5453 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5454 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5455 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5456 targetFuncName.Val));
5462bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
5463#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5464 REQUIRED(scope, MDField, ( false)); \
5465 OPTIONAL(file, MDField, ); \
5466 OPTIONAL(line, LineField, ); \
5467 OPTIONAL(column, ColumnField, );
5469#undef VISIT_MD_FIELDS
5478bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
5479#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5480 REQUIRED(scope, MDField, ( false)); \
5481 OPTIONAL(file, MDField, ); \
5482 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5484#undef VISIT_MD_FIELDS
5487 (Context, scope.Val,
file.Val, discriminator.Val));
5493bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
5494#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5495 REQUIRED(scope, MDField, ); \
5496 OPTIONAL(declaration, MDField, ); \
5497 OPTIONAL(name, MDStringField, ); \
5498 OPTIONAL(file, MDField, ); \
5499 OPTIONAL(line, LineField, );
5501#undef VISIT_MD_FIELDS
5504 (Context, scope.Val, declaration.Val,
name.Val,
5505 file.Val, line.Val));
5511bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
5512#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5513 REQUIRED(scope, MDField, ); \
5514 OPTIONAL(name, MDStringField, ); \
5515 OPTIONAL(exportSymbols, MDBoolField, );
5517#undef VISIT_MD_FIELDS
5520 (Context, scope.Val,
name.Val, exportSymbols.Val));
5527bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
5528#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5529 REQUIRED(type, DwarfMacinfoTypeField, ); \
5530 OPTIONAL(line, LineField, ); \
5531 REQUIRED(name, MDStringField, ); \
5532 OPTIONAL(value, MDStringField, );
5534#undef VISIT_MD_FIELDS
5537 (Context, type.Val, line.Val,
name.Val,
value.Val));
5543bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
5544#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5545 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5546 OPTIONAL(line, LineField, ); \
5547 REQUIRED(file, MDField, ); \
5548 OPTIONAL(nodes, MDField, );
5550#undef VISIT_MD_FIELDS
5553 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
5561bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
5562#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5563 REQUIRED(scope, MDField, ); \
5564 REQUIRED(name, MDStringField, ); \
5565 OPTIONAL(configMacros, MDStringField, ); \
5566 OPTIONAL(includePath, MDStringField, ); \
5567 OPTIONAL(apinotes, MDStringField, ); \
5568 OPTIONAL(file, MDField, ); \
5569 OPTIONAL(line, LineField, ); \
5570 OPTIONAL(isDecl, MDBoolField, );
5572#undef VISIT_MD_FIELDS
5575 configMacros.Val, includePath.Val,
5576 apinotes.Val, line.Val, isDecl.Val));
5582bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
5583#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5584 OPTIONAL(name, MDStringField, ); \
5585 REQUIRED(type, MDField, ); \
5586 OPTIONAL(defaulted, MDBoolField, );
5588#undef VISIT_MD_FIELDS
5591 (Context,
name.Val, type.Val, defaulted.Val));
5599bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
5600#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5601 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5602 OPTIONAL(name, MDStringField, ); \
5603 OPTIONAL(type, MDField, ); \
5604 OPTIONAL(defaulted, MDBoolField, ); \
5605 REQUIRED(value, MDField, );
5608#undef VISIT_MD_FIELDS
5612 (Context, tag.Val,
name.Val, type.Val, defaulted.Val,
value.Val));
5621bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
5622#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5623 OPTIONAL(name, MDStringField, ( false)); \
5624 OPTIONAL(scope, MDField, ); \
5625 OPTIONAL(linkageName, MDStringField, ); \
5626 OPTIONAL(file, MDField, ); \
5627 OPTIONAL(line, LineField, ); \
5628 OPTIONAL(type, MDField, ); \
5629 OPTIONAL(isLocal, MDBoolField, ); \
5630 OPTIONAL(isDefinition, MDBoolField, (true)); \
5631 OPTIONAL(templateParams, MDField, ); \
5632 OPTIONAL(declaration, MDField, ); \
5633 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5634 OPTIONAL(annotations, MDField, );
5636#undef VISIT_MD_FIELDS
5640 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
5641 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5642 declaration.Val, templateParams.Val, align.Val,
5654bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
5655#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5656 REQUIRED(scope, MDField, ( false)); \
5657 OPTIONAL(name, MDStringField, ); \
5658 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5659 OPTIONAL(file, MDField, ); \
5660 OPTIONAL(line, LineField, ); \
5661 OPTIONAL(type, MDField, ); \
5662 OPTIONAL(flags, DIFlagField, ); \
5663 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5664 OPTIONAL(annotations, MDField, );
5666#undef VISIT_MD_FIELDS
5669 (Context, scope.Val,
name.Val,
file.Val, line.Val,
5670 type.Val, arg.Val, flags.Val, align.Val,
5677bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
5678#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5679 REQUIRED(scope, MDField, ( false)); \
5680 REQUIRED(name, MDStringField, ); \
5681 REQUIRED(file, MDField, ); \
5682 REQUIRED(line, LineField, );
5684#undef VISIT_MD_FIELDS
5687 (Context, scope.Val,
name.Val,
file.Val, line.Val));
5693bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
5709 return tokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
5718 return tokError(
Twine(
"invalid DWARF attribute encoding '") +
5723 return tokError(
"expected unsigned integer");
5741bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
5742 assert(PFS &&
"Expected valid function state");
5753 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
5755 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5767bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
5769#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5770 REQUIRED(var, MDField, ); \
5771 REQUIRED(expr, MDField, );
5773#undef VISIT_MD_FIELDS
5783bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
5784#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5785 OPTIONAL(name, MDStringField, ); \
5786 OPTIONAL(file, MDField, ); \
5787 OPTIONAL(line, LineField, ); \
5788 OPTIONAL(setter, MDStringField, ); \
5789 OPTIONAL(getter, MDStringField, ); \
5790 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5791 OPTIONAL(type, MDField, );
5793#undef VISIT_MD_FIELDS
5796 (Context,
name.Val,
file.Val, line.Val, setter.Val,
5797 getter.Val, attributes.Val, type.Val));
5804bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
5805#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5806 REQUIRED(tag, DwarfTagField, ); \
5807 REQUIRED(scope, MDField, ); \
5808 OPTIONAL(entity, MDField, ); \
5809 OPTIONAL(file, MDField, ); \
5810 OPTIONAL(line, LineField, ); \
5811 OPTIONAL(name, MDStringField, ); \
5812 OPTIONAL(elements, MDField, );
5814#undef VISIT_MD_FIELDS
5817 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
5818 line.Val,
name.Val, elements.Val));
5822#undef PARSE_MD_FIELD
5834bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
5837 if (parseMetadata(MD, &PFS))
5848bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
5849 PerFunctionState *PFS) {
5852 if (parseType(Ty, TypeMsg, Loc))
5855 return error(Loc,
"invalid metadata-value-metadata roundtrip");
5858 if (parseValue(Ty, V, PFS))
5873bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
5879 if (parseDIArgList(AL, PFS))
5885 if (parseSpecializedMDNode(
N)) {
5895 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
5905 if (parseMDString(S))
5915 if (parseMDNodeTail(
N))
5926 PerFunctionState *PFS) {
5928 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
5933 return error(
ID.Loc,
"invalid use of function-local name");
5934 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
5935 return V ==
nullptr;
5938 return error(
ID.Loc,
"invalid use of function-local name");
5939 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
5940 return V ==
nullptr;
5943 return error(
ID.Loc,
"invalid type for inline asm constraint string");
5947 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
5952 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
5955 return V ==
nullptr;
5957 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
5960 return V ==
nullptr;
5963 return error(
ID.Loc,
"integer constant must have integer type");
5965 V = ConstantInt::get(Context,
ID.APSIntVal);
5970 return error(
ID.Loc,
"floating point constant invalid for type");
5976 bool IsSNAN =
ID.APFloatVal.isSignaling();
5991 APInt Payload =
ID.APFloatVal.bitcastToAPInt();
5993 ID.APFloatVal.isNegative(), &Payload);
5996 V = ConstantFP::get(Context,
ID.APFloatVal);
5998 if (
V->getType() != Ty)
5999 return error(
ID.Loc,
"floating point constant does not have type '" +
6005 return error(
ID.Loc,
"null must be a pointer type");
6011 return error(
ID.Loc,
"invalid type for undef constant");
6015 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6016 return error(
ID.Loc,
"invalid empty array initializer");
6022 return error(
ID.Loc,
"invalid type for null constant");
6023 if (
auto *TETy = dyn_cast<TargetExtType>(Ty))
6025 return error(
ID.Loc,
"invalid type for null constant");
6030 return error(
ID.Loc,
"invalid type for none constant");
6036 return error(
ID.Loc,
"invalid type for poison constant");
6040 if (
ID.ConstantVal->getType() != Ty)
6041 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6048 return error(
ID.Loc,
"vector constant must have vector type");
6050 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6052 "' but expected '" +
6059 if (
StructType *ST = dyn_cast<StructType>(Ty)) {
6060 if (
ST->getNumElements() !=
ID.UIntVal)
6062 "initializer with struct type has wrong # elements");
6064 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6067 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6068 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6071 "element " +
Twine(i) +
6072 " of struct initializer doesn't match struct element type");
6075 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6077 return error(
ID.Loc,
"constant expression type mismatch");
6087 if (parseValID(
ID,
nullptr))
6098 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6100 assert(isa<Constant>(V) &&
"Expected a constant value");
6101 C = cast<Constant>(V);
6108 return error(Loc,
"expected a constant value");
6112bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6115 return parseValID(
ID, PFS, Ty) ||
6116 convertValIDToValue(Ty,
ID, V, PFS);
6119bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6121 return parseType(Ty) || parseValue(Ty, V, PFS);
6124bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
6125 PerFunctionState &PFS) {
6128 if (parseTypeAndValue(V, PFS))
6130 if (!isa<BasicBlock>(V))
6131 return error(Loc,
"expected a basic block");
6132 BB = cast<BasicBlock>(V);
6140 if (!
Name.starts_with(
"llvm.dbg."))
6143 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6144 FnID == Intrinsic::dbg_assign;
6152bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6153 unsigned &FunctionNumber,
6158 unsigned Visibility;
6159 unsigned DLLStorageClass;
6164 Type *RetType =
nullptr;
6166 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6168 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
6169 parseType(RetType, RetTypeLoc,
true ))
6178 return error(LinkageLoc,
"invalid linkage for function definition");
6188 return error(LinkageLoc,
"invalid linkage for function declaration");
6192 return error(LinkageLoc,
"invalid function linkage type");
6196 return error(LinkageLoc,
6197 "symbol with local linkage must have default visibility");
6200 return error(LinkageLoc,
6201 "symbol with local linkage cannot have a DLL storage class");
6204 return error(RetTypeLoc,
"invalid function return type");
6208 std::string FunctionName;
6213 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
6217 return tokError(
"expected function name");
6223 return tokError(
"expected '(' in function argument list");
6228 std::vector<unsigned> FwdRefAttrGrps;
6231 std::string Partition;
6235 unsigned AddrSpace = 0;
6241 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6242 parseOptionalUnnamedAddr(UnnamedAddr) ||
6243 parseOptionalProgramAddrSpace(AddrSpace) ||
6244 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
6248 parseOptionalComdat(FunctionName,
C) ||
6249 parseOptionalAlignment(Alignment) ||
6250 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
6254 parseGlobalTypeAndValue(PersonalityFn)))
6257 if (FuncAttrs.contains(Attribute::Builtin))
6258 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
6263 FuncAttrs.removeAttribute(Attribute::Alignment);
6268 std::vector<Type*> ParamTypeList;
6271 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
6272 ParamTypeList.push_back(ArgList[i].Ty);
6273 Attrs.push_back(ArgList[i].Attrs);
6281 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
6288 if (!FunctionName.empty()) {
6291 auto FRVI = ForwardRefVals.find(FunctionName);
6292 if (FRVI != ForwardRefVals.end()) {
6293 FwdFn = FRVI->second.first;
6295 return error(FRVI->second.second,
6296 "invalid forward reference to "
6299 "' with wrong type: "
6303 ForwardRefVals.erase(FRVI);
6304 }
else if ((Fn =
M->getFunction(FunctionName))) {
6306 return error(NameLoc,
6307 "invalid redefinition of function '" + FunctionName +
"'");
6308 }
else if (
M->getNamedValue(FunctionName)) {
6309 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
6315 if (FunctionNumber == (
unsigned)-1)
6316 FunctionNumber = NumberedVals.getNext();
6320 auto I = ForwardRefValIDs.find(FunctionNumber);
6321 if (
I != ForwardRefValIDs.end()) {
6322 FwdFn =
I->second.first;
6324 return error(NameLoc,
"type of definition and forward reference of '@" +
6325 Twine(FunctionNumber) +
6330 ForwardRefValIDs.erase(
I);
6339 if (FunctionName.empty())
6340 NumberedVals.add(FunctionNumber, Fn);
6355 if (!
GC.empty()) Fn->
setGC(GC);
6358 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6362 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i, ++ArgIt) {
6364 if (ArgList[i].
Name.empty())
continue;
6369 if (ArgIt->
getName() != ArgList[i].Name)
6370 return error(ArgList[i].Loc,
6371 "redefinition of argument '%" + ArgList[i].
Name +
"'");
6384 if (FunctionName.empty()) {
6386 ID.UIntVal = FunctionNumber;
6389 ID.StrVal = FunctionName;
6391 auto Blocks = ForwardRefBlockAddresses.find(
ID);
6392 if (
Blocks != ForwardRefBlockAddresses.end())
6394 "cannot take blockaddress inside a declaration");
6398bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6400 if (FunctionNumber == -1) {
6402 ID.StrVal = std::string(
F.getName());
6405 ID.UIntVal = FunctionNumber;
6408 auto Blocks =
P.ForwardRefBlockAddresses.find(
ID);
6409 if (
Blocks ==
P.ForwardRefBlockAddresses.end())
6412 for (
const auto &
I :
Blocks->second) {
6413 const ValID &BBID =
I.first;
6417 "Expected local id or name");
6424 return P.error(BBID.
Loc,
"referenced value is not a basic block");
6435 P.ForwardRefBlockAddresses.erase(
Blocks);
6441bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
6444 return tokError(
"expected '{' in function body");
6447 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
6451 if (PFS.resolveForwardRefBlockAddresses())
6457 return tokError(
"function body requires at least one basic block");
6461 if (parseBasicBlock(PFS))
6465 if (parseUseListOrder(&PFS))
6472 return PFS.finishFunction();
6477bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6494 std::string NameStr;
6499 auto DeleteDbgRecord = [](
DbgRecord *DR) { DR->deleteRecord(); };
6500 using DbgRecordPtr = std::unique_ptr<
DbgRecord,
decltype(DeleteDbgRecord)>;
6507 if (SeenOldDbgInfoFormat)
6508 return error(Lex.
getLoc(),
"debug record should not appear in a module "
6509 "containing debug info intrinsics");
6510 SeenNewDbgInfoFormat =
true;
6512 if (!
M->IsNewDbgInfoFormat)
6513 M->convertToNewDbgValues();
6516 if (parseDebugRecord(DR, PFS))
6518 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6530 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
6535 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
6539 switch (parseInstruction(Inst, BB, PFS)) {
6542 case InstError:
return true;
6549 if (parseInstructionMetadata(*Inst))
6552 case InstExtraComma:
6557 if (parseInstructionMetadata(*Inst))
6563 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6567 for (DbgRecordPtr &DR : TrailingDbgRecord)
6569 TrailingDbgRecord.clear();
6572 assert(TrailingDbgRecord.empty() &&
6573 "All debug values should have been attached to an instruction.");
6582bool LLParser::parseDebugRecord(
DbgRecord *&DR, PerFunctionState &PFS) {
6587 return error(DVRLoc,
"expected debug record type here");
6589 .
Case(
"declare", RecordKind::ValueKind)
6590 .
Case(
"value", RecordKind::ValueKind)
6591 .
Case(
"assign", RecordKind::ValueKind)
6592 .
Case(
"label", RecordKind::LabelKind);
6601 if (parseMDNode(Label))
6606 if (parseMDNode(DbgLoc))
6615 .
Case(
"declare", LocType::Declare)
6616 .
Case(
"value", LocType::Value)
6617 .
Case(
"assign", LocType::Assign);
6625 if (parseMetadata(ValLocMD, &PFS))
6632 if (parseMDNode(Variable))
6645 MDNode *AssignID =
nullptr;
6646 Metadata *AddressLocation =
nullptr;
6647 MDNode *AddressExpression =
nullptr;
6650 if (parseMDNode(AssignID))
6656 if (parseMetadata(AddressLocation, &PFS))
6662 if (parseMDNode(AddressExpression))
6687 PerFunctionState &PFS) {
6690 return tokError(
"found end of file when expecting more instructions");
6697 return error(Loc,
"expected instruction opcode");
6701 return parseRet(Inst, BB, PFS);
6703 return parseBr(Inst, PFS);
6705 return parseSwitch(Inst, PFS);
6707 return parseIndirectBr(Inst, PFS);
6709 return parseInvoke(Inst, PFS);
6711 return parseResume(Inst, PFS);
6713 return parseCleanupRet(Inst, PFS);
6715 return parseCatchRet(Inst, PFS);
6717 return parseCatchSwitch(Inst, PFS);
6719 return parseCatchPad(Inst, PFS);
6721 return parseCleanupPad(Inst, PFS);
6723 return parseCallBr(Inst, PFS);
6727 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
6743 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6746 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
6747 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
6756 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
6770 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
6772 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
6778 return parseArithmetic(Inst, PFS, KeywordVal,
6782 if (parseLogical(Inst, PFS, KeywordVal))
6785 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(
true);
6790 return parseLogical(Inst, PFS, KeywordVal);
6792 return parseCompare(Inst, PFS, KeywordVal);
6795 int Res = parseCompare(Inst, PFS, KeywordVal);
6806 bool Res = parseCast(Inst, PFS, KeywordVal);
6825 return parseCast(Inst, PFS, KeywordVal);
6829 int Res = parseSelect(Inst, PFS);
6833 if (!isa<FPMathOperator>(Inst))
6834 return error(Loc,
"fast-math-flags specified for select without "
6835 "floating-point scalar or vector return type");
6841 return parseVAArg(Inst, PFS);
6843 return parseExtractElement(Inst, PFS);
6845 return parseInsertElement(Inst, PFS);
6847 return parseShuffleVector(Inst, PFS);
6850 int Res = parsePHI(Inst, PFS);
6854 if (!isa<FPMathOperator>(Inst))
6855 return error(Loc,
"fast-math-flags specified for phi without "
6856 "floating-point scalar or vector return type");
6862 return parseLandingPad(Inst, PFS);
6864 return parseFreeze(Inst, PFS);
6876 return parseAlloc(Inst, PFS);
6878 return parseLoad(Inst, PFS);
6880 return parseStore(Inst, PFS);
6882 return parseCmpXchg(Inst, PFS);
6884 return parseAtomicRMW(Inst, PFS);
6886 return parseFence(Inst, PFS);
6888 return parseGetElementPtr(Inst, PFS);
6890 return parseExtractValue(Inst, PFS);
6892 return parseInsertValue(Inst, PFS);
6897bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
6898 if (Opc == Instruction::FCmp) {
6901 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
6922 return tokError(
"expected icmp predicate (e.g. 'eq')");
6947 PerFunctionState &PFS) {
6950 if (parseType(Ty,
true ))
6953 Type *ResType = PFS.getFunction().getReturnType();
6957 return error(TypeLoc,
"value doesn't match function result type '" +
6965 if (parseValue(Ty, RV, PFS))
6969 return error(TypeLoc,
"value doesn't match function result type '" +
6979bool LLParser::parseBr(
Instruction *&Inst, PerFunctionState &PFS) {
6983 if (parseTypeAndValue(Op0, Loc, PFS))
6986 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6992 return error(Loc,
"branch condition must have 'i1' type");
6994 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
6995 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6996 parseToken(
lltok::comma,
"expected ',' after true destination") ||
6997 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7009bool LLParser::parseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7010 LocTy CondLoc, BBLoc;
7013 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7014 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7015 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7019 if (!
Cond->getType()->isIntegerTy())
7020 return error(CondLoc,
"switch condition must have integer type");
7029 if (parseTypeAndValue(
Constant, CondLoc, PFS) ||
7030 parseToken(
lltok::comma,
"expected ',' after case value") ||
7031 parseTypeAndBasicBlock(DestBB, PFS))
7035 return error(CondLoc,
"duplicate case value in switch");
7037 return error(CondLoc,
"case value is not a constant integer");
7045 for (
unsigned i = 0, e = Table.
size(); i != e; ++i)
7046 SI->addCase(Table[i].first, Table[i].second);
7054bool LLParser::parseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
7057 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7058 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7062 if (!
Address->getType()->isPointerTy())
7063 return error(AddrLoc,
"indirectbr address must have pointer type");
7070 if (parseTypeAndBasicBlock(DestBB, PFS))
7075 if (parseTypeAndBasicBlock(DestBB, PFS))
7081 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7085 for (
unsigned i = 0, e = DestList.
size(); i != e; ++i)
7094bool LLParser::resolveFunctionType(
Type *RetType,
7097 FuncTy = dyn_cast<FunctionType>(RetType);
7100 std::vector<Type*> ParamTypes;
7101 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i)
7102 ParamTypes.push_back(ArgList[i].
V->getType());
7115bool LLParser::parseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
7117 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7118 std::vector<unsigned> FwdRefAttrGrps;
7121 unsigned InvokeAddrSpace;
7122 Type *RetType =
nullptr;
7129 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7130 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7131 parseType(RetType, RetTypeLoc,
true ) ||
7132 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7133 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7135 parseOptionalOperandBundles(BundleList, PFS) ||
7137 parseTypeAndBasicBlock(NormalBB, PFS) ||
7139 parseTypeAndBasicBlock(UnwindBB, PFS))
7146 if (resolveFunctionType(RetType, ArgList, Ty))
7147 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7165 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7166 Type *ExpectedTy =
nullptr;
7169 }
else if (!Ty->isVarArg()) {
7170 return error(ArgList[i].Loc,
"too many arguments specified");
7173 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7174 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7176 Args.push_back(ArgList[i].V);
7181 return error(CallLoc,
"not enough parameters specified for call");
7192 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7199bool LLParser::parseResume(
Instruction *&Inst, PerFunctionState &PFS) {
7201 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7210 PerFunctionState &PFS) {
7211 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
7216 if (!
Args.empty() &&
7217 parseToken(
lltok::comma,
"expected ',' in argument list"))
7222 Type *ArgTy =
nullptr;
7223 if (parseType(ArgTy, ArgLoc))
7228 if (parseMetadataAsValue(V, PFS))
7231 if (parseValue(ArgTy, V, PFS))
7243bool LLParser::parseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
7244 Value *CleanupPad =
nullptr;
7246 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
7261 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7272bool LLParser::parseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
7273 Value *CatchPad =
nullptr;
7275 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
7282 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
7283 parseTypeAndBasicBlock(BB, PFS))
7292bool LLParser::parseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
7300 return tokError(
"expected scope value for catchswitch");
7305 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
7311 if (parseTypeAndBasicBlock(DestBB, PFS))
7316 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
7319 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
7327 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7334 CatchSwitch->addHandler(DestBB);
7341bool LLParser::parseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
7342 Value *CatchSwitch =
nullptr;
7348 return tokError(
"expected scope value for catchpad");
7354 if (parseExceptionArgs(Args, PFS))
7363bool LLParser::parseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
7364 Value *ParentPad =
nullptr;
7371 return tokError(
"expected scope value for cleanuppad");
7377 if (parseExceptionArgs(Args, PFS))
7393bool LLParser::parseUnaryOp(
Instruction *&Inst, PerFunctionState &PFS,
7394 unsigned Opc,
bool IsFP) {
7396 if (parseTypeAndValue(LHS, Loc, PFS))
7403 return error(Loc,
"invalid operand type for instruction");
7413bool LLParser::parseCallBr(
Instruction *&Inst, PerFunctionState &PFS) {
7415 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7416 std::vector<unsigned> FwdRefAttrGrps;
7419 Type *RetType =
nullptr;
7426 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7427 parseType(RetType, RetTypeLoc,
true ) ||
7428 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7429 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7431 parseOptionalOperandBundles(BundleList, PFS) ||
7433 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7442 if (parseTypeAndBasicBlock(DestBB, PFS))
7447 if (parseTypeAndBasicBlock(DestBB, PFS))
7453 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7460 if (resolveFunctionType(RetType, ArgList, Ty))
7461 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7478 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7479 Type *ExpectedTy =
nullptr;
7482 }
else if (!Ty->isVarArg()) {
7483 return error(ArgList[i].Loc,
"too many arguments specified");
7486 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7487 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7489 Args.push_back(ArgList[i].V);
7494 return error(CallLoc,
"not enough parameters specified for call");
7506 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7520bool LLParser::parseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
7521 unsigned Opc,
bool IsFP) {
7523 if (parseTypeAndValue(LHS, Loc, PFS) ||
7524 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
7532 return error(Loc,
"invalid operand type for instruction");
7540bool LLParser::parseLogical(
Instruction *&Inst, PerFunctionState &PFS,
7543 if (parseTypeAndValue(LHS, Loc, PFS) ||
7544 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
7550 "instruction requires integer or integer vector operands");
7559bool LLParser::parseCompare(
Instruction *&Inst, PerFunctionState &PFS,
7565 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7566 parseToken(
lltok::comma,
"expected ',' after compare value") ||
7570 if (Opc == Instruction::FCmp) {
7572 return error(Loc,
"fcmp requires floating point operands");
7575 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
7578 return error(Loc,
"icmp requires integer operands");
7590bool LLParser::parseCast(
Instruction *&Inst, PerFunctionState &PFS,
7594 Type *DestTy =
nullptr;
7595 if (parseTypeAndValue(
Op, Loc, PFS) ||
7596 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
7602 return error(Loc,
"invalid cast opcode for cast from '" +
7612bool LLParser::parseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
7614 Value *Op0, *Op1, *Op2;
7615 if (parseTypeAndValue(Op0, Loc, PFS) ||
7616 parseToken(
lltok::comma,
"expected ',' after select condition") ||
7617 parseTypeAndValue(Op1, PFS) ||
7618 parseToken(
lltok::comma,
"expected ',' after select value") ||
7619 parseTypeAndValue(Op2, PFS))
7623 return error(Loc, Reason);
7631bool LLParser::parseVAArg(
Instruction *&Inst, PerFunctionState &PFS) {
7633 Type *EltTy =
nullptr;
7635 if (parseTypeAndValue(
Op, PFS) ||
7636 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
7637 parseType(EltTy, TypeLoc))
7641 return error(TypeLoc,
"va_arg requires operand with first class type");
7649bool LLParser::parseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
7652 if (parseTypeAndValue(Op0, Loc, PFS) ||
7653 parseToken(
lltok::comma,
"expected ',' after extract value") ||
7654 parseTypeAndValue(Op1, PFS))
7658 return error(Loc,
"invalid extractelement operands");
7666bool LLParser::parseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
7668 Value *Op0, *Op1, *Op2;
7669 if (parseTypeAndValue(Op0, Loc, PFS) ||
7670 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7671 parseTypeAndValue(Op1, PFS) ||
7672 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7673 parseTypeAndValue(Op2, PFS))
7677 return error(Loc,
"invalid insertelement operands");
7685bool LLParser::parseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
7687 Value *Op0, *Op1, *Op2;
7688 if (parseTypeAndValue(Op0, Loc, PFS) ||
7689 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
7690 parseTypeAndValue(Op1, PFS) ||
7691 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
7692 parseTypeAndValue(Op2, PFS))
7696 return error(Loc,
"invalid shufflevector operands");
7704int LLParser::parsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
7708 if (parseType(Ty, TypeLoc))
7712 return error(TypeLoc,
"phi node must have first class type");
7715 bool AteExtraComma =
false;
7727 AteExtraComma =
true;
7731 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
7732 parseValue(Ty, Op0, PFS) ||
7733 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
7738 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7742 for (
unsigned i = 0, e = PHIVals.
size(); i != e; ++i)
7743 PN->
addIncoming(PHIVals[i].first, PHIVals[i].second);
7745 return AteExtraComma ? InstExtraComma : InstNormal;
7754bool LLParser::parseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
7757 if (parseType(Ty, TyLoc))
7770 return tokError(
"expected 'catch' or 'filter' clause type");
7774 if (parseTypeAndValue(V, VLoc, PFS))
7780 if (isa<ArrayType>(
V->getType()))
7781 error(VLoc,
"'catch' clause has an invalid type");
7783 if (!isa<ArrayType>(
V->getType()))
7784 error(VLoc,
"'filter' clause has an invalid type");
7787 Constant *CV = dyn_cast<Constant>(V);
7789 return error(VLoc,
"clause argument must be a constant");
7793 Inst = LP.release();
7799bool LLParser::parseFreeze(
Instruction *&Inst, PerFunctionState &PFS) {
7802 if (parseTypeAndValue(
Op, Loc, PFS))
7818bool LLParser::parseCall(
Instruction *&Inst, PerFunctionState &PFS,
7820 AttrBuilder RetAttrs(
M->getContext()), FnAttrs(
M->getContext());
7821 std::vector<unsigned> FwdRefAttrGrps;
7823 unsigned CallAddrSpace;
7825 Type *RetType =
nullptr;
7834 "expected 'tail call', 'musttail call', or 'notail call'"))
7839 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7840 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7841 parseType(RetType, RetTypeLoc,
true ) ||
7842 parseValID(CalleeID, &PFS) ||
7844 PFS.getFunction().isVarArg()) ||
7845 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
7846 parseOptionalOperandBundles(BundleList, PFS))
7853 if (resolveFunctionType(RetType, ArgList, Ty))
7854 return error(RetTypeLoc,
"Invalid result type for LLVM function");
7860 if (convertValIDToValue(
PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7873 for (
unsigned i = 0, e = ArgList.
size(); i != e; ++i) {
7874 Type *ExpectedTy =
nullptr;
7877 }
else if (!Ty->isVarArg()) {
7878 return error(ArgList[i].Loc,
"too many arguments specified");
7881 if (ExpectedTy && ExpectedTy != ArgList[i].
V->getType())
7882 return error(ArgList[i].Loc,
"argument is not of expected type '" +
7884 Args.push_back(ArgList[i].V);
7885 Attrs.push_back(ArgList[i].Attrs);
7889 return error(CallLoc,
"not enough parameters specified for call");
7900 if (!isa<FPMathOperator>(CI)) {
7902 return error(CallLoc,
"fast-math-flags specified for call without "
7903 "floating-point scalar or vector return type");
7910 if (SeenNewDbgInfoFormat) {
7912 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
7913 "using non-intrinsic debug info");
7915 SeenOldDbgInfoFormat =
true;
7918 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7930int LLParser::parseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
7932 LocTy SizeLoc, TyLoc, ASLoc;
7934 unsigned AddrSpace = 0;
7937 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7938 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7940 if (parseType(Ty, TyLoc))
7944 return error(TyLoc,
"invalid type for alloca");
7946 bool AteExtraComma =
false;
7948 if (Lex.
getKind() == lltok::kw_align) {
7949 if (parseOptionalAlignment(Alignment))
7951 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7955 if (parseOptionalAddrSpace(AddrSpace))
7958 AteExtraComma =
true;
7960 if (parseTypeAndValue(
Size, SizeLoc, PFS))
7963 if (Lex.
getKind() == lltok::kw_align) {
7964 if (parseOptionalAlignment(Alignment))
7966 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7970 if (parseOptionalAddrSpace(AddrSpace))
7973 AteExtraComma =
true;
7979 if (
Size && !
Size->getType()->isIntegerTy())
7980 return error(SizeLoc,
"element count must have integer type");
7983 if (!Alignment && !Ty->
isSized(&Visited))
7984 return error(TyLoc,
"Cannot allocate unsized type");
7986 Alignment =
M->getDataLayout().getPrefTypeAlign(Ty);
7991 return AteExtraComma ? InstExtraComma : InstNormal;
7998int LLParser::parseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
8001 bool AteExtraComma =
false;
8002 bool isAtomic =
false;
8011 bool isVolatile =
false;
8019 if (parseType(Ty) ||
8020 parseToken(
lltok::comma,
"expected comma after load's type") ||
8021 parseTypeAndValue(Val, Loc, PFS) ||
8022 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8023 parseOptionalCommaAlign(Alignment, AteExtraComma))
8027 return error(Loc,
"load operand must be a pointer to a first class type");
8028 if (isAtomic && !Alignment)
8029 return error(Loc,
"atomic load must have explicit non-zero alignment");
8032 return error(Loc,
"atomic load cannot use Release ordering");
8035 if (!Alignment && !Ty->
isSized(&Visited))
8036 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8038 Alignment =
M->getDataLayout().getABITypeAlign(Ty);
8039 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8040 return AteExtraComma ? InstExtraComma : InstNormal;
8048int LLParser::parseStore(
Instruction *&Inst, PerFunctionState &PFS) {
8051 bool AteExtraComma =
false;
8052 bool isAtomic =
false;
8061 bool isVolatile =
false;
8067 if (parseTypeAndValue(Val, Loc, PFS) ||
8068 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8069 parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8070 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8071 parseOptionalCommaAlign(Alignment, AteExtraComma))
8074 if (!
Ptr->getType()->isPointerTy())
8075 return error(PtrLoc,
"store operand must be a pointer");
8077 return error(Loc,
"store operand must be a first class value");
8078 if (isAtomic && !Alignment)
8079 return error(Loc,
"atomic store must have explicit non-zero alignment");
8082 return error(Loc,
"atomic store cannot use Acquire ordering");
8085 return error(Loc,
"storing unsized types is not allowed");
8087 Alignment =
M->getDataLayout().getABITypeAlign(Val->
getType());
8089 Inst =
new StoreInst(Val,
Ptr, isVolatile, *Alignment, Ordering, SSID);
8090 return AteExtraComma ? InstExtraComma : InstNormal;
8097int LLParser::parseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
8099 bool AteExtraComma =
false;
8103 bool isVolatile =
false;
8104 bool isWeak =
false;
8113 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8114 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8115 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8116 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8117 parseTypeAndValue(New, NewLoc, PFS) ||
8118 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8119 parseOrdering(FailureOrdering) ||
8120 parseOptionalCommaAlign(Alignment, AteExtraComma))
8124 return tokError(
"invalid cmpxchg success ordering");
8126 return tokError(
"invalid cmpxchg failure ordering");
8127 if (!
Ptr->getType()->isPointerTy())
8128 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8129 if (
Cmp->getType() !=
New->getType())
8130 return error(NewLoc,
"compare value and new value type do not match");
8131 if (!
New->getType()->isFirstClassType())
8132 return error(NewLoc,
"cmpxchg operand must be a first class value");
8134 const Align DefaultAlignment(
8135 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8140 SuccessOrdering, FailureOrdering, SSID);
8145 return AteExtraComma ? InstExtraComma : InstNormal;
8151int LLParser::parseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
8153 bool AteExtraComma =
false;
8156 bool isVolatile =
false;
8166 return tokError(
"expected binary operation in atomicrmw");
8203 if (parseTypeAndValue(
Ptr, PtrLoc, PFS) ||
8204 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
8205 parseTypeAndValue(Val, ValLoc, PFS) ||
8206 parseScopeAndOrdering(
true , SSID, Ordering) ||
8207 parseOptionalCommaAlign(Alignment, AteExtraComma))
8211 return tokError(
"atomicrmw cannot be unordered");
8212 if (!
Ptr->getType()->isPointerTy())
8213 return error(PtrLoc,
"atomicrmw operand must be a pointer");
8222 " operand must be an integer, floating point, or pointer type");
8226 return error(ValLoc,
"atomicrmw " +
8228 " operand must be a floating point type");
8232 return error(ValLoc,
"atomicrmw " +
8234 " operand must be an integer");
8239 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
8242 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
8244 const Align DefaultAlignment(
8245 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
8249 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8252 return AteExtraComma ? InstExtraComma : InstNormal;
8257int LLParser::parseFence(
Instruction *&Inst, PerFunctionState &PFS) {
8260 if (parseScopeAndOrdering(
true , SSID, Ordering))
8264 return tokError(
"fence cannot be unordered");
8266 return tokError(
"fence cannot be monotonic");
8268 Inst =
new FenceInst(Context, Ordering, SSID);
8274int LLParser::parseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
8276 Value *Val =
nullptr;
8282 if (parseType(Ty) ||
8283 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
8284 parseTypeAndValue(
Ptr, Loc, PFS))
8289 if (!BasePointerType)
8290 return error(Loc,
"base of getelementptr must be a pointer");
8293 bool AteExtraComma =
false;
8297 ? cast<VectorType>(
BaseType)->getElementCount()
8302 AteExtraComma =
true;
8305 if (parseTypeAndValue(Val, EltLoc, PFS))
8308 return error(EltLoc,
"getelementptr index must be an integer");
8310 if (
auto *ValVTy = dyn_cast<VectorType>(Val->
getType())) {
8315 "getelementptr vector index has a wrong number of elements");
8316 GEPWidth = ValNumEl;
8323 return error(Loc,
"base element of getelementptr must be sized");
8325 auto *STy = dyn_cast<StructType>(Ty);
8327 return error(Loc,
"getelementptr cannot target structure that contains "
8328 "scalable vector type");
8331 return error(Loc,
"invalid getelementptr indices");
8334 cast<GetElementPtrInst>(Inst)->setIsInBounds(
true);
8335 return AteExtraComma ? InstExtraComma : InstNormal;
8340int LLParser::parseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
8344 if (parseTypeAndValue(Val, Loc, PFS) ||
8345 parseIndexList(Indices, AteExtraComma))
8349 return error(Loc,
"extractvalue operand must be aggregate type");
8352 return error(Loc,
"invalid indices for extractvalue");
8354 return AteExtraComma ? InstExtraComma : InstNormal;
8359int LLParser::parseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
8363 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8364 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
8365 parseTypeAndValue(Val1, Loc1, PFS) ||
8366 parseIndexList(Indices, AteExtraComma))
8370 return error(Loc0,
"insertvalue operand must be aggregate type");
8374 return error(Loc0,
"invalid indices for insertvalue");
8375 if (IndexedType != Val1->
getType())
8376 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
8380 return AteExtraComma ? InstExtraComma : InstNormal;
8407 if (parseMetadata(MD,
nullptr))
8412 return parseToken(
lltok::rbrace,
"expected end of metadata node");
8421 return error(Loc,
"value has no uses");
8423 unsigned NumUses = 0;
8425 for (
const Use &U :
V->uses()) {
8426 if (++NumUses > Indexes.
size())
8428 Order[&
U] = Indexes[NumUses - 1];
8431 return error(Loc,
"value only has one use");
8432 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
8434 "wrong number of indexes, expected " +
Twine(
V->getNumUses()));
8436 V->sortUseList([&](
const Use &L,
const Use &R) {
8449 return Lex.
Error(
"expected non-empty list of uselistorder indexes");
8456 bool IsOrdered =
true;
8457 assert(Indexes.
empty() &&
"Expected empty order vector");
8460 if (parseUInt32(
Index))
8474 if (Indexes.
size() < 2)
8475 return error(Loc,
"expected >= 2 uselistorder indexes");
8478 "expected distinct uselistorder indexes in range [0, size)");
8480 return error(Loc,
"expected uselistorder indexes to change the order");
8487bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8494 if (parseTypeAndValue(V, PFS) ||
8495 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
8496 parseUseListOrderIndexes(Indexes))
8499 return sortUseListOrder(V, Indexes, Loc);
8504bool LLParser::parseUseListOrderBB() {
8511 if (parseValID(Fn,
nullptr) ||
8512 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8513 parseValID(Label,
nullptr) ||
8514 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
8515 parseUseListOrderIndexes(Indexes))
8521 GV =
M->getNamedValue(Fn.
StrVal);
8523 GV = NumberedVals.get(Fn.
UIntVal);
8525 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8528 "invalid function forward reference in uselistorder_bb");
8529 auto *
F = dyn_cast<Function>(GV);
8531 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
8532 if (
F->isDeclaration())
8533 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
8537 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
8539 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
8540 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
8542 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
8543 if (!isa<BasicBlock>(V))
8544 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
8546 return sortUseListOrder(V, Indexes, Loc);
8552bool LLParser::parseModuleEntry(
unsigned ID) {
8561 parseStringConstant(Path) ||
8569 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
8570 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
8571 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
8572 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
8573 parseUInt32(Hash[4]))
8580 auto ModuleEntry =
Index->addModule(Path, Hash);
8581 ModuleIdMap[
ID] = ModuleEntry->first();
8588bool LLParser::parseTypeIdEntry(
unsigned ID) {
8597 parseStringConstant(
Name))
8602 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
8607 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8608 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8609 for (
auto TIDRef : FwdRefTIDs->second) {
8611 "Forward referenced type id GUID expected to be 0");
8614 ForwardRefTypeIds.erase(FwdRefTIDs);
8626 parseTypeTestResolution(TIS.
TTRes))
8631 if (parseOptionalWpdResolutions(TIS.
WPDRes))
8642 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
8648bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
8657 parseStringConstant(
Name))
8661 Index->getOrInsertTypeIdCompatibleVtableSummary(
Name);
8668 IdToIndexMapType IdToIndexMap;
8681 if (parseGVReference(VI, GVId))
8688 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8689 TI.push_back({
Offset, VI});
8697 for (
auto I : IdToIndexMap) {
8698 auto &Infos = ForwardRefValueInfos[
I.first];
8699 for (
auto P :
I.second) {
8701 "Forward referenced ValueInfo expected to be empty");
8702 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
8712 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
8713 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8714 for (
auto TIDRef : FwdRefTIDs->second) {
8716 "Forward referenced type id GUID expected to be 0");
8719 ForwardRefTypeIds.erase(FwdRefTIDs);
8759 return error(Lex.
getLoc(),
"unexpected TypeTestResolution kind");
8786 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
8799 return error(Lex.
getLoc(),
"expected optional TypeTestResolution field");
8812bool LLParser::parseOptionalWpdResolutions(
8813 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8825 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
8828 WPDResMap[
Offset] = WPDRes;
8864 return error(Lex.
getLoc(),
"unexpected WholeProgramDevirtResolution kind");
8878 if (parseOptionalResByArg(WPDRes.
ResByArg))
8883 "expected optional WholeProgramDevirtResolution field");
8900bool LLParser::parseOptionalResByArg(
8909 std::vector<uint64_t>
Args;
8910 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
8934 "unexpected WholeProgramDevirtResolution::ByArg kind");
8944 parseUInt64(ByArg.
Info))
8950 parseUInt32(ByArg.
Byte))
8956 parseUInt32(ByArg.
Bit))
8961 "expected optional whole program devirt field");
8968 ResByArg[
Args] = ByArg;
8979bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8987 if (parseUInt64(Val))
8989 Args.push_back(Val);
8998static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9003 assert(!(ReadOnly && WriteOnly));
9013bool LLParser::addGlobalValueToIndex(
9015 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9020 VI =
Index->getOrInsertValueInfo(GUID);
9024 auto *GV =
M->getNamedValue(
Name);
9026 return error(Loc,
"Reference to undefined global \"" +
Name +
"\"");
9028 VI =
Index->getOrInsertValueInfo(GV);
9032 "Need a source_filename to compute GUID for local");
9040 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9041 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9042 for (
auto VIRef : FwdRefVIs->second) {
9044 "Forward referenced ValueInfo expected to be empty");
9047 ForwardRefValueInfos.erase(FwdRefVIs);
9051 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9052 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9053 for (
auto AliaseeRef : FwdRefAliasees->second) {
9054 assert(!AliaseeRef.first->hasAliasee() &&
9055 "Forward referencing alias already has aliasee");
9056 assert(Summary &&
"Aliasee must be a definition");
9057 AliaseeRef.first->setAliasee(VI,
Summary.get());
9059 ForwardRefAliasees.erase(FwdRefAliasees);
9064 Index->addGlobalValueSummary(VI, std::move(Summary));
9067 if (
ID == NumberedValueInfos.size())
9068 NumberedValueInfos.push_back(VI);
9071 if (
ID > NumberedValueInfos.size())
9072 NumberedValueInfos.resize(
ID + 1);
9073 NumberedValueInfos[
ID] =
VI;
9081bool LLParser::parseSummaryIndexFlags() {
9088 if (parseUInt64(Flags))
9091 Index->setFlags(Flags);
9097bool LLParser::parseBlockCount() {
9104 if (parseUInt64(BlockCount))
9107 Index->setBlockCount(BlockCount);
9115bool LLParser::parseGVEntry(
unsigned ID) {
9130 parseStringConstant(
Name))
9136 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
9140 return error(Lex.
getLoc(),
"expected name or guid tag");
9165 if (parseFunctionSummary(
Name, GUID,
ID))
9169 if (parseVariableSummary(
Name, GUID,
ID))
9173 if (parseAliasSummary(
Name, GUID,
ID))
9177 return error(Lex.
getLoc(),
"expected summary type");
9203 false,
false,
false);
9205 std::vector<FunctionSummary::EdgeTy> Calls;
9207 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9208 std::vector<ValueInfo> Refs;
9209 std::vector<CallsiteInfo> Callsites;
9210 std::vector<AllocInfo> Allocs;
9215 parseModuleReference(ModulePath) ||
9216 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9219 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
9226 if (parseOptionalFFlags(FFlags))
9230 if (parseOptionalCalls(Calls))
9234 if (parseOptionalTypeIdInfo(TypeIdInfo))
9238 if (parseOptionalRefs(Refs))
9242 if (parseOptionalParamAccesses(ParamAccesses))
9246 if (parseOptionalAllocs(Allocs))
9250 if (parseOptionalCallsites(Callsites))
9254 return error(Lex.
getLoc(),
"expected optional function summary field");
9261 auto FS = std::make_unique<FunctionSummary>(
9262 GVFlags, InstCount, FFlags, 0, std::move(Refs),
9263 std::move(Calls), std::move(TypeIdInfo.
TypeTests),
9268 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9270 FS->setModulePath(ModulePath);
9272 return addGlobalValueToIndex(
Name, GUID,
9274 std::move(FS), Loc);
9290 false,
false,
false);
9295 std::vector<ValueInfo> Refs;
9299 parseModuleReference(ModulePath) ||
9300 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9302 parseGVarFlags(GVarFlags))
9309 if (parseOptionalVTableFuncs(VTableFuncs))
9313 if (parseOptionalRefs(Refs))
9317 return error(Lex.
getLoc(),
"expected optional variable summary field");
9325 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9327 GS->setModulePath(ModulePath);
9328 GS->setVTableFuncs(std::move(VTableFuncs));
9330 return addGlobalValueToIndex(
Name, GUID,
9332 std::move(GS), Loc);
9348 false,
false,
false);
9351 parseModuleReference(ModulePath) ||
9352 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
9360 if (parseGVReference(AliaseeVI, GVId))
9366 auto AS = std::make_unique<AliasSummary>(GVFlags);
9368 AS->setModulePath(ModulePath);
9372 ForwardRefAliasees[GVId].emplace_back(AS.
get(), Loc);
9374 auto Summary =
Index->findSummaryInModule(AliaseeVI, ModulePath);
9375 assert(Summary &&
"Aliasee must be a definition");
9376 AS->setAliasee(AliaseeVI, Summary);
9379 return addGlobalValueToIndex(
Name, GUID,
9381 std::move(AS), Loc);
9386bool LLParser::parseFlag(
unsigned &Val) {
9388 return tokError(
"expected integer");
9409 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
9418 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9424 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9430 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9436 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9442 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9448 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9454 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9460 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9466 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9472 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
9477 return error(Lex.
getLoc(),
"expected function flag type");
9492bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9496 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
9500 IdToIndexMapType IdToIndexMap;
9511 if (parseGVReference(VI, GVId))
9516 unsigned HasTailCall =
false;
9523 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
9528 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
9533 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
9537 return error(Lex.
getLoc(),
"expected hotness, relbf, or tail");
9541 return tokError(
"Expected only one of hotness or relbf");
9546 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9556 for (
auto I : IdToIndexMap) {
9557 auto &Infos = ForwardRefValueInfos[
I.first];
9558 for (
auto P :
I.second) {
9560 "Forward referenced ValueInfo expected to be empty");
9561 Infos.emplace_back(&Calls[
P.first].first,
P.second);
9578 case lltok::kw_cold:
9591 return error(Lex.
getLoc(),
"invalid call edge hotness");
9600bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
9604 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
9608 IdToIndexMapType IdToIndexMap;
9612 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
9619 if (parseGVReference(VI, GVId))
9632 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9633 VTableFuncs.push_back({
VI,
Offset});
9635 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
9641 for (
auto I : IdToIndexMap) {
9642 auto &Infos = ForwardRefValueInfos[
I.first];
9643 for (
auto P :
I.second) {
9645 "Forward referenced ValueInfo expected to be empty");
9646 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
9650 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
9657bool LLParser::parseParamNo(
uint64_t &ParamNo) {
9659 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
9665bool LLParser::parseParamAccessOffset(
ConstantRange &Range) {
9668 auto ParseAPSInt = [&](
APSInt &Val) {
9670 return tokError(
"expected integer");
9673 Val.setIsSigned(
true);
9696 IdLocListType &IdLocList) {
9705 if (parseGVReference(VI, GVId))
9709 IdLocList.emplace_back(GVId, Loc);
9712 parseParamNo(
Call.ParamNo) ||
9714 parseParamAccessOffset(
Call.Offsets))
9727 IdLocListType &IdLocList) {
9729 parseParamNo(
Param.ParamNo) ||
9731 parseParamAccessOffset(
Param.Use))
9741 if (parseParamAccessCall(Call, IdLocList))
9743 Param.Calls.push_back(Call);
9758bool LLParser::parseOptionalParamAccesses(
9759 std::vector<FunctionSummary::ParamAccess> &Params) {
9767 IdLocListType VContexts;
9768 size_t CallsNum = 0;
9771 if (parseParamAccess(ParamAccess, VContexts))
9773 CallsNum += ParamAccess.
Calls.size();
9774 assert(VContexts.size() == CallsNum);
9776 Params.emplace_back(std::move(ParamAccess));
9784 IdLocListType::const_iterator ItContext = VContexts.begin();
9785 for (
auto &PA : Params) {
9786 for (
auto &
C : PA.Calls) {
9788 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
9793 assert(ItContext == VContexts.end());
9800bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9804 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
9808 struct ValueContext {
9813 std::vector<ValueContext> VContexts;
9818 if (parseGVReference(
VC.VI,
VC.GVId))
9820 VContexts.push_back(VC);
9826 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
9827 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9830 IdToIndexMapType IdToIndexMap;
9831 for (
auto &VC : VContexts) {
9836 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.size(),
VC.Loc));
9837 Refs.push_back(
VC.VI);
9842 for (
auto I : IdToIndexMap) {
9843 auto &Infos = ForwardRefValueInfos[
I.first];
9844 for (
auto P :
I.second) {
9846 "Forward referenced ValueInfo expected to be empty");
9847 Infos.emplace_back(&Refs[
P.first],
P.second);
9861bool LLParser::parseOptionalTypeIdInfo(
9873 if (parseTypeTests(TypeIdInfo.
TypeTests))
9897 return error(Lex.
getLoc(),
"invalid typeIdInfo list type");
9901 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
9910bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9918 IdToIndexMapType IdToIndexMap;
9927 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
9929 }
else if (parseUInt64(GUID))
9931 TypeTests.push_back(GUID);
9936 for (
auto I : IdToIndexMap) {
9937 auto &Ids = ForwardRefTypeIds[
I.first];
9938 for (
auto P :
I.second) {
9939 assert(TypeTests[
P.first] == 0 &&
9940 "Forward referenced type id GUID expected to be 0");
9941 Ids.emplace_back(&TypeTests[
P.first],
P.second);
9945 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
9953bool LLParser::parseVFuncIdList(
9954 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9962 IdToIndexMapType IdToIndexMap;
9965 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9967 VFuncIdList.push_back(VFuncId);
9975 for (
auto I : IdToIndexMap) {
9976 auto &Ids = ForwardRefTypeIds[
I.first];
9977 for (
auto P :
I.second) {
9978 assert(VFuncIdList[
P.first].GUID == 0 &&
9979 "Forward referenced type id GUID expected to be 0");
9980 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
9989bool LLParser::parseConstVCallList(
9991 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9999 IdToIndexMapType IdToIndexMap;
10002 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10004 ConstVCallList.push_back(ConstVCall);
10012 for (
auto I : IdToIndexMap) {
10013 auto &Ids = ForwardRefTypeIds[
I.first];
10014 for (
auto P :
I.second) {
10015 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10016 "Forward referenced type id GUID expected to be 0");
10017 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10027 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10029 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap,
Index))
10033 if (parseArgs(ConstVCall.
Args))
10046 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10061 IdToIndexMap[
ID].push_back(std::make_pair(
Index, Loc));
10063 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10065 parseUInt64(VFuncId.
GUID))
10071 parseUInt64(VFuncId.
Offset) ||
10100 assert(HasLinkage &&
"Linkage not optional in summary entry");
10107 parseOptionalVisibility(Flag);
10112 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10118 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10124 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10130 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
10135 return error(Lex.
getLoc(),
"expected gv flag type");
10157 auto ParseRest = [
this](
unsigned int &Val) {
10161 return parseFlag(Val);
10167 case lltok::kw_readonly:
10168 if (ParseRest(Flag))
10172 case lltok::kw_writeonly:
10173 if (ParseRest(Flag))
10178 if (ParseRest(Flag))
10183 if (ParseRest(Flag))
10188 return error(Lex.
getLoc(),
"expected gvar flag type");
10196bool LLParser::parseModuleReference(
StringRef &ModulePath) {
10204 auto I = ModuleIdMap.find(ModuleID);
10206 assert(
I != ModuleIdMap.end());
10207 ModulePath =
I->second;
10213bool LLParser::parseGVReference(
ValueInfo &VI,
unsigned &GVId) {
10216 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10222 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10224 VI = NumberedValueInfos[GVId];
10241bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10245 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
10260 if (parseAllocType(V))
10265 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
10269 std::vector<MIBInfo> MIBs;
10270 if (parseMemProfs(MIBs))
10273 Allocs.push_back({Versions, MIBs});
10290bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10294 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
10300 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
10309 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
10318 if (parseUInt64(StackId))
10340bool LLParser::parseAllocType(uint8_t &
AllocType) {
10348 case lltok::kw_cold:
10351 case lltok::kw_hot:
10355 return error(Lex.
getLoc(),
"invalid alloc type");
10368bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10372 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
10376 IdToIndexMapType IdToIndexMap;
10379 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
10388 if (parseGVReference(VI, GVId))
10392 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
10401 if (parseUInt32(V))
10407 parseToken(
lltok::comma,
"expected ',' in callsite") ||
10416 if (parseUInt64(StackId))
10428 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10429 Callsites.push_back({
VI, Clones, StackIdIndices});
10437 for (
auto I : IdToIndexMap) {
10438 auto &Infos = ForwardRefValueInfos[
I.first];
10439 for (
auto P :
I.second) {
10441 "Forward referenced ValueInfo expected to be empty");
10442 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
10446 if (parseToken(
lltok::rparen,
"expected ')' in callsites"))
static int64_t upperBound(StackOffset Size)
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Expand Atomic instructions
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live value
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
DenseMap< Block *, BlockRelaxAux > Blocks
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
llvm::cl::opt< bool > UseNewDbgInfoFormat
bool finalizeDebugInfoFormat(Module *M)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Module.h This file contains the declarations for the Module class.
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file provides utility classes that use RAII to save and restore values.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallPtrSet class.
static SymbolRef::Type getType(const Symbol *Sym)
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Class for arbitrary precision integers.
uint64_t getZExtValue() const
Get zero extended value.
unsigned getBitWidth() const
Return the number of bits in the APInt.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
bool getBoolValue() const
Convert APInt to a boolean value.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
An arbitrary precision integer that knows its signedness.
APSInt extOrTrunc(uint32_t width) const
APSInt extend(uint32_t width) const
an instruction to allocate memory on the stack
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
An instruction that atomically checks whether a specified value is in a memory location,...
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
an instruction that atomically reads a memory location, combines it with another value,...
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Min
*p = old <signed v ? old : v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
static StringRef getOperationName(BinOp Op)
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeList removeAttribute(LLVMContext &C, unsigned Index, StringRef Kind) const
AttributeList addFnAttributes(LLVMContext &C, const AttrBuilder &B) const
Add function attribute to the list.
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
AttributeList removeFnAttributes(LLVMContext &C, const AttributeMask &AttrsToRemove) const
Remove the specified attribute at the function index from this attribute list.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a binary instruction, given the opcode and the two operands.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static BranchInst * Create(BasicBlock *IfTrue, BasicBlock::iterator InsertBefore)
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr, BasicBlock::iterator InsertBefore)
void setTailCallKind(TailCallKind TCK)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name, BasicBlock::iterator InsertBefore)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, BasicBlock::iterator InsertBefore)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB, BasicBlock::iterator InsertBefore)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static ConstantInt * getFalse(LLVMContext &Context)
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents a range of values.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
Basic type, like 'int' or 'float'.
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations)
Build a DICompositeType with the given ODR identifier.
static std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Tagged DWARF-like metadata node.
static DIFlags getFlag(StringRef Flag)
String type, Fortran CHARACTER(n)
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
Type array for a subprogram.
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
This class represents an Operation in the Expression.
static Expected< DataLayout > parse(StringRef LayoutDescription)
Parse a data layout string and return the layout.
static DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Base class for non-instruction debug metadata records that have positions within IR.
Kind
Subclass discriminator.
static DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static constexpr ElementCount getFixed(ScalarTy MinVal)
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
Class representing an expression and its matching format.
This instruction compares its operands according to the predicate given to the constructor.
Convenience struct for specifying and reasoning about fast-math flags.
An instruction for ordering other memory operations.
This class represents a freeze function that returns random concrete value if an operand is either a ...
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
Type::subtype_iterator param_iterator
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setPrefixData(Constant *PrefixData)
static Intrinsic::ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Generic tagged DWARF-like metadata node.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
void setComdat(Comdat *C)
void setSection(StringRef S)
Change the section for this global.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
void setDSOLocal(bool Local)
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
void setVisibility(VisibilityTypes V)
void setSanitizerMetadata(SanitizerMetadata Meta)
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e....
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
void setPartition(StringRef Part)
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, BasicBlock::iterator InsertBefore)
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
static Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr, BasicBlock::iterator InsertBefore)
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, BasicBlock::iterator InsertBefore)
unsigned getUIntVal() const
lltok::Kind getKind() const
bool Error(LocTy ErrorLoc, const Twine &Msg) const
const std::string & getStrVal() const
const APSInt & getAPSIntVal() const
void setIgnoreColonInIdentifiers(bool val)
const APFloat & getAPFloatVal() const
LLVMContext & getContext()
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr, BasicBlock::iterator InsertBefore)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
An instruction for reading from memory.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
static MemoryEffectsBase readOnly()
Create MemoryEffectsBase that can read any memory.
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access argument memory.
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible memory.
static MemoryEffectsBase writeOnly()
Create MemoryEffectsBase that can write any memory.
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible or argument memory.
static MemoryEffectsBase none()
Create MemoryEffectsBase that cannot read or write any memory.
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
A Module instance is used to store all the information related to an LLVM module.
void addOperand(MDNode *M)
static NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, BasicBlock::iterator InsertBefore)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Resume the propagation of an exception.
static ResumeInst * Create(Value *Exn, BasicBlock::iterator InsertBefore)
static ReturnInst * Create(LLVMContext &C, Value *retVal, BasicBlock::iterator InsertBefore)
Represents a location in source code.
static const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr, BasicBlock::iterator InsertBefore, Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
ArrayRef< int > getShuffleMask() const
static bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
iterator find(StringRef Key)
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Class to represent struct types.
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
bool containsScalableVectorType(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, BasicBlock::iterator InsertBefore)
static TargetExtType * get(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types=std::nullopt, ArrayRef< unsigned > Ints=std::nullopt)
Return a target extension type having the specified name and optional type and integer parameters.
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
static IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
TypeID
Definitions of all of the base types for the Type system.
static Type * getLabelTy(LLVMContext &C)
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isAggregateType() const
Return true if the type is an aggregate type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static IntegerType * getInt8Ty(LLVMContext &C)
static Type * getTokenTy(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isFunctionTy() const
True if this is an instance of FunctionType.
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVoidTy() const
Return true if this is 'void'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name, BasicBlock::iterator InsertBefore)
Construct a unary instruction, given the opcode and an operand.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
void setName(const Twine &Name)
Change the name of the value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void deleteValue()
Delete a pointer to a generic Value.
StringRef getName() const
Return a constant reference to the value's name.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
unsigned getOperationEncoding(StringRef OperationEncodingString)
unsigned getAttributeEncoding(StringRef EncodingString)
unsigned getTag(StringRef TagString)
unsigned getCallingConvention(StringRef LanguageString)
unsigned getLanguage(StringRef LanguageString)
unsigned getVirtuality(StringRef VirtualityString)
unsigned getMacinfo(StringRef MacinfoString)
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
const CustomOperand< const MCSubtargetInfo & > Msg[]
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CXX_FAST_TLS
Used for access functions.
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
@ X86_StdCall
stdcall is mostly used by the Win32 API.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
@ X86_FastCall
'fast' analog of X86_StdCall.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
initializer< Ty > init(const Ty &Val)
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Linkage
Describes symbol linkage. This can be used to resolve definition clashes.
@ kw_no_sanitize_hwaddress
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_dso_local_equivalent
@ kw_aarch64_sme_preservemost_from_x2
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
void UpgradeSectionAttributes(Module &M)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
bool isPointerTy(const Type *T)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
@ ArgMem
Access to memory via argument pointers.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
Implement std::hash so that hash_code can be used in STL containers.
static const fltSemantics & IEEEsingle() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToEven
static const fltSemantics & IEEEdouble() LLVM_READNONE
static const fltSemantics & IEEEhalf() LLVM_READNONE
static const fltSemantics & BFloat() LLVM_READNONE
This struct is a compact representation of a valid (non-zero power of two) alignment.
Class to accumulate and hold information about a callee.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
A specification for a virtual function call with all constant integer arguments.
std::vector< uint64_t > Args
Flags specific to function summaries.
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
Describes the use of a value in a call instruction, specifying the call's target, the value's paramet...
Describes the uses of a parameter by the function.
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
All type identifier related information.
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
An "identifier" for a virtual function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
A utility class that uses RAII to save and restore the value of a variable.
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
std::map< unsigned, Type * > Types
StringMap< Type * > NamedTypes
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
NumberedValues< GlobalValue * > GlobalValues
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
enum llvm::ValID::@36 Kind
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
Utility type to build an inheritance chain that makes it easy to rank overload candidates.