65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
81 if (Context.shouldDiscardValueNames())
84 "Can't read textual IR with a Context that discards named Values");
87 if (parseTargetDefinitions(DataLayoutCallback))
91 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
97 restoreParsingState(Slots);
101 if (parseType(Ty) || parseConstantValue(Ty,
C))
104 return error(Lex.getLoc(),
"expected end of string");
110 restoreParsingState(Slots);
114 SMLoc Start = Lex.getLoc();
118 SMLoc End = Lex.getLoc();
126 restoreParsingState(Slots);
130 SMLoc Start = Lex.getLoc();
132 bool Status = parseDIExpressionBody(Result,
false);
133 SMLoc End = Lex.getLoc();
139void LLParser::restoreParsingState(
const SlotMapping *Slots) {
146 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
147 for (
const auto &
I : Slots->
Types)
148 NumberedTypes.insert(
149 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
155 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
162 if (MD->isTemporary())
166 assert(
II->use_empty() &&
"Cannot have uses");
167 II->eraseFromParent();
176void LLParser::dropUnknownMetadataReferences() {
177 auto Pred = [](
unsigned MDKind, MDNode *
Node) {
return Node->isTemporary(); };
178 for (Function &
F : *M) {
179 F.eraseMetadataIf(Pred);
181 I.eraseMetadataIf(Pred);
188 for (GlobalVariable &GV : M->globals())
189 GV.eraseMetadataIf(Pred);
192 [](
const auto &
E) {
return std::get<2>(
E)->isTemporary(); });
194 [](
const auto &
E) {
return std::get<2>(
E)->isTemporary(); });
199 if (
Info.first->getNumTemporaryUses() == 1) {
200 NumberedMetadata.erase(
ID);
201 ForwardRefMDNodes.erase(
ID);
214 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
215 "Mixed debug intrinsics/records seen without a parsing error?");
218 for (
const auto &RAG : ForwardRefAttrGroups) {
220 const std::vector<unsigned> &
Attrs = RAG.second;
221 AttrBuilder
B(Context);
223 for (
const auto &Attr : Attrs) {
224 auto R = NumberedAttrBuilders.find(Attr);
225 if (R != NumberedAttrBuilders.end())
230 AttributeList AS = Fn->getAttributes();
231 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
232 AS = AS.removeFnAttributes(Context);
238 if (MaybeAlign
A = FnAttrs.getAlignment()) {
239 Fn->setAlignment(*
A);
240 FnAttrs.removeAttribute(Attribute::Alignment);
243 AS = AS.addFnAttributes(Context, FnAttrs);
244 Fn->setAttributes(AS);
246 AttributeList AS = CI->getAttributes();
247 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
248 AS = AS.removeFnAttributes(Context);
250 AS = AS.addFnAttributes(Context, FnAttrs);
251 CI->setAttributes(AS);
253 AttributeList AS =
II->getAttributes();
254 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
255 AS = AS.removeFnAttributes(Context);
257 AS = AS.addFnAttributes(Context, FnAttrs);
258 II->setAttributes(AS);
260 AttributeList AS = CBI->getAttributes();
261 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
262 AS = AS.removeFnAttributes(Context);
264 AS = AS.addFnAttributes(Context, FnAttrs);
265 CBI->setAttributes(AS);
267 AttrBuilder
Attrs(M->getContext(), GV->getAttributes());
277 if (!ForwardRefBlockAddresses.empty())
278 return error(ForwardRefBlockAddresses.begin()->first.Loc,
279 "expected function name in blockaddress");
281 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
282 GlobalValue *FwdRef) {
283 GlobalValue *GV =
nullptr;
285 GV = M->getNamedValue(GVRef.
StrVal);
287 GV = NumberedVals.get(GVRef.
UIntVal);
292 "' referenced by dso_local_equivalent");
296 "expected a function, alias to function, or ifunc "
297 "in dso_local_equivalent");
300 FwdRef->replaceAllUsesWith(Equiv);
301 FwdRef->eraseFromParent();
308 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
309 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
312 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
313 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
316 ForwardRefDSOLocalEquivalentIDs.clear();
317 ForwardRefDSOLocalEquivalentNames.clear();
319 for (
const auto &NT : NumberedTypes)
320 if (
NT.second.second.isValid())
322 "use of undefined type '%" + Twine(
NT.first) +
"'");
324 for (
const auto &[Name, TypeInfo] : NamedTypes)
325 if (TypeInfo.second.isValid())
326 return error(TypeInfo.second,
327 "use of undefined type named '" + Name +
"'");
329 if (!ForwardRefComdats.empty())
330 return error(ForwardRefComdats.begin()->second,
331 "use of undefined comdat '$" +
332 ForwardRefComdats.begin()->first +
"'");
335 dropUnknownMetadataReferences();
337 if (!ForwardRefMDNodes.empty())
338 return error(ForwardRefMDNodes.begin()->second.second,
339 "use of undefined metadata '!" +
340 Twine(ForwardRefMDNodes.begin()->first) +
"'");
343 for (
auto [Loc, DR, MD] : PendingDbgRecords) {
347 return error(Loc,
"invalid debug location");
349 PendingDbgRecords.clear();
350 for (
auto [Loc,
I, MD] : PendingDbgInsts) {
354 return error(Loc,
"invalid !dbg metadata");
356 PendingDbgInsts.clear();
370 if (!CB || !CB->isCallee(&U))
371 return error(
Info.second,
"intrinsic can only be used as callee");
373 std::string ErrorMsg;
374 raw_string_ostream ErrorOS(ErrorMsg);
388 return error(
Info.second,
"unknown intrinsic '" + Name +
"'");
399 Info.first->eraseFromParent();
400 ForwardRefVals.erase(Name);
409 auto GetCommonFunctionType = [](
Value *
V) -> FunctionType * {
410 FunctionType *FTy =
nullptr;
411 for (Use &U :
V->uses()) {
413 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
415 FTy = CB->getFunctionType();
423 Type *Ty = GetCommonFunctionType(
Info.first);
431 GV =
new GlobalVariable(*M, Ty,
false,
434 Info.first->replaceAllUsesWith(GV);
435 Info.first->eraseFromParent();
436 ForwardRefVals.erase(Name);
439 if (!ForwardRefVals.empty())
440 return error(ForwardRefVals.begin()->second.second,
441 "use of undefined value '@" + ForwardRefVals.begin()->first +
444 if (!ForwardRefValIDs.empty())
445 return error(ForwardRefValIDs.begin()->second.second,
446 "use of undefined value '@" +
447 Twine(ForwardRefValIDs.begin()->first) +
"'");
450 for (
auto &
N : NumberedMetadata) {
451 if (
N.second && !
N.second->isResolved())
452 N.second->resolveCycles();
456 NewDistinctSPs.clear();
458 for (
auto *Inst : InstsWithTBAATag) {
459 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
462 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
465 if (MD != UpgradedMD)
466 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
475 if (UpgradeDebugInfo)
489 Slots->GlobalValues = std::move(NumberedVals);
490 Slots->MetadataNodes = std::move(NumberedMetadata);
491 for (
const auto &
I : NamedTypes)
492 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
493 for (
const auto &
I : NumberedTypes)
494 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
500bool LLParser::validateEndOfIndex() {
504 if (!ForwardRefValueInfos.empty())
505 return error(ForwardRefValueInfos.begin()->second.front().second,
506 "use of undefined summary '^" +
507 Twine(ForwardRefValueInfos.begin()->first) +
"'");
509 if (!ForwardRefAliasees.empty())
510 return error(ForwardRefAliasees.begin()->second.front().second,
511 "use of undefined summary '^" +
512 Twine(ForwardRefAliasees.begin()->first) +
"'");
514 if (!ForwardRefTypeIds.empty())
515 return error(ForwardRefTypeIds.begin()->second.front().second,
516 "use of undefined type id summary '^" +
517 Twine(ForwardRefTypeIds.begin()->first) +
"'");
531 std::string TentativeDLStr = M->getDataLayoutStr();
536 switch (Lex.getKind()) {
538 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
542 if (parseSourceFileName())
551 if (
auto LayoutOverride =
552 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
553 TentativeDLStr = *LayoutOverride;
559 M->setDataLayout(MaybeDL.
get());
563bool LLParser::parseTopLevelEntities() {
567 switch (Lex.getKind()) {
571 if (parseSummaryEntry())
575 if (parseSourceFileName())
585 switch (Lex.getKind()) {
587 return tokError(
"expected top-level entity");
598 if (parseModuleAsm())
602 if (parseUnnamedType())
606 if (parseNamedType())
610 if (parseUnnamedGlobal())
614 if (parseNamedGlobal())
619 if (parseStandaloneMetadata())
623 if (parseSummaryEntry())
627 if (parseNamedMetadata())
631 if (parseUnnamedAttrGrp())
635 if (parseUseListOrder())
644bool LLParser::parseModuleAsm() {
650 parseStringConstant(AsmStr))
653 M->appendModuleInlineAsm(AsmStr);
660bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
666 return tokError(
"unknown target property");
669 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
670 parseStringConstant(Str))
672 M->setTargetTriple(Triple(std::move(Str)));
676 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
678 DLStrLoc = Lex.getLoc();
679 if (parseStringConstant(TentativeDLStr))
687bool LLParser::parseSourceFileName() {
690 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
691 parseStringConstant(SourceFileName))
694 M->setSourceFileName(SourceFileName);
700bool LLParser::parseUnnamedType() {
701 LocTy TypeLoc = Lex.getLoc();
702 unsigned TypeID = Lex.getUIntVal();
705 if (parseToken(
lltok::equal,
"expected '=' after name") ||
710 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
714 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
716 return error(TypeLoc,
"non-struct types may not be recursive");
718 Entry.second = SMLoc();
726bool LLParser::parseNamedType() {
727 std::string
Name = Lex.getStrVal();
728 LocTy NameLoc = Lex.getLoc();
731 if (parseToken(
lltok::equal,
"expected '=' after name") ||
736 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
740 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
742 return error(NameLoc,
"non-struct types may not be recursive");
744 Entry.second = SMLoc();
752bool LLParser::parseDeclare() {
756 std::vector<std::pair<unsigned, MDNode *>> MDs;
760 if (parseMetadataAttachment(MDK,
N))
762 MDs.push_back({MDK,
N});
766 unsigned FunctionNumber = -1;
767 SmallVector<unsigned> UnnamedArgNums;
768 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
771 F->addMetadata(MD.first, *MD.second);
777bool LLParser::parseDefine() {
780 FileLoc FunctionStart = getTokLineColumnPos();
784 unsigned FunctionNumber = -1;
785 SmallVector<unsigned> UnnamedArgNums;
787 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
788 parseOptionalFunctionMetadata(*
F) ||
789 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
791 ParserContext->addFunctionLocation(
792 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
800bool LLParser::parseGlobalType(
bool &IsConstant) {
807 return tokError(
"expected 'global' or 'constant'");
813bool LLParser::parseOptionalUnnamedAddr(
834bool LLParser::parseUnnamedGlobal() {
837 LocTy NameLoc = Lex.getLoc();
841 VarID = Lex.getUIntVal();
842 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
846 if (parseToken(
lltok::equal,
"expected '=' after name"))
849 VarID = NumberedVals.getNext();
853 unsigned Linkage, Visibility, DLLStorageClass;
857 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
859 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
862 switch (Lex.getKind()) {
864 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
865 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
868 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
869 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
878bool LLParser::parseNamedGlobal() {
880 LocTy NameLoc = Lex.getLoc();
881 std::string
Name = Lex.getStrVal();
885 unsigned Linkage, Visibility, DLLStorageClass;
889 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
890 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
892 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
895 switch (Lex.getKind()) {
897 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
898 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
901 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
902 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
906bool LLParser::parseComdat() {
908 std::string
Name = Lex.getStrVal();
909 LocTy NameLoc = Lex.getLoc();
916 return tokError(
"expected comdat type");
919 switch (Lex.getKind()) {
921 return tokError(
"unknown selection kind");
943 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
944 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
947 if (
I != ComdatSymTab.
end())
950 C = M->getOrInsertComdat(Name);
951 C->setSelectionKind(SK);
958bool LLParser::parseMDString(
MDString *&Result) {
960 if (parseStringConstant(Str))
968bool LLParser::parseMDNodeID(
MDNode *&Result) {
970 LocTy IDLoc = Lex.getLoc();
972 if (parseUInt32(MID))
976 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
983 auto &FwdRef = ForwardRefMDNodes[MID];
986 Result = FwdRef.first.get();
987 It->second.reset(Result);
993bool LLParser::parseNamedMetadata() {
995 std::string
Name = Lex.getStrVal();
1003 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1006 MDNode *
N =
nullptr;
1011 Lex.getStrVal() ==
"DIExpression") {
1012 if (parseDIExpression(
N,
false))
1017 Lex.getStrVal() ==
"DIArgList") {
1018 return tokError(
"found DIArgList outside of function");
1026 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1031bool LLParser::parseStandaloneMetadata() {
1034 unsigned MetadataID = 0;
1037 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1042 return tokError(
"unexpected type in metadata definition");
1046 if (parseSpecializedMDNode(Init, IsDistinct))
1049 parseMDTuple(Init, IsDistinct))
1053 auto FI = ForwardRefMDNodes.find(MetadataID);
1054 if (FI != ForwardRefMDNodes.end()) {
1055 auto *ToReplace = FI->second.first.get();
1059 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1060 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1061 "Inst unexpectedly already has DIAssignID attachment");
1062 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1066 ToReplace->replaceAllUsesWith(Init);
1067 ForwardRefMDNodes.erase(FI);
1069 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1071 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1073 return tokError(
"Metadata id is already used");
1074 It->second.reset(Init);
1081bool LLParser::skipModuleSummaryEntry() {
1091 return tokError(
"Expected 'gv', 'module', 'typeid', "
1092 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1093 "start of summary entry");
1095 return parseSummaryIndexFlags();
1097 return parseBlockCount();
1099 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1100 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1104 unsigned NumOpenParen = 1;
1106 switch (Lex.getKind()) {
1114 return tokError(
"found end of file while parsing summary entry");
1120 }
while (NumOpenParen > 0);
1126bool LLParser::parseSummaryEntry() {
1132 Lex.setIgnoreColonInIdentifiers(
true);
1140 return skipModuleSummaryEntry();
1142 bool result =
false;
1143 switch (Lex.getKind()) {
1145 result = parseGVEntry(SummaryID);
1148 result = parseModuleEntry(SummaryID);
1151 result = parseTypeIdEntry(SummaryID);
1154 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1157 result = parseSummaryIndexFlags();
1160 result = parseBlockCount();
1163 result =
error(Lex.getLoc(),
"unexpected summary kind");
1166 Lex.setIgnoreColonInIdentifiers(
false);
1200bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1201 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1202 unsigned DLLStorageClass,
bool DSOLocal,
1217 return error(NameLoc,
"invalid linkage type for alias");
1220 return error(NameLoc,
1221 "symbol with local linkage must have default visibility");
1224 return error(NameLoc,
1225 "symbol with local linkage cannot have a DLL storage class");
1228 LocTy ExplicitTypeLoc = Lex.getLoc();
1229 if (parseType(Ty) ||
1230 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1234 LocTy AliaseeLoc = Lex.getLoc();
1239 if (parseGlobalTypeAndValue(Aliasee))
1244 if (parseValID(
ID,
nullptr))
1247 return error(AliaseeLoc,
"invalid aliasee");
1248 Aliasee =
ID.ConstantVal;
1254 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1255 unsigned AddrSpace = PTy->getAddressSpace();
1257 GlobalValue *GVal =
nullptr;
1261 if (!
Name.empty()) {
1262 auto I = ForwardRefVals.find(Name);
1263 if (
I != ForwardRefVals.end()) {
1264 GVal =
I->second.first;
1265 ForwardRefVals.erase(Name);
1266 }
else if (M->getNamedValue(Name)) {
1267 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1270 auto I = ForwardRefValIDs.find(NameID);
1271 if (
I != ForwardRefValIDs.end()) {
1272 GVal =
I->second.first;
1273 ForwardRefValIDs.erase(
I);
1278 std::unique_ptr<GlobalAlias> GA;
1279 std::unique_ptr<GlobalIFunc> GI;
1307 if (parseGlobalObjectMetadataAttachment(*GI))
1310 return tokError(
"unknown alias or ifunc property!");
1315 NumberedVals.add(NameID, GV);
1322 "forward reference and definition of alias have different types");
1332 M->insertAlias(GA.release());
1334 M->insertIFunc(GI.release());
1335 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1344 case lltok::kw_sanitize_memtag:
1358 switch (Lex.getKind()) {
1360 Meta.NoAddress =
true;
1363 Meta.NoHWAddress =
true;
1365 case lltok::kw_sanitize_memtag:
1369 Meta.IsDynInit =
true;
1372 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1392bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1393 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1394 unsigned Visibility,
unsigned DLLStorageClass,
1398 return error(NameLoc,
1399 "symbol with local linkage must have default visibility");
1402 return error(NameLoc,
1403 "symbol with local linkage cannot have a DLL storage class");
1407 LocTy IsExternallyInitializedLoc;
1411 if (parseOptionalAddrSpace(AddrSpace) ||
1413 IsExternallyInitialized,
1414 &IsExternallyInitializedLoc) ||
1415 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1424 if (parseGlobalValue(Ty, Init))
1429 return error(TyLoc,
"invalid type for global variable");
1431 GlobalValue *GVal =
nullptr;
1434 if (!
Name.empty()) {
1435 auto I = ForwardRefVals.find(Name);
1436 if (
I != ForwardRefVals.end()) {
1437 GVal =
I->second.first;
1438 ForwardRefVals.erase(
I);
1439 }
else if (M->getNamedValue(Name)) {
1440 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1445 if (NameID == (
unsigned)-1)
1446 NameID = NumberedVals.getNext();
1448 auto I = ForwardRefValIDs.find(NameID);
1449 if (
I != ForwardRefValIDs.end()) {
1450 GVal =
I->second.first;
1451 ForwardRefValIDs.erase(
I);
1455 GlobalVariable *GV =
new GlobalVariable(
1460 NumberedVals.add(NameID, GV);
1478 "forward reference and definition of global have different types");
1498 }
else if (Lex.getKind() == lltok::kw_align) {
1499 MaybeAlign Alignment;
1500 if (parseOptionalAlignment(Alignment))
1506 if (parseOptionalCodeModel(CodeModel))
1510 if (parseGlobalObjectMetadataAttachment(*GV))
1513 if (parseSanitizer(GV))
1517 if (parseOptionalComdat(Name,
C))
1522 return tokError(
"unknown global variable property!");
1526 AttrBuilder
Attrs(M->getContext());
1528 std::vector<unsigned> FwdRefAttrGrps;
1529 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1531 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1533 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1541bool LLParser::parseUnnamedAttrGrp() {
1543 LocTy AttrGrpLoc = Lex.getLoc();
1547 return tokError(
"expected attribute group id");
1549 unsigned VarID = Lex.getUIntVal();
1550 std::vector<unsigned> unused;
1558 auto R = NumberedAttrBuilders.find(
VarID);
1559 if (R == NumberedAttrBuilders.end())
1560 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1562 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1563 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1566 if (!
R->second.hasAttributes())
1567 return error(AttrGrpLoc,
"attribute group has no attributes");
1574#define GET_ATTR_NAMES
1575#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1576 case lltok::kw_##DISPLAY_NAME: \
1577 return Attribute::ENUM_NAME;
1578#include "llvm/IR/Attributes.inc"
1587 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1590 case Attribute::Alignment: {
1591 MaybeAlign Alignment;
1599 if (parseOptionalAlignment(Alignment,
true))
1602 B.addAlignmentAttr(Alignment);
1605 case Attribute::StackAlignment: {
1610 parseUInt32(Alignment))
1613 if (parseOptionalStackAlignment(Alignment))
1616 B.addStackAlignmentAttr(Alignment);
1619 case Attribute::AllocSize: {
1620 unsigned ElemSizeArg;
1621 std::optional<unsigned> NumElemsArg;
1622 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1624 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1627 case Attribute::VScaleRange: {
1628 unsigned MinValue, MaxValue;
1629 if (parseVScaleRangeArguments(MinValue, MaxValue))
1631 B.addVScaleRangeAttr(MinValue,
1632 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1635 case Attribute::Dereferenceable: {
1636 std::optional<uint64_t> Bytes;
1637 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1639 assert(Bytes.has_value());
1640 B.addDereferenceableAttr(Bytes.value());
1643 case Attribute::DeadOnReturn: {
1644 std::optional<uint64_t> Bytes;
1645 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1648 if (Bytes.has_value()) {
1649 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1651 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1655 case Attribute::DereferenceableOrNull: {
1656 std::optional<uint64_t> Bytes;
1657 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1659 assert(Bytes.has_value());
1660 B.addDereferenceableOrNullAttr(Bytes.value());
1663 case Attribute::UWTable: {
1665 if (parseOptionalUWTableKind(Kind))
1667 B.addUWTableAttr(Kind);
1670 case Attribute::AllocKind: {
1672 if (parseAllocKind(Kind))
1674 B.addAllocKindAttr(Kind);
1677 case Attribute::Memory: {
1678 std::optional<MemoryEffects> ME = parseMemoryAttr();
1681 B.addMemoryAttr(*ME);
1684 case Attribute::DenormalFPEnv: {
1685 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1689 B.addDenormalFPEnvAttr(*
Mode);
1692 case Attribute::NoFPClass: {
1695 B.addNoFPClassAttr(NoFPClass);
1701 case Attribute::Range:
1702 return parseRangeAttr(
B);
1703 case Attribute::Initializes:
1704 return parseInitializesAttr(
B);
1705 case Attribute::Captures:
1706 return parseCapturesAttr(
B);
1708 B.addAttribute(Attr);
1716 case lltok::kw_readnone:
1719 case lltok::kw_readonly:
1722 case lltok::kw_writeonly:
1741bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1742 std::vector<unsigned> &FwdRefAttrGrps,
1743 bool InAttrGrp, LocTy &BuiltinLoc) {
1744 bool HaveError =
false;
1755 if (parseStringAttribute(
B))
1767 "cannot have an attribute group reference in an attribute group");
1770 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1776 SMLoc Loc = Lex.getLoc();
1777 if (Token == lltok::kw_builtin)
1789 return error(Lex.getLoc(),
"unterminated attribute group");
1792 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1799 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1803 B.addMemoryAttr(ME);
1817 PTy->getAddressSpace());
1826 error(Loc,
"'" + Name +
"' is not a basic block");
1828 error(Loc,
"'" + Name +
"' defined with type '" +
1841 error(Loc,
"global variable reference must have pointer type");
1852 auto I = ForwardRefVals.find(Name);
1853 if (
I != ForwardRefVals.end())
1854 Val =
I->second.first;
1860 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1864 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1871 error(Loc,
"global variable reference must have pointer type");
1875 GlobalValue *Val = NumberedVals.get(
ID);
1880 auto I = ForwardRefValIDs.find(
ID);
1881 if (
I != ForwardRefValIDs.end())
1882 Val =
I->second.first;
1888 checkValidVariableType(Loc,
"@" + Twine(
ID), Ty, Val));
1892 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1900Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
1904 if (
I != ComdatSymTab.
end())
1908 Comdat *
C = M->getOrInsertComdat(Name);
1909 ForwardRefComdats[
Name] = Loc;
1919bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1920 if (Lex.getKind() !=
T)
1921 return tokError(ErrMsg);
1928bool LLParser::parseStringConstant(std::string &Result) {
1930 return tokError(
"expected string constant");
1931 Result = Lex.getStrVal();
1938bool LLParser::parseUInt32(uint32_t &Val) {
1939 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1940 return tokError(
"expected integer");
1941 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1942 if (Val64 !=
unsigned(Val64))
1943 return tokError(
"expected 32-bit integer (too large)");
1951bool LLParser::parseUInt64(uint64_t &Val) {
1952 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1953 return tokError(
"expected integer");
1954 Val = Lex.getAPSIntVal().getLimitedValue();
1964 switch (Lex.getKind()) {
1966 return tokError(
"expected localdynamic, initialexec or localexec");
1994 return parseTLSModel(TLM) ||
1995 parseToken(
lltok::rparen,
"expected ')' after thread local model");
2003bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
2004 AddrSpace = DefaultAS;
2008 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
2010 const std::string &AddrSpaceStr = Lex.getStrVal();
2011 if (AddrSpaceStr ==
"A") {
2012 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2013 }
else if (AddrSpaceStr ==
"G") {
2014 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2015 }
else if (AddrSpaceStr ==
"P") {
2016 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2017 }
else if (std::optional<unsigned> AS =
2018 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2021 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2027 return tokError(
"expected integer or string constant");
2028 SMLoc Loc = Lex.getLoc();
2029 if (parseUInt32(AddrSpace))
2032 return error(Loc,
"invalid address space, must be a 24-bit integer");
2036 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2037 ParseAddrspaceValue(AddrSpace) ||
2044bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2045 std::string Attr = Lex.getStrVal();
2048 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2050 B.addAttribute(Attr, Val);
2055bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2056 bool HaveError =
false;
2063 if (parseStringAttribute(
B))
2074 SMLoc Loc = Lex.getLoc();
2079 if (parseEnumAttribute(Attr,
B,
false))
2083 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2085 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2133bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2134 unsigned &Visibility,
2135 unsigned &DLLStorageClass,
bool &DSOLocal) {
2139 parseOptionalDSOLocal(DSOLocal);
2140 parseOptionalVisibility(Visibility);
2141 parseOptionalDLLStorageClass(DLLStorageClass);
2144 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2150void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2151 switch (Lex.getKind()) {
2172void LLParser::parseOptionalVisibility(
unsigned &Res) {
2173 switch (Lex.getKind()) {
2190bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2194 return tokError(
"unknown import kind. Expect definition or declaration.");
2209void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2210 switch (Lex.getKind()) {
2280bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2281 switch (Lex.getKind()) {
2368 return tokError(
"unknown RISC-V ABI VLEN");
2369#define CC_VLS_CASE(ABIVlen) \
2371 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2399 return parseUInt32(CC);
2409bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2412 std::string
Name = Lex.getStrVal();
2413 Kind = M->getMDKindID(Name);
2416 return parseMDNode(MD);
2421bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2424 return tokError(
"expected metadata after comma");
2428 auto Loc = Lex.getLoc();
2429 if (parseMetadataAttachment(MDK,
N))
2432 if (MDK == LLVMContext::MD_DIAssignID)
2433 TempDIAssignIDAttachments[
N].push_back(&Inst);
2434 else if (MDK == LLVMContext::MD_dbg)
2435 PendingDbgInsts.emplace_back(Loc, &Inst,
N);
2439 if (MDK == LLVMContext::MD_tbaa)
2440 InstsWithTBAATag.push_back(&Inst);
2449bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2452 if (parseMetadataAttachment(MDK,
N))
2461bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2463 if (parseGlobalObjectMetadataAttachment(
F))
2471bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2472 Alignment = std::nullopt;
2473 if (!EatIfPresent(lltok::kw_align))
2475 LocTy AlignLoc = Lex.getLoc();
2478 LocTy ParenLoc = Lex.getLoc();
2479 bool HaveParens =
false;
2485 if (parseUInt64(
Value))
2489 return error(ParenLoc,
"expected ')'");
2492 return error(AlignLoc,
"alignment is not a power of two");
2494 return error(AlignLoc,
"huge alignments are not supported yet");
2502bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2503 Alignment = std::nullopt;
2506 LocTy AlignLoc = Lex.getLoc();
2509 LocTy ParenLoc = Lex.getLoc();
2511 return error(ParenLoc,
"expected '('");
2513 if (parseUInt64(
Value))
2516 ParenLoc = Lex.getLoc();
2518 return error(ParenLoc,
"expected ')'");
2521 return error(AlignLoc,
"alignment is not a power of two");
2523 return error(AlignLoc,
"huge alignments are not supported yet");
2533 auto StrVal = Lex.getStrVal();
2534 auto ErrMsg =
"expected global code model string";
2535 if (StrVal ==
"tiny")
2537 else if (StrVal ==
"small")
2539 else if (StrVal ==
"kernel")
2541 else if (StrVal ==
"medium")
2543 else if (StrVal ==
"large")
2546 return tokError(ErrMsg);
2558bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2559 std::optional<uint64_t> &Bytes,
2560 bool ErrorNoBytes) {
2561 assert((AttrKind == lltok::kw_dereferenceable ||
2562 AttrKind == lltok::kw_dereferenceable_or_null ||
2563 AttrKind == lltok::kw_dead_on_return) &&
2567 if (!EatIfPresent(AttrKind))
2569 LocTy ParenLoc = Lex.getLoc();
2572 return error(ParenLoc,
"expected '('");
2573 Bytes = std::nullopt;
2576 LocTy DerefLoc = Lex.getLoc();
2577 if (parseUInt64(Bytes.value()))
2579 ParenLoc = Lex.getLoc();
2581 return error(ParenLoc,
"expected ')'");
2583 return error(DerefLoc,
"byte count specified must be non-zero");
2587bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2592 LocTy KindLoc = Lex.getLoc();
2598 return error(KindLoc,
"expected unwind table kind");
2605 LocTy ParenLoc = Lex.getLoc();
2607 return error(ParenLoc,
"expected '('");
2608 LocTy KindLoc = Lex.getLoc();
2610 if (parseStringConstant(Arg))
2611 return error(KindLoc,
"expected allockind value");
2615 }
else if (
A ==
"realloc") {
2617 }
else if (
A ==
"free") {
2619 }
else if (
A ==
"uninitialized") {
2621 }
else if (
A ==
"zeroed") {
2623 }
else if (
A ==
"aligned") {
2626 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2629 ParenLoc = Lex.getLoc();
2631 return error(ParenLoc,
"expected ')'");
2633 return error(KindLoc,
"expected allockind value");
2642 return {Loc::ArgMem};
2644 return {Loc::InaccessibleMem};
2646 return {Loc::ErrnoMem};
2648 return {Loc::TargetMem0};
2650 return {Loc::TargetMem1};
2673 return std::nullopt;
2677static std::optional<DenormalMode::DenormalModeKind>
2689 return std::nullopt;
2693std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2698 Lex.setIgnoreColonInIdentifiers(
true);
2703 tokError(
"expected '('");
2704 return std::nullopt;
2707 bool SeenLoc =
false;
2708 bool SeenTargetLoc =
false;
2711 if (!Locs.
empty()) {
2714 tokError(
"expected ':' after location");
2715 return std::nullopt;
2722 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2723 "or access kind (none, read, write, readwrite)");
2725 tokError(
"expected access kind (none, read, write, readwrite)");
2726 return std::nullopt;
2730 if (!Locs.
empty()) {
2735 SeenTargetLoc =
true;
2737 if (Locs.size() > 1 && SeenTargetLoc) {
2738 tokError(
"target memory default access kind must be specified first");
2739 return std::nullopt;
2744 tokError(
"default access kind must be specified first");
2745 return std::nullopt;
2754 tokError(
"unterminated memory attribute");
2755 return std::nullopt;
2758std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2759 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2762 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2763 "positivezero, dynamic)");
2769 std::optional<DenormalMode::DenormalModeKind> InputMode;
2773 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2774 "positivezero, dynamic)");
2781 InputMode = OutputMode;
2784 return DenormalMode(*OutputMode, *InputMode);
2787std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2790 Lex.setIgnoreColonInIdentifiers(
true);
2801 bool HasDefaultSection =
false;
2803 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2804 if (!ParsedDefaultMode)
2806 DefaultMode = *ParsedDefaultMode;
2807 HasDefaultSection =
true;
2812 if (HasDefaultSection && !HasComma) {
2813 tokError(
"expected ',' before float:");
2818 if (parseType(Ty) || !Ty->
isFloatTy()) {
2819 tokError(
"expected float:");
2823 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2826 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2830 F32Mode = *ParsedF32Mode;
2833 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2836 return DenormalFPEnv(DefaultMode, F32Mode);
2878unsigned LLParser::parseNoFPClassAttr() {
2883 tokError(
"expected '('");
2890 if (TestMask != 0) {
2894 !parseUInt64(
Value)) {
2896 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
2901 error(Lex.getLoc(),
"expected ')'");
2907 error(Lex.getLoc(),
"expected nofpclass test mask");
2925bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2926 bool &AteExtraComma) {
2927 AteExtraComma =
false;
2931 AteExtraComma =
true;
2935 if (Lex.getKind() != lltok::kw_align)
2936 return error(Lex.getLoc(),
"expected metadata or 'align'");
2938 if (parseOptionalAlignment(Alignment))
2951bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
2952 bool &AteExtraComma) {
2953 AteExtraComma =
false;
2957 AteExtraComma =
true;
2963 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
2965 if (parseOptionalAddrSpace(AddrSpace))
2972bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2973 std::optional<unsigned> &HowManyArg) {
2976 auto StartParen = Lex.getLoc();
2978 return error(StartParen,
"expected '('");
2980 if (parseUInt32(BaseSizeArg))
2984 auto HowManyAt = Lex.getLoc();
2986 if (parseUInt32(HowMany))
2988 if (HowMany == BaseSizeArg)
2989 return error(HowManyAt,
2990 "'allocsize' indices can't refer to the same parameter");
2991 HowManyArg = HowMany;
2993 HowManyArg = std::nullopt;
2995 auto EndParen = Lex.getLoc();
2997 return error(EndParen,
"expected ')'");
3001bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
3002 unsigned &MaxValue) {
3005 auto StartParen = Lex.getLoc();
3007 return error(StartParen,
"expected '('");
3009 if (parseUInt32(MinValue))
3013 if (parseUInt32(MaxValue))
3016 MaxValue = MinValue;
3018 auto EndParen = Lex.getLoc();
3020 return error(EndParen,
"expected ')'");
3029bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3034 return parseScope(SSID) || parseOrdering(Ordering);
3044 auto StartParenAt = Lex.getLoc();
3046 return error(StartParenAt,
"Expected '(' in syncscope");
3049 auto SSNAt = Lex.getLoc();
3050 if (parseStringConstant(SSN))
3051 return error(SSNAt,
"Expected synchronization scope name");
3053 auto EndParenAt = Lex.getLoc();
3055 return error(EndParenAt,
"Expected ')' in syncscope");
3057 SSID = Context.getOrInsertSyncScopeID(SSN);
3068 switch (Lex.getKind()) {
3070 return tokError(
"Expected ordering on atomic instruction");
3089bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3091 if (!EatIfPresent(lltok::kw_alignstack))
3093 LocTy ParenLoc = Lex.getLoc();
3095 return error(ParenLoc,
"expected '('");
3096 LocTy AlignLoc = Lex.getLoc();
3097 if (parseUInt32(Alignment))
3099 ParenLoc = Lex.getLoc();
3101 return error(ParenLoc,
"expected ')'");
3103 return error(AlignLoc,
"stack alignment is not a power of two");
3117 bool &AteExtraComma) {
3118 AteExtraComma =
false;
3121 return tokError(
"expected ',' as start of index list");
3125 if (Indices.
empty())
3126 return tokError(
"expected index");
3127 AteExtraComma =
true;
3131 if (parseUInt32(Idx))
3144bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
3145 SMLoc TypeLoc = Lex.getLoc();
3146 switch (Lex.getKind()) {
3148 return tokError(Msg);
3157 if (
Result->isPointerTy()) {
3159 if (parseOptionalAddrSpace(AddrSpace))
3165 return tokError(
"ptr* is invalid - use ptr instead");
3176 if (parseTargetExtType(Result))
3182 if (parseAnonStructType(Result,
false))
3188 if (parseArrayVectorType(Result,
false))
3195 if (parseAnonStructType(Result,
true) ||
3196 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3198 }
else if (parseArrayVectorType(Result,
true))
3203 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3209 Entry.second = Lex.getLoc();
3218 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3224 Entry.second = Lex.getLoc();
3234 switch (Lex.getKind()) {
3237 if (!AllowVoid &&
Result->isVoidTy())
3238 return error(TypeLoc,
"void type only allowed for function results");
3244 return tokError(
"basic block pointers are invalid");
3246 return tokError(
"pointers to void are invalid - use i8* instead");
3248 return tokError(
"pointer to this type is invalid");
3256 return tokError(
"basic block pointers are invalid");
3258 return tokError(
"pointers to void are invalid; use i8* instead");
3260 return tokError(
"pointer to this type is invalid");
3262 if (parseOptionalAddrSpace(AddrSpace) ||
3263 parseToken(
lltok::star,
"expected '*' in address space"))
3272 if (parseFunctionType(Result))
3285 PerFunctionState &PFS,
bool IsMustTailCall,
3286 bool InVarArgsFunc) {
3292 if (!ArgList.
empty() &&
3293 parseToken(
lltok::comma,
"expected ',' in argument list"))
3298 const char *Msg =
"unexpected ellipsis in argument list for ";
3299 if (!IsMustTailCall)
3300 return tokError(Twine(Msg) +
"non-musttail call");
3302 return tokError(Twine(Msg) +
"musttail call in non-varargs function");
3304 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3309 Type *ArgTy =
nullptr;
3311 if (parseType(ArgTy, ArgLoc))
3314 return error(ArgLoc,
"invalid type for function argument");
3316 AttrBuilder ArgAttrs(M->getContext());
3319 if (parseMetadataAsValue(V, PFS))
3323 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3330 if (IsMustTailCall && InVarArgsFunc)
3331 return tokError(
"expected '...' at end of argument list for musttail call "
3332 "in varargs function");
3340bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3343 if (!EatIfPresent(AttrToken))
3346 return error(Lex.getLoc(),
"expected '('");
3350 return error(Lex.getLoc(),
"expected ')'");
3352 B.addTypeAttr(AttrKind, Ty);
3358bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3366 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3368 return tokError(
"expected integer");
3369 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3371 "integer is too large for the bit width of specified type");
3372 Val = Lex.getAPSIntVal().extend(
BitWidth);
3377 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3380 return error(TyLoc,
"the range must have integer type!");
3388 return tokError(
"the range represent the empty set but limits aren't 0!");
3399bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3402 auto ParseAPSInt = [&](APInt &Val) {
3404 return tokError(
"expected integer");
3405 Val = Lex.getAPSIntVal().extend(64);
3425 return tokError(
"the range should not represent the full or empty set!");
3437 if (!CRLOrNull.has_value())
3438 return tokError(
"Invalid (unordered or overlapping) range list");
3439 B.addInitializesAttr(*CRLOrNull);
3443bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3445 std::optional<CaptureComponents> Ret;
3449 Lex.setIgnoreColonInIdentifiers(
true);
3457 bool SeenComponent =
false;
3463 return tokError(
"duplicate 'ret' location");
3466 SeenComponent =
false;
3471 return tokError(
"cannot use 'none' with other component");
3475 return tokError(
"cannot use 'none' with other component");
3486 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3487 "'provenance' or 'read_provenance'");
3490 SeenComponent =
true;
3498 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3511bool LLParser::parseOptionalOperandBundles(
3513 LocTy BeginLoc = Lex.getLoc();
3519 if (!BundleList.
empty() &&
3520 parseToken(
lltok::comma,
"expected ',' in input list"))
3524 if (parseStringConstant(
Tag))
3527 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3530 std::vector<Value *> Inputs;
3533 if (!Inputs.empty() &&
3534 parseToken(
lltok::comma,
"expected ',' in input list"))
3538 Value *Input =
nullptr;
3542 if (parseMetadataAsValue(Input, PFS))
3544 }
else if (parseValue(Ty, Input, PFS)) {
3547 Inputs.push_back(Input);
3555 if (BundleList.
empty())
3556 return error(BeginLoc,
"operand bundle set must not be empty");
3563 unsigned NextID,
unsigned ID) {
3565 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3566 Twine(NextID) +
"' or greater");
3583 unsigned CurValID = 0;
3597 LocTy TypeLoc = Lex.getLoc();
3598 Type *ArgTy =
nullptr;
3599 AttrBuilder
Attrs(M->getContext());
3600 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3604 return error(TypeLoc,
"argument can not have void type");
3609 bool Unnamed =
false;
3611 Name = Lex.getStrVal();
3612 IdentStart = getTokLineColumnPos();
3614 IdentEnd = getPrevTokEndLineColumnPos();
3618 ArgID = Lex.getUIntVal();
3619 IdentStart = getTokLineColumnPos();
3620 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3623 IdentEnd = getPrevTokEndLineColumnPos();
3629 CurValID = ArgID + 1;
3633 return error(TypeLoc,
"invalid type for function argument");
3637 Unnamed ? std::nullopt
3638 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3643 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3648bool LLParser::parseFunctionType(
Type *&Result) {
3652 return tokError(
"invalid function return type");
3656 SmallVector<unsigned> UnnamedArgNums;
3657 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3661 for (
const ArgInfo &Arg : ArgList) {
3662 if (!Arg.Name.empty())
3663 return error(Arg.Loc,
"argument name invalid in function type");
3664 if (Arg.Attrs.hasAttributes())
3665 return error(Arg.Loc,
"argument attributes invalid in function type");
3669 for (
const ArgInfo &Arg : ArgList)
3678bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3680 if (parseStructBody(Elts))
3688bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3689 std::pair<Type *, LocTy> &Entry,
3693 return error(TypeLoc,
"redefinition of type");
3699 Entry.second = SMLoc();
3704 ResultTy =
Entry.first;
3716 return error(TypeLoc,
"forward references to non-struct type");
3720 return parseArrayVectorType(ResultTy,
true);
3721 return parseType(ResultTy);
3725 Entry.second = SMLoc();
3734 if (parseStructBody(Body) ||
3735 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3739 return tokError(
toString(std::move(
E)));
3759 LocTy EltTyLoc = Lex.getLoc();
3766 return error(EltTyLoc,
"invalid element type for struct");
3769 EltTyLoc = Lex.getLoc();
3774 return error(EltTyLoc,
"invalid element type for struct");
3779 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3788bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3789 bool Scalable =
false;
3793 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3799 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3800 Lex.getAPSIntVal().getBitWidth() > 64)
3801 return tokError(
"expected number in address space");
3803 LocTy SizeLoc = Lex.getLoc();
3804 uint64_t
Size = Lex.getAPSIntVal().getZExtValue();
3807 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3810 LocTy TypeLoc = Lex.getLoc();
3811 Type *EltTy =
nullptr;
3812 if (parseType(EltTy))
3816 "expected end of sequential type"))
3821 return error(SizeLoc,
"zero element vector is illegal");
3823 return error(SizeLoc,
"size too large for vector");
3825 return error(TypeLoc,
"invalid vector element type");
3829 return error(TypeLoc,
"invalid array element type");
3846bool LLParser::parseTargetExtType(
Type *&Result) {
3851 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3852 parseStringConstant(TypeName))
3859 SmallVector<unsigned> IntParams;
3860 bool SeenInt =
false;
3867 if (parseUInt32(IntVal))
3870 }
else if (SeenInt) {
3873 return tokError(
"expected uint32 param");
3876 if (parseType(TypeParam,
true))
3882 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3887 if (
auto E = TTy.takeError())
3888 return tokError(
toString(std::move(
E)));
3901 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3904 auto It = UnnamedArgNums.
begin();
3907 unsigned ArgNum = *It++;
3908 NumberedVals.add(ArgNum, &A);
3913LLParser::PerFunctionState::~PerFunctionState() {
3916 for (
const auto &P : ForwardRefVals) {
3919 P.second.first->replaceAllUsesWith(
3921 P.second.first->deleteValue();
3924 for (
const auto &P : ForwardRefValIDs) {
3927 P.second.first->replaceAllUsesWith(
3929 P.second.first->deleteValue();
3933bool LLParser::PerFunctionState::finishFunction() {
3934 if (!ForwardRefVals.empty())
3935 return P.error(ForwardRefVals.begin()->second.second,
3936 "use of undefined value '%" + ForwardRefVals.begin()->first +
3938 if (!ForwardRefValIDs.empty())
3939 return P.error(ForwardRefValIDs.begin()->second.second,
3940 "use of undefined value '%" +
3941 Twine(ForwardRefValIDs.begin()->first) +
"'");
3948Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
3951 Value *Val =
F.getValueSymbolTable()->lookup(Name);
3956 auto I = ForwardRefVals.find(Name);
3957 if (
I != ForwardRefVals.end())
3958 Val =
I->second.first;
3963 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
3967 P.error(Loc,
"invalid use of a non-first-class type");
3978 if (FwdVal->
getName() != Name) {
3979 P.error(Loc,
"name is too long which can result in name collisions, "
3980 "consider making the name shorter or "
3981 "increasing -non-global-value-max-name-size");
3985 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3989Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
3991 Value *Val = NumberedVals.get(
ID);
3996 auto I = ForwardRefValIDs.find(
ID);
3997 if (
I != ForwardRefValIDs.end())
3998 Val =
I->second.first;
4003 return P.checkValidVariableType(Loc,
"%" + Twine(
ID), Ty, Val);
4006 P.error(Loc,
"invalid use of a non-first-class type");
4018 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
4024bool LLParser::PerFunctionState::setInstName(
int NameID,
4025 const std::string &NameStr,
4026 LocTy NameLoc, Instruction *Inst) {
4029 if (NameID != -1 || !NameStr.empty())
4030 return P.error(NameLoc,
"instructions returning void cannot have a name");
4036 if (NameStr.empty()) {
4039 NameID = NumberedVals.getNext();
4041 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4045 auto FI = ForwardRefValIDs.find(NameID);
4046 if (FI != ForwardRefValIDs.end()) {
4049 return P.error(NameLoc,
"instruction forward referenced with type '" +
4053 Sentinel->replaceAllUsesWith(Inst);
4055 ForwardRefValIDs.erase(FI);
4058 NumberedVals.add(NameID, Inst);
4063 auto FI = ForwardRefVals.find(NameStr);
4064 if (FI != ForwardRefVals.end()) {
4067 return P.error(NameLoc,
"instruction forward referenced with type '" +
4071 Sentinel->replaceAllUsesWith(Inst);
4073 ForwardRefVals.erase(FI);
4079 if (Inst->
getName() != NameStr)
4080 return P.error(NameLoc,
"multiple definition of local value named '" +
4087BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4101BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4102 int NameID,
LocTy Loc) {
4106 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4109 NameID = NumberedVals.getNext();
4111 BB = getBB(NameID, Loc);
4113 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4117 BB = getBB(Name, Loc);
4119 P.error(Loc,
"unable to create block named '" + Name +
"'");
4130 ForwardRefValIDs.erase(NameID);
4131 NumberedVals.add(NameID, BB);
4134 ForwardRefVals.erase(Name);
4151bool LLParser::parseValID(ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4152 ID.Loc = Lex.getLoc();
4153 switch (Lex.getKind()) {
4155 return tokError(
"expected value token");
4157 ID.UIntVal = Lex.getUIntVal();
4161 ID.StrVal = Lex.getStrVal();
4165 ID.UIntVal = Lex.getUIntVal();
4169 ID.StrVal = Lex.getStrVal();
4173 ID.APSIntVal = Lex.getAPSIntVal();
4177 ID.APFloatVal = Lex.getAPFloatVal();
4183 return error(
ID.Loc,
"unexpected floating-point literal");
4185 return error(
ID.Loc,
"floating-point constant invalid for type");
4190 "Invalid float strings should be caught by the lexer");
4195 return error(
ID.Loc,
"floating-point constant overflowed type");
4197 return error(
ID.Loc,
"floating-point constant underflowed type");
4203 return error(
ID.Loc,
"unexpected floating-point literal");
4205 const APInt &
Bits = Lex.getAPSIntVal();
4207 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4208 ID.APFloatVal =
APFloat(Semantics, Bits);
4230 if (parseGlobalValueVector(Elts) ||
4231 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4234 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4235 ID.UIntVal = Elts.
size();
4236 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4237 Elts.
size() *
sizeof(Elts[0]));
4248 LocTy FirstEltLoc = Lex.getLoc();
4249 if (parseGlobalValueVector(Elts) ||
4251 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4255 if (isPackedStruct) {
4256 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4257 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4258 Elts.
size() *
sizeof(Elts[0]));
4259 ID.UIntVal = Elts.
size();
4265 return error(
ID.Loc,
"constant vector must not be empty");
4267 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4268 !Elts[0]->
getType()->isFloatingPointTy() &&
4272 "vector elements must have integer, byte, pointer or floating point "
4276 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4278 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4279 " is not of type '" +
4289 LocTy FirstEltLoc = Lex.getLoc();
4290 if (parseGlobalValueVector(Elts) ||
4302 if (!Elts[0]->
getType()->isFirstClassType())
4303 return error(FirstEltLoc,
"invalid array element type: " +
4309 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4311 return error(FirstEltLoc,
"array element #" + Twine(i) +
4312 " is not of type '" +
4324 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4333 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4336 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4339 parseStringConstant(
ID.StrVal) ||
4340 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4343 ID.StrVal2 = Lex.getStrVal();
4344 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4345 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4356 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4357 parseValID(Fn, PFS) ||
4359 "expected comma in block address expression") ||
4360 parseValID(Label, PFS) ||
4361 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4365 return error(Fn.
Loc,
"expected function name in blockaddress");
4367 return error(
Label.Loc,
"expected basic block name in blockaddress");
4370 GlobalValue *GV =
nullptr;
4372 GV = NumberedVals.get(Fn.
UIntVal);
4373 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4374 GV = M->getNamedValue(Fn.
StrVal);
4380 return error(Fn.
Loc,
"expected function name in blockaddress");
4382 if (
F->isDeclaration())
4383 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4388 GlobalValue *&FwdRef =
4389 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4397 "type of blockaddress must be a pointer and not '" +
4402 FwdDeclAS = PFS->getFunction().getAddressSpace();
4406 FwdRef =
new GlobalVariable(
4411 ID.ConstantVal = FwdRef;
4419 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4421 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4423 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4425 return error(
Label.Loc,
"referenced value is not a basic block");
4428 return error(
Label.Loc,
"cannot take address of numeric label after "
4429 "the function is defined");
4431 F->getValueSymbolTable()->lookup(
Label.StrVal));
4433 return error(
Label.Loc,
"referenced value is not a basic block");
4447 if (parseValID(Fn, PFS))
4452 "expected global value name in dso_local_equivalent");
4455 GlobalValue *GV =
nullptr;
4457 GV = NumberedVals.get(Fn.
UIntVal);
4458 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4459 GV = M->getNamedValue(Fn.
StrVal);
4465 ? ForwardRefDSOLocalEquivalentIDs
4466 : ForwardRefDSOLocalEquivalentNames;
4467 GlobalValue *&FwdRef = FwdRefMap[Fn];
4474 ID.ConstantVal = FwdRef;
4480 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4481 "in dso_local_equivalent");
4492 if (parseValID(
ID, PFS))
4496 return error(
ID.Loc,
"expected global value name in no_cfi");
4508 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4509 *DeactivationSymbol =
nullptr;
4512 "expected '(' in constant ptrauth expression") ||
4513 parseGlobalTypeAndValue(Ptr) ||
4515 "expected comma in constant ptrauth expression") ||
4516 parseGlobalTypeAndValue(
Key))
4519 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4521 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4524 parseGlobalTypeAndValue(DeactivationSymbol))
4527 "expected ')' in constant ptrauth expression"))
4531 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4534 if (!KeyC || KeyC->getBitWidth() != 32)
4535 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4537 ConstantInt *DiscC =
nullptr;
4543 "constant ptrauth integer discriminator must be i64 constant");
4549 if (!AddrDisc->getType()->isPointerTy())
4551 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4556 if (!DeactivationSymbol)
4557 DeactivationSymbol =
4559 if (!DeactivationSymbol->getType()->isPointerTy())
4561 "constant ptrauth deactivation symbol must be a pointer");
4575 unsigned Opc = Lex.getUIntVal();
4576 Type *DestTy =
nullptr;
4579 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4580 parseGlobalTypeAndValue(SrcVal) ||
4581 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4582 parseType(DestTy) ||
4583 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4586 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4595 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4597 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4599 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4601 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4603 return error(
ID.Loc,
"urem constexprs are no longer supported");
4605 return error(
ID.Loc,
"srem constexprs are no longer supported");
4607 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4609 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4611 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4613 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4615 return error(
ID.Loc,
"frem constexprs are no longer supported");
4617 return error(
ID.Loc,
"and constexprs are no longer supported");
4619 return error(
ID.Loc,
"or constexprs are no longer supported");
4621 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4623 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4625 return error(
ID.Loc,
"shl constexprs are no longer supported");
4627 return error(
ID.Loc,
"mul constexprs are no longer supported");
4629 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4631 return error(
ID.Loc,
"select constexprs are no longer supported");
4633 return error(
ID.Loc,
"zext constexprs are no longer supported");
4635 return error(
ID.Loc,
"sext constexprs are no longer supported");
4637 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4639 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4641 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4643 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4645 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4647 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4649 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4651 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4659 unsigned Opc = Lex.getUIntVal();
4662 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4663 Opc == Instruction::Mul) {
4672 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4673 parseGlobalTypeAndValue(Val0) ||
4674 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4675 parseGlobalTypeAndValue(Val1) ||
4676 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4679 return error(
ID.Loc,
"operands of constexpr must have same type");
4683 "constexpr requires integer or integer vector operands");
4694 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4697 if (parseGlobalTypeAndValue(
C))
4699 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4711 unsigned Opc = Lex.getUIntVal();
4714 bool HasInRange =
false;
4720 if (
Opc == Instruction::GetElementPtr) {
4736 return tokError(
"expected integer");
4737 InRangeStart = Lex.getAPSIntVal();
4742 return tokError(
"expected integer");
4743 InRangeEnd = Lex.getAPSIntVal();
4751 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4754 if (
Opc == Instruction::GetElementPtr) {
4755 if (parseType(Ty) ||
4756 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4760 if (parseGlobalValueVector(Elts) ||
4764 if (
Opc == Instruction::GetElementPtr) {
4765 if (Elts.
size() == 0 ||
4766 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4767 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4770 std::optional<ConstantRange>
InRange;
4772 unsigned IndexWidth =
4773 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4774 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4775 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4776 if (InRangeStart.
sge(InRangeEnd))
4777 return error(
ID.Loc,
"expected end to be larger than start");
4787 for (Constant *Val : Indices) {
4790 return error(
ID.Loc,
"getelementptr index must be an integer");
4793 if (GEPWidth && (ValNumEl != GEPWidth))
4796 "getelementptr vector index has a wrong number of elements");
4799 GEPWidth = ValNumEl;
4803 SmallPtrSet<Type*, 4> Visited;
4804 if (!Indices.empty() && !Ty->
isSized(&Visited))
4805 return error(
ID.Loc,
"base element of getelementptr must be sized");
4808 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4811 return error(
ID.Loc,
"invalid getelementptr indices");
4815 }
else if (
Opc == Instruction::ShuffleVector) {
4816 if (Elts.
size() != 3)
4817 return error(
ID.Loc,
"expected three operands to shufflevector");
4819 return error(
ID.Loc,
"invalid operands to shufflevector");
4820 SmallVector<int, 16>
Mask;
4823 }
else if (
Opc == Instruction::ExtractElement) {
4824 if (Elts.
size() != 2)
4825 return error(
ID.Loc,
"expected two operands to extractelement");
4827 return error(
ID.Loc,
"invalid extractelement operands");
4830 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4831 if (Elts.
size() != 3)
4832 return error(
ID.Loc,
"expected three operands to insertelement");
4834 return error(
ID.Loc,
"invalid insertelement operands");
4849bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4853 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4854 convertValIDToValue(Ty,
ID, V,
nullptr);
4856 return error(
ID.Loc,
"global values must be constants");
4860bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4862 return parseType(Ty) || parseGlobalValue(Ty, V);
4865bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4868 LocTy KwLoc = Lex.getLoc();
4874 return tokError(
"expected comdat variable");
4875 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4877 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4880 if (GlobalName.
empty())
4881 return tokError(
"comdat cannot be unnamed");
4882 C = getComdat(std::string(GlobalName), KwLoc);
4891bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4905 if (parseGlobalTypeAndValue(
C))
4913bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
4915 if (parseMDNodeVector(Elts))
4926bool LLParser::parseMDNode(MDNode *&
N) {
4928 return parseSpecializedMDNode(
N);
4930 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4933bool LLParser::parseMDNodeTail(MDNode *&
N) {
4936 return parseMDTuple(
N);
4939 return parseMDNodeID(
N);
4945template <
class FieldTy>
struct MDFieldImpl {
4946 typedef MDFieldImpl ImplTy;
4950 void assign(FieldTy Val) {
4952 this->Val = std::move(Val);
4955 explicit MDFieldImpl(FieldTy
Default)
4963template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4964 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4977 this->
A = std::move(
A);
4983 this->
B = std::move(
B);
4987 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4989 WhatIs(IsInvalid) {}
4992struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4999struct LineField :
public MDUnsignedField {
5000 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5003struct ColumnField :
public MDUnsignedField {
5004 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5007struct DwarfTagField :
public MDUnsignedField {
5013struct DwarfMacinfoTypeField :
public MDUnsignedField {
5019struct DwarfAttEncodingField :
public MDUnsignedField {
5020 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5023struct DwarfVirtualityField :
public MDUnsignedField {
5027struct DwarfLangField :
public MDUnsignedField {
5031struct DwarfSourceLangNameField :
public MDUnsignedField {
5032 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5035struct DwarfLangDialectField :
public MDUnsignedField {
5036 DwarfLangDialectField()
5040struct DwarfCCField :
public MDUnsignedField {
5041 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5044struct DwarfEnumKindField :
public MDUnsignedField {
5045 DwarfEnumKindField()
5050struct EmissionKindField :
public MDUnsignedField {
5051 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5054struct FixedPointKindField :
public MDUnsignedField {
5055 FixedPointKindField()
5056 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5059struct NameTableKindField :
public MDUnsignedField {
5060 NameTableKindField()
5063 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5066struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5067 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5070struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5071 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5074struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5075 MDAPSIntField() : ImplTy(
APSInt()) {}
5078struct MDSignedField :
public MDFieldImpl<int64_t> {
5082 MDSignedField(int64_t
Default = 0)
5084 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5088struct MDBoolField :
public MDFieldImpl<bool> {
5092struct MDField :
public MDFieldImpl<Metadata *> {
5095 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5098struct MDStringField :
public MDFieldImpl<MDString *> {
5099 enum class EmptyIs {
5104 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5105 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5108struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5112struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5116struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5117 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5118 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5120 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5121 bool AllowNull =
true)
5122 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5124 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5125 bool isMDField()
const {
return WhatIs == IsTypeB; }
5126 int64_t getMDSignedValue()
const {
5127 assert(isMDSignedField() &&
"Wrong field type");
5130 Metadata *getMDFieldValue()
const {
5131 assert(isMDField() &&
"Wrong field type");
5136struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5137 MDUnsignedOrMDField(uint64_t
Default = 0,
bool AllowNull =
true)
5138 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5140 MDUnsignedOrMDField(uint64_t
Default, uint64_t Max,
bool AllowNull =
true)
5141 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5143 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5144 bool isMDField()
const {
return WhatIs == IsTypeB; }
5145 uint64_t getMDUnsignedValue()
const {
5146 assert(isMDUnsignedField() &&
"Wrong field type");
5149 Metadata *getMDFieldValue()
const {
5150 assert(isMDField() &&
"Wrong field type");
5155 if (isMDUnsignedField())
5157 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5159 return getMDFieldValue();
5171 return tokError(
"expected integer");
5173 Result.assign(Lex.getAPSIntVal());
5180 MDUnsignedField &Result) {
5181 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5182 return tokError(
"expected unsigned integer");
5184 auto &U = Lex.getAPSIntVal();
5185 if (U.ugt(Result.Max))
5186 return tokError(
"value for '" + Name +
"' too large, limit is " +
5188 Result.assign(U.getZExtValue());
5189 assert(Result.Val <= Result.Max &&
"Expected value in range");
5196 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5200 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5206 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5209 return tokError(
"expected DWARF tag");
5213 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5214 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5223 DwarfMacinfoTypeField &Result) {
5225 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5228 return tokError(
"expected DWARF macinfo type");
5232 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5233 Lex.getStrVal() +
"'");
5234 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5236 Result.assign(Macinfo);
5243 DwarfVirtualityField &Result) {
5245 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5248 return tokError(
"expected DWARF virtuality code");
5252 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5253 Lex.getStrVal() +
"'");
5254 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5255 Result.assign(Virtuality);
5262 DwarfEnumKindField &Result) {
5264 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5267 return tokError(
"expected DWARF enum kind code");
5271 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5272 Lex.getStrVal() +
"'");
5273 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5274 Result.assign(EnumKind);
5282 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5285 return tokError(
"expected DWARF language");
5289 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5291 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5292 Result.assign(Lang);
5299 DwarfSourceLangNameField &Result) {
5301 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5304 return tokError(
"expected DWARF source language name");
5308 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5309 Lex.getStrVal() +
"'");
5310 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5311 Result.assign(Lang);
5318 DwarfLangDialectField &Result) {
5323 if (Lex.getAPSIntVal() == 0)
5324 return tokError(
"value for 'dialect' must be a known DWARF language "
5325 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5326 "DW_LLVM_LANG_DIALECT_tile)");
5327 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5331 return tokError(
"expected DWARF language dialect");
5333 StringRef DialectString = Lex.getStrVal();
5338 if (Dialect > Result.Max)
5339 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5340 DialectString +
"'");
5341 Result.assign(Dialect);
5349 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5352 return tokError(
"expected DWARF calling convention");
5356 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5357 Lex.getStrVal() +
"'");
5358 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5366 EmissionKindField &Result) {
5368 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5371 return tokError(
"expected emission kind");
5375 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5377 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5378 Result.assign(*Kind);
5385 FixedPointKindField &Result) {
5387 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5390 return tokError(
"expected fixed-point kind");
5394 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5396 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5397 Result.assign(*Kind);
5404 NameTableKindField &Result) {
5406 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5409 return tokError(
"expected nameTable kind");
5413 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5415 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5416 Result.assign((
unsigned)*Kind);
5423 DwarfAttEncodingField &Result) {
5425 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5428 return tokError(
"expected DWARF type attribute encoding");
5432 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5433 Lex.getStrVal() +
"'");
5434 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5435 Result.assign(Encoding);
5449 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5451 bool Res = parseUInt32(TempVal);
5457 return tokError(
"expected debug info flag");
5461 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5476 Result.assign(Combined);
5489 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5491 bool Res = parseUInt32(TempVal);
5497 return tokError(
"expected debug info flag");
5501 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5502 Lex.getStrVal() +
"'");
5516 Result.assign(Combined);
5523 return tokError(
"expected signed integer");
5525 auto &S = Lex.getAPSIntVal();
5527 return tokError(
"value for '" + Name +
"' too small, limit is " +
5530 return tokError(
"value for '" + Name +
"' too large, limit is " +
5532 Result.assign(S.getExtValue());
5533 assert(Result.Val >= Result.Min &&
"Expected value in range");
5534 assert(Result.Val <= Result.Max &&
"Expected value in range");
5541 switch (Lex.getKind()) {
5543 return tokError(
"expected 'true' or 'false'");
5545 Result.assign(
true);
5548 Result.assign(
false);
5558 if (!Result.AllowNull)
5559 return tokError(
"'" + Name +
"' cannot be null");
5561 Result.assign(
nullptr);
5566 if (parseMetadata(MD,
nullptr))
5575 MDSignedOrMDField &Result) {
5578 MDSignedField Res = Result.A;
5579 if (!parseMDField(
Loc, Name, Res)) {
5587 MDField Res = Result.B;
5588 if (!parseMDField(
Loc, Name, Res)) {
5598 MDUnsignedOrMDField &Result) {
5601 MDUnsignedField Res = Result.A;
5602 if (!parseMDField(
Loc, Name, Res)) {
5610 MDField Res = Result.B;
5611 if (!parseMDField(
Loc, Name, Res)) {
5621 LocTy ValueLoc = Lex.getLoc();
5623 if (parseStringConstant(S))
5627 switch (Result.EmptyIs) {
5628 case MDStringField::EmptyIs::Null:
5629 Result.assign(
nullptr);
5631 case MDStringField::EmptyIs::Empty:
5633 case MDStringField::EmptyIs::Error:
5634 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5645 if (parseMDNodeVector(MDs))
5648 Result.assign(std::move(MDs));
5654 ChecksumKindField &Result) {
5655 std::optional<DIFile::ChecksumKind> CSKind =
5659 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5662 Result.assign(*CSKind);
5669template <
class ParserTy>
5670bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5673 return tokError(
"expected field label here");
5682template <
class ParserTy>
5683bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5690 if (parseMDFieldsImplBody(ParseField))
5693 ClosingLoc = Lex.getLoc();
5697template <
class FieldTy>
5698bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5700 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5702 LocTy Loc = Lex.getLoc();
5704 return parseMDField(Loc, Name, Result);
5707bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5710#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5711 if (Lex.getStrVal() == #CLASS) \
5712 return parse##CLASS(N, IsDistinct);
5713#include "llvm/IR/Metadata.def"
5715 return tokError(
"expected metadata type");
5718#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5719#define NOP_FIELD(NAME, TYPE, INIT)
5720#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5722 return error(ClosingLoc, "missing required field '" #NAME "'");
5723#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5724 if (Lex.getStrVal() == #NAME) \
5725 return parseMDField(#NAME, NAME);
5726#define PARSE_MD_FIELDS() \
5727 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5730 if (parseMDFieldsImpl( \
5732 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5733 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5738 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5740#define GET_OR_DISTINCT(CLASS, ARGS) \
5741 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5746bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5747#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5748 OPTIONAL(line, LineField, ); \
5749 OPTIONAL(column, ColumnField, ); \
5750 REQUIRED(scope, MDField, ( false)); \
5751 OPTIONAL(inlinedAt, MDField, ); \
5752 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5753 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5754 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5756#undef VISIT_MD_FIELDS
5759 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5760 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5766bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5768 return tokError(
"missing 'distinct', required for !DIAssignID()");
5784bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5785#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5786 REQUIRED(tag, DwarfTagField, ); \
5787 OPTIONAL(header, MDStringField, ); \
5788 OPTIONAL(operands, MDFieldList, );
5790#undef VISIT_MD_FIELDS
5793 (Context, tag.Val, header.Val, operands.Val));
5802bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5803#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5804 OPTIONAL(name, MDStringField, ); \
5805 OPTIONAL(file, MDField, ); \
5806 OPTIONAL(line, LineField, ); \
5807 OPTIONAL(scope, MDField, ); \
5808 OPTIONAL(baseType, MDField, ); \
5809 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5810 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5811 OPTIONAL(flags, DIFlagField, ); \
5812 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5813 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5814 OPTIONAL(stride, MDSignedOrMDField, ); \
5815 OPTIONAL(bias, MDSignedOrMDField, );
5817#undef VISIT_MD_FIELDS
5819 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5820 if (Bound.isMDSignedField())
5823 if (Bound.isMDField())
5824 return Bound.getMDFieldValue();
5828 Metadata *LowerBound = convToMetadata(lowerBound);
5830 Metadata *Stride = convToMetadata(stride);
5831 Metadata *Bias = convToMetadata(bias);
5834 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5835 size.getValueAsMetadata(Context),
align.Val, flags.Val,
5836 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5845bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5846#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5847 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5848 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5849 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5850 OPTIONAL(stride, MDSignedOrMDField, );
5852#undef VISIT_MD_FIELDS
5859 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5860 if (Bound.isMDSignedField())
5863 if (Bound.isMDField())
5864 return Bound.getMDFieldValue();
5869 LowerBound = convToMetadata(lowerBound);
5871 Stride = convToMetadata(stride);
5874 (Context,
Count, LowerBound, UpperBound, Stride));
5882bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5883#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5884 OPTIONAL(count, MDSignedOrMDField, ); \
5885 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5886 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5887 OPTIONAL(stride, MDSignedOrMDField, );
5889#undef VISIT_MD_FIELDS
5891 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5892 if (Bound.isMDSignedField())
5894 Context, {dwarf::DW_OP_consts,
5895 static_cast<uint64_t
>(Bound.getMDSignedValue())});
5896 if (Bound.isMDField())
5897 return Bound.getMDFieldValue();
5902 Metadata *LowerBound = ConvToMetadata(lowerBound);
5904 Metadata *Stride = ConvToMetadata(stride);
5907 (Context,
Count, LowerBound, UpperBound, Stride));
5914bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5915#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5916 REQUIRED(name, MDStringField, ); \
5917 REQUIRED(value, MDAPSIntField, ); \
5918 OPTIONAL(isUnsigned, MDBoolField, (false));
5920#undef VISIT_MD_FIELDS
5922 if (isUnsigned.Val && value.Val.isNegative())
5923 return tokError(
"unsigned enumerator with negative value");
5928 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5940bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5941#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5942 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5943 OPTIONAL(name, MDStringField, ); \
5944 OPTIONAL(file, MDField, ); \
5945 OPTIONAL(line, LineField, ); \
5946 OPTIONAL(scope, MDField, ); \
5947 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5948 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5949 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5950 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5951 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5952 OPTIONAL(flags, DIFlagField, );
5954#undef VISIT_MD_FIELDS
5957 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
5958 size.getValueAsMetadata(Context),
align.Val, encoding.Val,
5959 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5968bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
5969#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5970 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5971 OPTIONAL(name, MDStringField, ); \
5972 OPTIONAL(file, MDField, ); \
5973 OPTIONAL(line, LineField, ); \
5974 OPTIONAL(scope, MDField, ); \
5975 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5976 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5977 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5978 OPTIONAL(flags, DIFlagField, ); \
5979 OPTIONAL(kind, FixedPointKindField, ); \
5980 OPTIONAL(factor, MDSignedField, ); \
5981 OPTIONAL(numerator, MDAPSIntField, ); \
5982 OPTIONAL(denominator, MDAPSIntField, );
5984#undef VISIT_MD_FIELDS
5987 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5988 scope.Val,
size.getValueAsMetadata(Context),
5989 align.Val, encoding.Val, flags.Val, kind.Val,
5990 factor.Val, numerator.Val, denominator.Val));
5996bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5997#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5998 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5999 OPTIONAL(name, MDStringField, ); \
6000 OPTIONAL(stringLength, MDField, ); \
6001 OPTIONAL(stringLengthExpression, MDField, ); \
6002 OPTIONAL(stringLocationExpression, MDField, ); \
6003 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6004 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6005 OPTIONAL(encoding, DwarfAttEncodingField, );
6007#undef VISIT_MD_FIELDS
6011 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
6012 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
6013 align.Val, encoding.Val));
6026bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6027#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6028 REQUIRED(tag, DwarfTagField, ); \
6029 OPTIONAL(name, MDStringField, ); \
6030 OPTIONAL(file, MDField, ); \
6031 OPTIONAL(line, LineField, ); \
6032 OPTIONAL(scope, MDField, ); \
6033 REQUIRED(baseType, MDField, ); \
6034 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6035 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6036 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6037 OPTIONAL(flags, DIFlagField, ); \
6038 OPTIONAL(extraData, MDField, ); \
6039 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6040 OPTIONAL(annotations, MDField, ); \
6041 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6042 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6043 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6044 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6045 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6047#undef VISIT_MD_FIELDS
6049 std::optional<unsigned> DWARFAddressSpace;
6050 if (dwarfAddressSpace.Val != UINT32_MAX)
6051 DWARFAddressSpace = dwarfAddressSpace.Val;
6052 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6054 PtrAuthData.emplace(
6055 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6056 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6057 ptrAuthAuthenticatesNullValues.Val);
6060 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6061 baseType.Val,
size.getValueAsMetadata(Context),
align.Val,
6062 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6063 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6067bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6068#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6069 REQUIRED(tag, DwarfTagField, ); \
6070 OPTIONAL(name, MDStringField, ); \
6071 OPTIONAL(file, MDField, ); \
6072 OPTIONAL(line, LineField, ); \
6073 OPTIONAL(scope, MDField, ); \
6074 OPTIONAL(baseType, MDField, ); \
6075 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6076 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6077 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6078 OPTIONAL(flags, DIFlagField, ); \
6079 OPTIONAL(elements, MDField, ); \
6080 OPTIONAL(runtimeLang, DwarfLangField, ); \
6081 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6082 OPTIONAL(vtableHolder, MDField, ); \
6083 OPTIONAL(templateParams, MDField, ); \
6084 OPTIONAL(identifier, MDStringField, ); \
6085 OPTIONAL(discriminator, MDField, ); \
6086 OPTIONAL(dataLocation, MDField, ); \
6087 OPTIONAL(associated, MDField, ); \
6088 OPTIONAL(allocated, MDField, ); \
6089 OPTIONAL(rank, MDSignedOrMDField, ); \
6090 OPTIONAL(annotations, MDField, ); \
6091 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6092 OPTIONAL(specification, MDField, ); \
6093 OPTIONAL(bitStride, MDField, );
6095#undef VISIT_MD_FIELDS
6098 if (rank.isMDSignedField())
6101 else if (rank.isMDField())
6102 Rank = rank.getMDFieldValue();
6104 std::optional<unsigned> EnumKind;
6106 EnumKind = enumKind.Val;
6111 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6112 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6113 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6114 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6115 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6116 dataLocation.Val, associated.Val, allocated.Val, Rank,
6117 annotations.Val, bitStride.Val)) {
6126 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6127 size.getValueAsMetadata(Context),
align.Val,
6128 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6129 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6130 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6131 allocated.Val, Rank, annotations.Val, specification.Val,
6132 num_extra_inhabitants.Val, bitStride.Val));
6136bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6137#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6138 OPTIONAL(flags, DIFlagField, ); \
6139 OPTIONAL(cc, DwarfCCField, ); \
6140 REQUIRED(types, MDField, );
6142#undef VISIT_MD_FIELDS
6145 (Context, flags.Val, cc.Val, types.Val));
6154bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6158#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6159 REQUIRED(filename, MDStringField, ); \
6160 REQUIRED(directory, MDStringField, ); \
6161 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6162 OPTIONAL(checksum, MDStringField, ); \
6163 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6165#undef VISIT_MD_FIELDS
6167 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6168 if (checksumkind.Seen && checksum.Seen)
6169 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6170 else if (checksumkind.Seen || checksum.Seen)
6171 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6173 MDString *
Source =
nullptr;
6177 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6189bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6191 return tokError(
"missing 'distinct', required for !DICompileUnit");
6193 LocTy Loc = Lex.getLoc();
6195#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6196 REQUIRED(file, MDField, ( false)); \
6197 OPTIONAL(language, DwarfLangField, ); \
6198 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6199 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6200 OPTIONAL(producer, MDStringField, ); \
6201 OPTIONAL(isOptimized, MDBoolField, ); \
6202 OPTIONAL(flags, MDStringField, ); \
6203 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6204 OPTIONAL(splitDebugFilename, MDStringField, ); \
6205 OPTIONAL(emissionKind, EmissionKindField, ); \
6206 OPTIONAL(enums, MDField, ); \
6207 OPTIONAL(retainedTypes, MDField, ); \
6208 OPTIONAL(globals, MDField, ); \
6209 OPTIONAL(imports, MDField, ); \
6210 OPTIONAL(macros, MDField, ); \
6211 OPTIONAL(dwoId, MDUnsignedField, ); \
6212 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6213 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6214 OPTIONAL(nameTableKind, NameTableKindField, ); \
6215 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6216 OPTIONAL(sysroot, MDStringField, ); \
6217 OPTIONAL(sdk, MDStringField, ); \
6218 OPTIONAL(dialect, DwarfLangDialectField, );
6220#undef VISIT_MD_FIELDS
6222 if (!language.Seen && !sourceLanguageName.Seen)
6223 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6224 "required for !DICompileUnit");
6226 if (language.Seen && sourceLanguageName.Seen)
6227 return error(Loc,
"can only specify one of 'language' and "
6228 "'sourceLanguageName' on !DICompileUnit");
6230 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6231 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6232 "'sourceLanguageName' on !DICompileUnit");
6234 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6237 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6238 : DISourceLanguageName(
6239 static_cast<uint16_t>(sourceLanguageName.Val),
6240 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6243 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6244 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6245 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6246 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6247 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6260bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6261 auto Loc = Lex.getLoc();
6262#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6263 OPTIONAL(scope, MDField, ); \
6264 OPTIONAL(name, MDStringField, ); \
6265 OPTIONAL(linkageName, MDStringField, ); \
6266 OPTIONAL(file, MDField, ); \
6267 OPTIONAL(line, LineField, ); \
6268 REQUIRED(type, MDField, ( false)); \
6269 OPTIONAL(isLocal, MDBoolField, ); \
6270 OPTIONAL(isDefinition, MDBoolField, (true)); \
6271 OPTIONAL(scopeLine, LineField, ); \
6272 OPTIONAL(containingType, MDField, ); \
6273 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6274 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6275 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6276 OPTIONAL(flags, DIFlagField, ); \
6277 OPTIONAL(spFlags, DISPFlagField, ); \
6278 OPTIONAL(isOptimized, MDBoolField, ); \
6279 OPTIONAL(unit, MDField, ); \
6280 OPTIONAL(templateParams, MDField, ); \
6281 OPTIONAL(declaration, MDField, ); \
6282 OPTIONAL(retainedNodes, MDField, ); \
6283 OPTIONAL(thrownTypes, MDField, ); \
6284 OPTIONAL(annotations, MDField, ); \
6285 OPTIONAL(targetFuncName, MDStringField, ); \
6286 OPTIONAL(keyInstructions, MDBoolField, );
6288#undef VISIT_MD_FIELDS
6293 spFlags.Seen ? spFlags.Val
6295 isOptimized.Val, virtuality.Val);
6296 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6299 "missing 'distinct', required for !DISubprogram that is a Definition");
6302 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6303 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6304 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6305 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6306 targetFuncName.Val, keyInstructions.Val));
6316bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6317#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6318 REQUIRED(scope, MDField, ( false)); \
6319 OPTIONAL(file, MDField, ); \
6320 OPTIONAL(line, LineField, ); \
6321 OPTIONAL(column, ColumnField, );
6323#undef VISIT_MD_FIELDS
6326 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6332bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6333#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6334 REQUIRED(scope, MDField, ( false)); \
6335 OPTIONAL(file, MDField, ); \
6336 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6338#undef VISIT_MD_FIELDS
6341 (Context, scope.Val,
file.Val, discriminator.Val));
6347bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6348#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6349 REQUIRED(scope, MDField, ); \
6350 OPTIONAL(declaration, MDField, ); \
6351 OPTIONAL(name, MDStringField, ); \
6352 OPTIONAL(file, MDField, ); \
6353 OPTIONAL(line, LineField, );
6355#undef VISIT_MD_FIELDS
6358 (Context, scope.Val, declaration.Val,
name.Val,
6359 file.Val, line.Val));
6365bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6366#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6367 REQUIRED(scope, MDField, ); \
6368 OPTIONAL(name, MDStringField, ); \
6369 OPTIONAL(exportSymbols, MDBoolField, );
6371#undef VISIT_MD_FIELDS
6374 (Context, scope.Val,
name.Val, exportSymbols.Val));
6381bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6382#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6383 REQUIRED(type, DwarfMacinfoTypeField, ); \
6384 OPTIONAL(line, LineField, ); \
6385 REQUIRED(name, MDStringField, ); \
6386 OPTIONAL(value, MDStringField, );
6388#undef VISIT_MD_FIELDS
6391 (Context, type.Val, line.Val,
name.Val, value.Val));
6397bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6398#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6399 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6400 OPTIONAL(line, LineField, ); \
6401 REQUIRED(file, MDField, ); \
6402 OPTIONAL(nodes, MDField, );
6404#undef VISIT_MD_FIELDS
6407 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6415bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6416#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6417 REQUIRED(scope, MDField, ); \
6418 REQUIRED(name, MDStringField, ); \
6419 OPTIONAL(configMacros, MDStringField, ); \
6420 OPTIONAL(includePath, MDStringField, ); \
6421 OPTIONAL(apinotes, MDStringField, ); \
6422 OPTIONAL(file, MDField, ); \
6423 OPTIONAL(line, LineField, ); \
6424 OPTIONAL(isDecl, MDBoolField, );
6426#undef VISIT_MD_FIELDS
6429 configMacros.Val, includePath.Val,
6430 apinotes.Val, line.Val, isDecl.Val));
6436bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6437#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6438 OPTIONAL(name, MDStringField, ); \
6439 REQUIRED(type, MDField, ); \
6440 OPTIONAL(defaulted, MDBoolField, );
6442#undef VISIT_MD_FIELDS
6445 (Context,
name.Val, type.Val, defaulted.Val));
6453bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6454#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6455 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6456 OPTIONAL(name, MDStringField, ); \
6457 OPTIONAL(type, MDField, ); \
6458 OPTIONAL(defaulted, MDBoolField, ); \
6459 REQUIRED(value, MDField, );
6462#undef VISIT_MD_FIELDS
6465 DITemplateValueParameter,
6466 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6475bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6476#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6477 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6478 OPTIONAL(scope, MDField, ); \
6479 OPTIONAL(linkageName, MDStringField, ); \
6480 OPTIONAL(file, MDField, ); \
6481 OPTIONAL(line, LineField, ); \
6482 OPTIONAL(type, MDField, ); \
6483 OPTIONAL(isLocal, MDBoolField, ); \
6484 OPTIONAL(isDefinition, MDBoolField, (true)); \
6485 OPTIONAL(templateParams, MDField, ); \
6486 OPTIONAL(declaration, MDField, ); \
6487 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6488 OPTIONAL(annotations, MDField, );
6490#undef VISIT_MD_FIELDS
6494 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6495 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6496 declaration.Val, templateParams.Val,
align.Val,
6508bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6509#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6510 REQUIRED(scope, MDField, ( false)); \
6511 OPTIONAL(name, MDStringField, ); \
6512 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6513 OPTIONAL(file, MDField, ); \
6514 OPTIONAL(line, LineField, ); \
6515 OPTIONAL(type, MDField, ); \
6516 OPTIONAL(flags, DIFlagField, ); \
6517 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6518 OPTIONAL(annotations, MDField, );
6520#undef VISIT_MD_FIELDS
6523 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6524 type.Val, arg.Val, flags.Val,
align.Val,
6531bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6532#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6533 REQUIRED(scope, MDField, ( false)); \
6534 REQUIRED(name, MDStringField, ); \
6535 REQUIRED(file, MDField, ); \
6536 REQUIRED(line, LineField, ); \
6537 OPTIONAL(column, ColumnField, ); \
6538 OPTIONAL(isArtificial, MDBoolField, ); \
6539 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6541#undef VISIT_MD_FIELDS
6543 std::optional<unsigned> CoroSuspendIdx =
6544 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6548 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6549 column.Val, isArtificial.Val, CoroSuspendIdx));
6555bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6568 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6577 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6578 Lex.getStrVal() +
"'");
6581 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6582 return tokError(
"expected unsigned integer");
6584 auto &
U = Lex.getAPSIntVal();
6586 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6600bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6602 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6605 return parseDIExpressionBody(Result, IsDistinct);
6610bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6611 assert(PFS &&
"Expected valid function state");
6622 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6636bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6638#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6639 REQUIRED(var, MDField, ); \
6640 REQUIRED(expr, MDField, );
6642#undef VISIT_MD_FIELDS
6645 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6652bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6653#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6654 OPTIONAL(name, MDStringField, ); \
6655 OPTIONAL(file, MDField, ); \
6656 OPTIONAL(line, LineField, ); \
6657 OPTIONAL(setter, MDStringField, ); \
6658 OPTIONAL(getter, MDStringField, ); \
6659 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6660 OPTIONAL(type, MDField, );
6662#undef VISIT_MD_FIELDS
6665 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6666 setter.Val, attributes.Val, type.Val));
6673bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6674#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6675 REQUIRED(tag, DwarfTagField, ); \
6676 REQUIRED(scope, MDField, ); \
6677 OPTIONAL(entity, MDField, ); \
6678 OPTIONAL(file, MDField, ); \
6679 OPTIONAL(line, LineField, ); \
6680 OPTIONAL(name, MDStringField, ); \
6681 OPTIONAL(elements, MDField, );
6683#undef VISIT_MD_FIELDS
6686 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6687 line.Val,
name.Val, elements.Val));
6691#undef PARSE_MD_FIELD
6703bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6706 if (parseMetadata(MD, &PFS))
6717bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6718 PerFunctionState *PFS) {
6721 if (parseType(Ty, TypeMsg, Loc))
6724 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6727 if (parseValue(Ty, V, PFS))
6742bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6746 if (Lex.getStrVal() ==
"DIArgList") {
6748 if (parseDIArgList(AL, PFS))
6754 if (parseSpecializedMDNode(
N)) {
6764 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6774 if (parseMDString(S))
6784 if (parseMDNodeTail(
N))
6795 PerFunctionState *PFS) {
6797 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6802 return error(
ID.Loc,
"invalid use of function-local name");
6803 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6804 return V ==
nullptr;
6807 return error(
ID.Loc,
"invalid use of function-local name");
6808 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6809 return V ==
nullptr;
6812 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6816 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6821 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6824 return V ==
nullptr;
6826 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6829 return V ==
nullptr;
6832 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
6835 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
6840 return error(
ID.Loc,
"floating point constant invalid for type");
6846 bool IsSNAN = ID.APFloatVal.isSignaling();
6849 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6851 else if (Ty->isBFloatTy())
6852 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6854 else if (Ty->isFloatTy())
6855 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6861 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6862 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6863 ID.APFloatVal.isNegative(), &Payload);
6866 V = ConstantFP::get(Context,
ID.APFloatVal);
6868 if (
V->getType() != Ty)
6869 return error(
ID.Loc,
"floating point constant does not have type '" +
6875 return error(
ID.Loc,
"null must be a pointer type");
6881 return error(
ID.Loc,
"invalid type for undef constant");
6886 return error(
ID.Loc,
"invalid empty array initializer");
6892 return error(
ID.Loc,
"invalid type for null constant");
6895 return error(
ID.Loc,
"invalid type for null constant");
6900 return error(
ID.Loc,
"invalid type for none constant");
6906 return error(
ID.Loc,
"invalid type for poison constant");
6910 if (
ID.ConstantVal->getType() != Ty)
6911 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6918 return error(
ID.Loc,
"vector constant must have vector type");
6920 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6922 "' but expected '" +
6930 if (
ST->getNumElements() !=
ID.UIntVal)
6932 "initializer with struct type has wrong # elements");
6934 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6937 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6938 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6941 "element " + Twine(i) +
6942 " of struct initializer doesn't match struct element type");
6945 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6947 return error(
ID.Loc,
"constant expression type mismatch");
6956 auto Loc = Lex.getLoc();
6957 if (parseValID(
ID,
nullptr, Ty))
6970 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6980 return error(Loc,
"expected a constant value");
6984bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6988 FileLoc
Start = getTokLineColumnPos();
6989 bool Ret = parseValID(
ID, PFS, Ty) || convertValIDToValue(Ty,
ID, V, PFS);
6990 if (!Ret && ParserContext) {
6991 FileLoc End = getPrevTokEndLineColumnPos();
6992 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6997bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6999 return parseType(Ty) || parseValue(Ty, V, PFS);
7002bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
7003 PerFunctionState &PFS) {
7006 if (parseTypeAndValue(V, PFS))
7009 return error(Loc,
"expected a basic block");
7018 if (!Name.starts_with(
"llvm.dbg."))
7021 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7022 FnID == Intrinsic::dbg_assign;
7030bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7031 unsigned &FunctionNumber,
7034 LocTy LinkageLoc = Lex.getLoc();
7036 unsigned Visibility;
7037 unsigned DLLStorageClass;
7039 AttrBuilder RetAttrs(M->getContext());
7042 Type *RetType =
nullptr;
7043 LocTy RetTypeLoc = Lex.getLoc();
7044 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7046 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7047 parseType(RetType, RetTypeLoc,
true ))
7056 return error(LinkageLoc,
"invalid linkage for function definition");
7066 return error(LinkageLoc,
"invalid linkage for function declaration");
7070 return error(LinkageLoc,
"invalid function linkage type");
7074 return error(LinkageLoc,
7075 "symbol with local linkage must have default visibility");
7078 return error(LinkageLoc,
7079 "symbol with local linkage cannot have a DLL storage class");
7082 return error(RetTypeLoc,
"invalid function return type");
7084 LocTy NameLoc = Lex.getLoc();
7086 std::string FunctionName;
7088 FunctionName = Lex.getStrVal();
7090 FunctionNumber = Lex.getUIntVal();
7091 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7095 return tokError(
"expected function name");
7101 return tokError(
"expected '(' in function argument list");
7105 AttrBuilder FuncAttrs(M->getContext());
7106 std::vector<unsigned> FwdRefAttrGrps;
7109 std::string Partition;
7110 MaybeAlign Alignment, PrefAlignment;
7113 unsigned AddrSpace = 0;
7119 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7120 parseOptionalUnnamedAddr(UnnamedAddr) ||
7121 parseOptionalProgramAddrSpace(AddrSpace) ||
7122 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7126 parseOptionalComdat(FunctionName,
C) ||
7127 parseOptionalAlignment(Alignment) ||
7128 parseOptionalPrefAlignment(PrefAlignment) ||
7129 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7133 parseGlobalTypeAndValue(PersonalityFn)))
7136 if (FuncAttrs.contains(Attribute::Builtin))
7137 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7140 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7142 FuncAttrs.removeAttribute(Attribute::Alignment);
7147 std::vector<Type*> ParamTypeList;
7150 for (
const ArgInfo &Arg : ArgList) {
7151 ParamTypeList.push_back(Arg.Ty);
7152 Attrs.push_back(Arg.Attrs);
7159 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7160 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7166 GlobalValue *FwdFn =
nullptr;
7167 if (!FunctionName.empty()) {
7170 auto FRVI = ForwardRefVals.find(FunctionName);
7171 if (FRVI != ForwardRefVals.end()) {
7172 FwdFn = FRVI->second.first;
7174 return error(FRVI->second.second,
7175 "invalid forward reference to "
7178 "' with wrong type: "
7182 ForwardRefVals.erase(FRVI);
7183 }
else if ((Fn = M->getFunction(FunctionName))) {
7185 return error(NameLoc,
7186 "invalid redefinition of function '" + FunctionName +
"'");
7187 }
else if (M->getNamedValue(FunctionName)) {
7188 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7194 if (FunctionNumber == (
unsigned)-1)
7195 FunctionNumber = NumberedVals.getNext();
7199 auto I = ForwardRefValIDs.find(FunctionNumber);
7200 if (
I != ForwardRefValIDs.end()) {
7201 FwdFn =
I->second.first;
7203 return error(NameLoc,
"type of definition and forward reference of '@" +
7204 Twine(FunctionNumber) +
7209 ForwardRefValIDs.erase(
I);
7218 if (FunctionName.empty())
7219 NumberedVals.add(FunctionNumber, Fn);
7235 if (!
GC.empty()) Fn->
setGC(GC);
7238 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7242 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7243 if (ParserContext && ArgList[i].IdentLoc)
7244 ParserContext->addInstructionOrArgumentLocation(
7245 &*ArgIt, ArgList[i].IdentLoc.value());
7247 if (ArgList[i].
Name.empty())
continue;
7250 ArgIt->
setName(ArgList[i].Name);
7252 if (ArgIt->
getName() != ArgList[i].Name)
7253 return error(ArgList[i].Loc,
7254 "redefinition of argument '%" + ArgList[i].Name +
"'");
7267 if (FunctionName.empty()) {
7269 ID.UIntVal = FunctionNumber;
7272 ID.StrVal = FunctionName;
7274 auto Blocks = ForwardRefBlockAddresses.find(
ID);
7275 if (Blocks != ForwardRefBlockAddresses.end())
7276 return error(Blocks->first.Loc,
7277 "cannot take blockaddress inside a declaration");
7281bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7283 if (FunctionNumber == -1) {
7285 ID.StrVal = std::string(F.getName());
7288 ID.UIntVal = FunctionNumber;
7291 auto Blocks = P.ForwardRefBlockAddresses.find(
ID);
7292 if (Blocks == P.ForwardRefBlockAddresses.end())
7295 for (
const auto &
I : Blocks->second) {
7296 const ValID &BBID =
I.first;
7297 GlobalValue *GV =
I.second;
7300 "Expected local id or name");
7307 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7310 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7318 P.ForwardRefBlockAddresses.erase(Blocks);
7324bool LLParser::parseFunctionBody(Function &Fn,
unsigned FunctionNumber,
7325 ArrayRef<unsigned> UnnamedArgNums) {
7327 return tokError(
"expected '{' in function body");
7330 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7334 if (PFS.resolveForwardRefBlockAddresses())
7340 return tokError(
"function body requires at least one basic block");
7344 if (parseBasicBlock(PFS))
7348 if (parseUseListOrder(&PFS))
7355 return PFS.finishFunction();
7360bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7361 FileLoc BBStart = getTokLineColumnPos();
7366 LocTy NameLoc = Lex.getLoc();
7368 Name = Lex.getStrVal();
7371 NameID = Lex.getUIntVal();
7375 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7379 std::string NameStr;
7384 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7385 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7392 if (SeenOldDbgInfoFormat)
7393 return error(Lex.getLoc(),
"debug record should not appear in a module "
7394 "containing debug info intrinsics");
7395 SeenNewDbgInfoFormat =
true;
7399 if (parseDebugRecord(DR, PFS))
7401 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7404 FileLoc InstStart = getTokLineColumnPos();
7407 LocTy NameLoc = Lex.getLoc();
7412 NameID = Lex.getUIntVal();
7414 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7417 NameStr = Lex.getStrVal();
7419 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7423 switch (parseInstruction(Inst, BB, PFS)) {
7426 case InstError:
return true;
7433 if (parseInstructionMetadata(*Inst))
7436 case InstExtraComma:
7441 if (parseInstructionMetadata(*Inst))
7447 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7451 for (DbgRecordPtr &DR : TrailingDbgRecord)
7453 TrailingDbgRecord.clear();
7454 if (ParserContext) {
7455 ParserContext->addInstructionOrArgumentLocation(
7456 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7461 ParserContext->addBlockLocation(
7462 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7464 assert(TrailingDbgRecord.empty() &&
7465 "All debug values should have been attached to an instruction.");
7474bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7477 LocTy DVRLoc = Lex.getLoc();
7479 return error(DVRLoc,
"expected debug record type here");
7480 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7481 .Case(
"declare", RecordKind::ValueKind)
7482 .Case(
"value", RecordKind::ValueKind)
7483 .Case(
"assign", RecordKind::ValueKind)
7484 .Case(
"label", RecordKind::LabelKind)
7485 .Case(
"declare_value", RecordKind::ValueKind);
7494 if (parseMDNode(Label))
7499 if (parseMDNode(DbgLoc))
7504 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7508 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7509 .Case(
"declare", LocType::Declare)
7510 .Case(
"value", LocType::Value)
7511 .Case(
"assign", LocType::Assign)
7512 .Case(
"declare_value", LocType::DeclareValue);
7520 if (parseMetadata(ValLocMD, &PFS))
7527 if (parseMDNode(Variable))
7534 if (parseMDNode(Expression))
7540 MDNode *AssignID =
nullptr;
7541 Metadata *AddressLocation =
nullptr;
7542 MDNode *AddressExpression =
nullptr;
7545 if (parseMDNode(AssignID))
7551 if (parseMetadata(AddressLocation, &PFS))
7557 if (parseMDNode(AddressExpression))
7571 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7573 PendingDbgRecords.emplace_back(DVRLoc, DR,
DebugLoc);
7582int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7583 PerFunctionState &PFS) {
7586 return tokError(
"found end of file when expecting more instructions");
7587 LocTy Loc = Lex.getLoc();
7588 unsigned KeywordVal = Lex.getUIntVal();
7593 return error(Loc,
"expected instruction opcode");
7597 return parseRet(Inst, BB, PFS);
7599 return parseBr(Inst, PFS);
7601 return parseSwitch(Inst, PFS);
7603 return parseIndirectBr(Inst, PFS);
7605 return parseInvoke(Inst, PFS);
7607 return parseResume(Inst, PFS);
7609 return parseCleanupRet(Inst, PFS);
7611 return parseCatchRet(Inst, PFS);
7613 return parseCatchSwitch(Inst, PFS);
7615 return parseCatchPad(Inst, PFS);
7617 return parseCleanupPad(Inst, PFS);
7619 return parseCallBr(Inst, PFS);
7622 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7623 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7639 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7651 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7652 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7666 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7674 return parseArithmetic(Inst, PFS, KeywordVal,
7678 if (parseLogical(Inst, PFS, KeywordVal))
7686 return parseLogical(Inst, PFS, KeywordVal);
7689 if (parseCompare(Inst, PFS, KeywordVal))
7696 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7697 int Res = parseCompare(Inst, PFS, KeywordVal);
7707 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7709 bool Res = parseCast(Inst, PFS, KeywordVal);
7719 bool Res = parseCast(Inst, PFS, KeywordVal);
7731 if (parseCast(Inst, PFS, KeywordVal))
7747 return parseCast(Inst, PFS, KeywordVal);
7751 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7752 if (parseCast(Inst, PFS, KeywordVal))
7761 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7762 int Res = parseSelect(Inst, PFS);
7768 return error(Loc,
"fast-math-flags specified for select without "
7769 "floating-point scalar or vector return type");
7776 return parseVAArg(Inst, PFS);
7778 return parseExtractElement(Inst, PFS);
7780 return parseInsertElement(Inst, PFS);
7782 return parseShuffleVector(Inst, PFS);
7784 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7785 int Res = parsePHI(Inst, PFS);
7791 return error(Loc,
"fast-math-flags specified for phi without "
7792 "floating-point scalar or vector return type");
7799 return parseLandingPad(Inst, PFS);
7801 return parseFreeze(Inst, PFS);
7813 return parseAlloc(Inst, PFS);
7815 return parseLoad(Inst, PFS);
7817 return parseStore(Inst, PFS);
7819 return parseCmpXchg(Inst, PFS);
7821 return parseAtomicRMW(Inst, PFS);
7823 return parseFence(Inst, PFS);
7825 return parseGetElementPtr(Inst, PFS);
7827 return parseExtractValue(Inst, PFS);
7829 return parseInsertValue(Inst, PFS);
7834bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7835 if (
Opc == Instruction::FCmp) {
7836 switch (Lex.getKind()) {
7838 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7857 switch (Lex.getKind()) {
7859 return tokError(
"expected icmp predicate (e.g. 'eq')");
7883bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7884 PerFunctionState &PFS) {
7885 SMLoc TypeLoc = Lex.getLoc();
7887 if (parseType(Ty,
true ))
7890 Type *ResType = PFS.getFunction().getReturnType();
7894 return error(TypeLoc,
"value doesn't match function result type '" +
7902 if (parseValue(Ty, RV, PFS))
7906 return error(TypeLoc,
"value doesn't match function result type '" +
7916bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7920 if (parseTypeAndValue(Op0, Loc, PFS))
7929 return error(Loc,
"branch condition must have 'i1' type");
7931 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7932 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7933 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7934 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7946bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7947 LocTy CondLoc, BBLoc;
7950 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7951 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7952 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7956 if (!
Cond->getType()->isIntegerTy())
7957 return error(CondLoc,
"switch condition must have integer type");
7960 SmallPtrSet<Value*, 32> SeenCases;
7966 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7967 parseToken(
lltok::comma,
"expected ',' after case value") ||
7968 parseTypeAndBasicBlock(DestBB, PFS))
7971 if (!SeenCases.
insert(Constant).second)
7972 return error(CondLoc,
"duplicate case value in switch");
7974 return error(CondLoc,
"case value is not a constant integer");
7982 for (
const auto &[OnVal, Dest] : Table)
7983 SI->addCase(OnVal, Dest);
7991bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7994 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7995 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7999 if (!
Address->getType()->isPointerTy())
8000 return error(AddrLoc,
"indirectbr address must have pointer type");
8003 SmallVector<BasicBlock*, 16> DestList;
8007 if (parseTypeAndBasicBlock(DestBB, PFS))
8012 if (parseTypeAndBasicBlock(DestBB, PFS))
8018 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8022 for (BasicBlock *Dest : DestList)
8032 FunctionType *&FuncTy) {
8038 for (
const ParamInfo &Arg : ArgList)
8052bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8053 LocTy CallLoc = Lex.getLoc();
8054 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8055 std::vector<unsigned> FwdRefAttrGrps;
8058 unsigned InvokeAddrSpace;
8059 Type *RetType =
nullptr;
8066 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8067 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8068 parseType(RetType, RetTypeLoc,
true ) ||
8069 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8070 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8072 parseOptionalOperandBundles(BundleList, PFS) ||
8074 parseTypeAndBasicBlock(NormalBB, PFS) ||
8076 parseTypeAndBasicBlock(UnwindBB, PFS))
8083 if (resolveFunctionType(RetType, ArgList, Ty))
8084 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8090 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8095 SmallVector<Value *, 8>
Args;
8102 for (
const ParamInfo &Arg : ArgList) {
8103 Type *ExpectedTy =
nullptr;
8106 }
else if (!Ty->isVarArg()) {
8107 return error(Arg.Loc,
"too many arguments specified");
8110 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8111 return error(Arg.Loc,
"argument is not of expected type '" +
8113 Args.push_back(Arg.V);
8118 return error(CallLoc,
"not enough parameters specified for call");
8127 II->setCallingConv(CC);
8128 II->setAttributes(PAL);
8129 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8136bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8138 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8146bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8147 PerFunctionState &PFS) {
8148 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8153 if (!
Args.empty() &&
8154 parseToken(
lltok::comma,
"expected ',' in argument list"))
8159 Type *ArgTy =
nullptr;
8160 if (parseType(ArgTy, ArgLoc))
8165 if (parseMetadataAsValue(V, PFS))
8168 if (parseValue(ArgTy, V, PFS))
8180bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8181 Value *CleanupPad =
nullptr;
8183 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8198 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8209bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8210 Value *CatchPad =
nullptr;
8212 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8219 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8220 parseTypeAndBasicBlock(BB, PFS))
8229bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8237 return tokError(
"expected scope value for catchswitch");
8242 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8248 if (parseTypeAndBasicBlock(DestBB, PFS))
8253 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8256 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8264 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8270 for (BasicBlock *DestBB : Table)
8271 CatchSwitch->addHandler(DestBB);
8278bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8279 Value *CatchSwitch =
nullptr;
8285 return tokError(
"expected scope value for catchpad");
8290 SmallVector<Value *, 8>
Args;
8291 if (parseExceptionArgs(Args, PFS))
8300bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8301 Value *ParentPad =
nullptr;
8308 return tokError(
"expected scope value for cleanuppad");
8313 SmallVector<Value *, 8>
Args;
8314 if (parseExceptionArgs(Args, PFS))
8330bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8331 unsigned Opc,
bool IsFP) {
8333 if (parseTypeAndValue(
LHS, Loc, PFS))
8340 return error(Loc,
"invalid operand type for instruction");
8350bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8351 LocTy CallLoc = Lex.getLoc();
8352 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8353 std::vector<unsigned> FwdRefAttrGrps;
8356 Type *RetType =
nullptr;
8363 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8364 parseType(RetType, RetTypeLoc,
true ) ||
8365 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8366 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8368 parseOptionalOperandBundles(BundleList, PFS) ||
8370 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8375 SmallVector<BasicBlock *, 16> IndirectDests;
8379 if (parseTypeAndBasicBlock(DestBB, PFS))
8384 if (parseTypeAndBasicBlock(DestBB, PFS))
8390 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8397 if (resolveFunctionType(RetType, ArgList, Ty))
8398 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8409 SmallVector<Value *, 8>
Args;
8416 for (
const ParamInfo &Arg : ArgList) {
8417 Type *ExpectedTy =
nullptr;
8420 }
else if (!Ty->isVarArg()) {
8421 return error(Arg.Loc,
"too many arguments specified");
8424 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8425 return error(Arg.Loc,
"argument is not of expected type '" +
8427 Args.push_back(Arg.V);
8432 return error(CallLoc,
"not enough parameters specified for call");
8444 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8458bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8459 unsigned Opc,
bool IsFP) {
8461 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8462 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8470 return error(Loc,
"invalid operand type for instruction");
8478bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8481 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8482 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8488 "instruction requires integer or integer vector operands");
8497bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8503 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8504 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8508 if (
Opc == Instruction::FCmp) {
8510 return error(Loc,
"fcmp requires floating point operands");
8513 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8516 return error(Loc,
"icmp requires integer operands");
8528bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8532 Type *DestTy =
nullptr;
8533 if (parseTypeAndValue(
Op, Loc, PFS) ||
8534 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8539 return error(Loc,
"invalid cast opcode for cast from '" +
8548bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8550 Value *Op0, *Op1, *Op2;
8551 if (parseTypeAndValue(Op0, Loc, PFS) ||
8552 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8553 parseTypeAndValue(Op1, PFS) ||
8554 parseToken(
lltok::comma,
"expected ',' after select value") ||
8555 parseTypeAndValue(Op2, PFS))
8559 return error(Loc, Reason);
8567bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8569 Type *EltTy =
nullptr;
8571 if (parseTypeAndValue(
Op, PFS) ||
8572 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8573 parseType(EltTy, TypeLoc))
8577 return error(TypeLoc,
"va_arg requires operand with first class type");
8579 Inst =
new VAArgInst(
Op, EltTy);
8585bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8588 if (parseTypeAndValue(Op0, Loc, PFS) ||
8589 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8590 parseTypeAndValue(Op1, PFS))
8594 return error(Loc,
"invalid extractelement operands");
8602bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8604 Value *Op0, *Op1, *Op2;
8605 if (parseTypeAndValue(Op0, Loc, PFS) ||
8606 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8607 parseTypeAndValue(Op1, PFS) ||
8608 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8609 parseTypeAndValue(Op2, PFS))
8613 return error(Loc,
"invalid insertelement operands");
8621bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8623 Value *Op0, *Op1, *Op2;
8624 if (parseTypeAndValue(Op0, Loc, PFS) ||
8625 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8626 parseTypeAndValue(Op1, PFS) ||
8627 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8628 parseTypeAndValue(Op2, PFS))
8632 return error(Loc,
"invalid shufflevector operands");
8634 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8640int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8644 if (parseType(Ty, TypeLoc))
8648 return error(TypeLoc,
"phi node must have first class type");
8651 bool AteExtraComma =
false;
8663 AteExtraComma =
true;
8667 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8668 parseValue(Ty, Op0, PFS) ||
8669 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8678 for (
const auto &[Val, BB] : PHIVals)
8681 return AteExtraComma ? InstExtraComma : InstNormal;
8690bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8693 if (parseType(Ty, TyLoc))
8706 return tokError(
"expected 'catch' or 'filter' clause type");
8710 if (parseTypeAndValue(V, VLoc, PFS))
8717 return error(VLoc,
"'catch' clause has an invalid type");
8720 return error(VLoc,
"'filter' clause has an invalid type");
8725 return error(VLoc,
"clause argument must be a constant");
8729 Inst = LP.release();
8735bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8738 if (parseTypeAndValue(
Op, Loc, PFS))
8741 Inst =
new FreezeInst(
Op);
8754bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8756 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8757 std::vector<unsigned> FwdRefAttrGrps;
8759 unsigned CallAddrSpace;
8761 Type *RetType =
nullptr;
8766 LocTy CallLoc = Lex.getLoc();
8770 "expected 'tail call', 'musttail call', or 'notail call'"))
8773 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8775 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8776 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8777 parseType(RetType, RetTypeLoc,
true ) ||
8778 parseValID(CalleeID, &PFS) ||
8780 PFS.getFunction().isVarArg()) ||
8781 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8782 parseOptionalOperandBundles(BundleList, PFS))
8789 if (resolveFunctionType(RetType, ArgList, Ty))
8790 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8796 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
8803 SmallVector<Value*, 8>
Args;
8809 for (
const ParamInfo &Arg : ArgList) {
8810 Type *ExpectedTy =
nullptr;
8813 }
else if (!Ty->isVarArg()) {
8814 return error(Arg.Loc,
"too many arguments specified");
8817 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8818 return error(Arg.Loc,
"argument is not of expected type '" +
8820 Args.push_back(Arg.V);
8821 Attrs.push_back(Arg.Attrs);
8825 return error(CallLoc,
"not enough parameters specified for call");
8838 return error(CallLoc,
"fast-math-flags specified for call without "
8839 "floating-point scalar or vector return type");
8846 if (SeenNewDbgInfoFormat) {
8848 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8849 "using non-intrinsic debug info");
8851 SeenOldDbgInfoFormat =
true;
8854 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8866int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8868 LocTy SizeLoc, TyLoc, ASLoc;
8869 MaybeAlign Alignment;
8870 unsigned AddrSpace = 0;
8873 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8874 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8876 if (parseType(Ty, TyLoc))
8880 return error(TyLoc,
"invalid type for alloca");
8882 bool AteExtraComma =
false;
8884 if (Lex.getKind() == lltok::kw_align) {
8885 if (parseOptionalAlignment(Alignment))
8887 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8890 ASLoc = Lex.getLoc();
8891 if (parseOptionalAddrSpace(AddrSpace))
8894 AteExtraComma =
true;
8896 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8899 if (Lex.getKind() == lltok::kw_align) {
8900 if (parseOptionalAlignment(Alignment))
8902 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8905 ASLoc = Lex.getLoc();
8906 if (parseOptionalAddrSpace(AddrSpace))
8909 AteExtraComma =
true;
8915 if (
Size && !
Size->getType()->isIntegerTy())
8916 return error(SizeLoc,
"element count must have integer type");
8918 SmallPtrSet<Type *, 4> Visited;
8919 if (!Alignment && !Ty->
isSized(&Visited))
8920 return error(TyLoc,
"Cannot allocate unsized type");
8922 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8923 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
8927 return AteExtraComma ? InstExtraComma : InstNormal;
8934int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8936 MaybeAlign Alignment;
8937 bool AteExtraComma =
false;
8938 bool isAtomic =
false;
8947 bool isVolatile =
false;
8954 LocTy ExplicitTypeLoc = Lex.getLoc();
8955 if (parseType(Ty) ||
8956 parseToken(
lltok::comma,
"expected comma after load's type") ||
8957 parseTypeAndValue(Val, Loc, PFS) ||
8958 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8959 parseOptionalCommaAlign(Alignment, AteExtraComma))
8963 return error(Loc,
"load operand must be a pointer to a first class type");
8964 if (isAtomic && !Alignment)
8965 return error(Loc,
"atomic load must have explicit non-zero alignment");
8968 return error(Loc,
"atomic load cannot use Release ordering");
8970 SmallPtrSet<Type *, 4> Visited;
8971 if (!Alignment && !Ty->
isSized(&Visited))
8972 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8974 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8975 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8976 return AteExtraComma ? InstExtraComma : InstNormal;
8984int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8986 MaybeAlign Alignment;
8987 bool AteExtraComma =
false;
8988 bool isAtomic =
false;
8997 bool isVolatile =
false;
9003 if (parseTypeAndValue(Val, Loc, PFS) ||
9004 parseToken(
lltok::comma,
"expected ',' after store operand") ||
9005 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9006 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9007 parseOptionalCommaAlign(Alignment, AteExtraComma))
9011 return error(PtrLoc,
"store operand must be a pointer");
9013 return error(Loc,
"store operand must be a first class value");
9014 if (isAtomic && !Alignment)
9015 return error(Loc,
"atomic store must have explicit non-zero alignment");
9018 return error(Loc,
"atomic store cannot use Acquire ordering");
9019 SmallPtrSet<Type *, 4> Visited;
9021 return error(Loc,
"storing unsized types is not allowed");
9023 Alignment = M->getDataLayout().getABITypeAlign(Val->
getType());
9025 Inst =
new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
9026 return AteExtraComma ? InstExtraComma : InstNormal;
9033int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9035 bool AteExtraComma =
false;
9039 bool isVolatile =
false;
9040 bool isWeak =
false;
9041 MaybeAlign Alignment;
9049 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9050 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9051 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9052 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9053 parseTypeAndValue(New, NewLoc, PFS) ||
9054 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9055 parseOrdering(FailureOrdering) ||
9056 parseOptionalCommaAlign(Alignment, AteExtraComma))
9060 return tokError(
"invalid cmpxchg success ordering");
9062 return tokError(
"invalid cmpxchg failure ordering");
9064 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9065 if (
Cmp->getType() !=
New->getType())
9066 return error(NewLoc,
"compare value and new value type do not match");
9067 if (!
New->getType()->isFirstClassType())
9068 return error(NewLoc,
"cmpxchg operand must be a first class value");
9070 const Align DefaultAlignment(
9071 PFS.getFunction().getDataLayout().getTypeStoreSize(
9074 AtomicCmpXchgInst *CXI =
9075 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9076 SuccessOrdering, FailureOrdering, SSID);
9081 return AteExtraComma ? InstExtraComma : InstNormal;
9088int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9090 bool AteExtraComma =
false;
9094 bool IsElementwise =
false;
9097 MaybeAlign Alignment;
9102 IsElementwise =
true;
9104 switch (Lex.getKind()) {
9106 return tokError(
"expected binary operation in atomicrmw");
9165 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9166 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9167 parseTypeAndValue(Val, ValLoc, PFS) ||
9168 parseScopeAndOrdering(
true , SSID, Ordering) ||
9169 parseOptionalCommaAlign(Alignment, AteExtraComma))
9173 return tokError(
"atomicrmw cannot be unordered");
9175 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9177 return error(ValLoc,
"atomicrmw operand may not be scalable");
9183 if (IsElementwise) {
9186 return error(ValLoc,
9187 "atomicrmw elementwise operand must be a fixed vector type");
9188 ScalarTy = VecTy->getElementType();
9197 " operand must be an integer, floating point, or pointer type");
9201 return error(ValLoc,
"atomicrmw " +
9203 " operand must be a floating point type");
9207 return error(ValLoc,
"atomicrmw " +
9209 " operand must be an integer");
9214 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(Val->
getType());
9216 return error(ValLoc,
9217 "atomicrmw operand must have a power-of-two byte size");
9218 const Align DefaultAlignment(
9219 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9220 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9221 Alignment.value_or(DefaultAlignment),
9222 Ordering, SSID, IsElementwise);
9225 return AteExtraComma ? InstExtraComma : InstNormal;
9230int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9233 if (parseScopeAndOrdering(
true , SSID, Ordering))
9237 return tokError(
"fence cannot be unordered");
9239 return tokError(
"fence cannot be monotonic");
9241 Inst =
new FenceInst(Context, Ordering, SSID);
9247int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9248 Value *Ptr =
nullptr;
9249 Value *Val =
nullptr;
9265 if (parseType(Ty) ||
9266 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9267 parseTypeAndValue(Ptr, Loc, PFS))
9272 if (!BasePointerType)
9273 return error(Loc,
"base of getelementptr must be a pointer");
9275 SmallVector<Value*, 16> Indices;
9276 bool AteExtraComma =
false;
9279 ElementCount GEPWidth =
BaseType->isVectorTy()
9285 AteExtraComma =
true;
9288 if (parseTypeAndValue(Val, EltLoc, PFS))
9291 return error(EltLoc,
"getelementptr index must be an integer");
9294 ElementCount ValNumEl = ValVTy->getElementCount();
9298 "getelementptr vector index has a wrong number of elements");
9299 GEPWidth = ValNumEl;
9304 SmallPtrSet<Type*, 4> Visited;
9306 return error(Loc,
"base element of getelementptr must be sized");
9310 return error(Loc,
"getelementptr cannot target structure that contains "
9311 "scalable vector type");
9314 return error(Loc,
"invalid getelementptr indices");
9317 GEP->setNoWrapFlags(NW);
9318 return AteExtraComma ? InstExtraComma : InstNormal;
9323int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9325 SmallVector<unsigned, 4> Indices;
9327 if (parseTypeAndValue(Val, Loc, PFS) ||
9328 parseIndexList(Indices, AteExtraComma))
9332 return error(Loc,
"extractvalue operand must be aggregate type");
9335 return error(Loc,
"invalid indices for extractvalue");
9337 return AteExtraComma ? InstExtraComma : InstNormal;
9342int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9344 SmallVector<unsigned, 4> Indices;
9346 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9347 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9348 parseTypeAndValue(Val1, Loc1, PFS) ||
9349 parseIndexList(Indices, AteExtraComma))
9353 return error(Loc0,
"insertvalue operand must be aggregate type");
9357 return error(Loc0,
"invalid indices for insertvalue");
9358 if (IndexedType != Val1->
getType())
9359 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9363 return AteExtraComma ? InstExtraComma : InstNormal;
9374bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9389 if (parseMetadata(MD,
nullptr))
9394 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9400bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
9402 if (!
V->hasUseList())
9405 return error(Loc,
"value has no uses");
9407 unsigned NumUses = 0;
9408 SmallDenseMap<const Use *, unsigned, 16> Order;
9409 for (
const Use &U :
V->uses()) {
9410 if (++NumUses > Indexes.
size())
9412 Order[&
U] = Indexes[NumUses - 1];
9415 return error(Loc,
"value only has one use");
9416 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9418 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9420 V->sortUseList([&](
const Use &L,
const Use &R) {
9428bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9429 SMLoc Loc = Lex.getLoc();
9433 return tokError(
"expected non-empty list of uselistorder indexes");
9440 bool IsOrdered =
true;
9441 assert(Indexes.
empty() &&
"Expected empty order vector");
9444 if (parseUInt32(Index))
9449 Max = std::max(Max, Index);
9450 IsOrdered &= Index == Indexes.
size();
9458 if (Indexes.
size() < 2)
9459 return error(Loc,
"expected >= 2 uselistorder indexes");
9462 "expected distinct uselistorder indexes in range [0, size)");
9464 return error(Loc,
"expected uselistorder indexes to change the order");
9471bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9472 SMLoc Loc = Lex.getLoc();
9477 SmallVector<unsigned, 16> Indexes;
9478 if (parseTypeAndValue(V, PFS) ||
9479 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9480 parseUseListOrderIndexes(Indexes))
9483 return sortUseListOrder(V, Indexes, Loc);
9489bool LLParser::parseModuleEntry(
unsigned ID) {
9498 parseStringConstant(Path) ||
9506 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9507 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9508 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9509 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9510 parseUInt32(Hash[4]))
9517 auto ModuleEntry = Index->addModule(Path, Hash);
9518 ModuleIdMap[
ID] = ModuleEntry->first();
9525bool LLParser::parseTypeIdEntry(
unsigned ID) {
9534 parseStringConstant(Name))
9537 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9539 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9544 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9545 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9546 for (
auto TIDRef : FwdRefTIDs->second) {
9548 "Forward referenced type id GUID expected to be 0");
9551 ForwardRefTypeIds.erase(FwdRefTIDs);
9559bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9563 parseTypeTestResolution(TIS.
TTRes))
9568 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9579 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
9585bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9594 parseStringConstant(Name))
9598 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9605 IdToIndexMapType IdToIndexMap;
9618 if (parseGVReference(VI, GVId))
9625 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9626 TI.push_back({
Offset, VI});
9634 for (
auto I : IdToIndexMap) {
9635 auto &Infos = ForwardRefValueInfos[
I.first];
9636 for (
auto P :
I.second) {
9638 "Forward referenced ValueInfo expected to be empty");
9639 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9649 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9650 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9651 for (
auto TIDRef : FwdRefTIDs->second) {
9653 "Forward referenced type id GUID expected to be 0");
9656 ForwardRefTypeIds.erase(FwdRefTIDs);
9668bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9676 switch (Lex.getKind()) {
9696 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9708 switch (Lex.getKind()) {
9723 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9736 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9749bool LLParser::parseOptionalWpdResolutions(
9750 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9758 WholeProgramDevirtResolution WPDRes;
9762 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9765 WPDResMap[
Offset] = WPDRes;
9782bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9790 switch (Lex.getKind()) {
9801 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9807 switch (Lex.getKind()) {
9815 if (parseOptionalResByArg(WPDRes.
ResByArg))
9819 return error(Lex.getLoc(),
9820 "expected optional WholeProgramDevirtResolution field");
9837bool LLParser::parseOptionalResByArg(
9838 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9846 std::vector<uint64_t>
Args;
9847 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9855 WholeProgramDevirtResolution::ByArg ByArg;
9856 switch (Lex.getKind()) {
9870 return error(Lex.getLoc(),
9871 "unexpected WholeProgramDevirtResolution::ByArg kind");
9877 switch (Lex.getKind()) {
9881 parseUInt64(ByArg.
Info))
9887 parseUInt32(ByArg.
Byte))
9893 parseUInt32(ByArg.
Bit))
9897 return error(Lex.getLoc(),
9898 "expected optional whole program devirt field");
9905 ResByArg[
Args] = ByArg;
9916bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9924 if (parseUInt64(Val))
9926 Args.push_back(Val);
9935static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9950bool LLParser::addGlobalValueToIndex(
9952 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
9957 VI = Index->getOrInsertValueInfo(GUID);
9961 auto *GV = M->getNamedValue(Name);
9963 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
9965 VI = Index->getOrInsertValueInfo(GV);
9969 "Need a source_filename to compute GUID for local");
9972 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9977 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9978 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9979 for (
auto VIRef : FwdRefVIs->second) {
9981 "Forward referenced ValueInfo expected to be empty");
9984 ForwardRefValueInfos.erase(FwdRefVIs);
9988 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9989 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9990 for (
auto AliaseeRef : FwdRefAliasees->second) {
9991 assert(!AliaseeRef.first->hasAliasee() &&
9992 "Forward referencing alias already has aliasee");
9993 assert(Summary &&
"Aliasee must be a definition");
9994 AliaseeRef.first->setAliasee(VI,
Summary.get());
9996 ForwardRefAliasees.erase(FwdRefAliasees);
10001 Index->addGlobalValueSummary(VI, std::move(Summary));
10004 if (
ID == NumberedValueInfos.size())
10005 NumberedValueInfos.push_back(VI);
10008 if (
ID > NumberedValueInfos.size())
10009 NumberedValueInfos.resize(
ID + 1);
10010 NumberedValueInfos[
ID] =
VI;
10018bool LLParser::parseSummaryIndexFlags() {
10025 if (parseUInt64(Flags))
10028 Index->setFlags(Flags);
10034bool LLParser::parseBlockCount() {
10040 uint64_t BlockCount;
10041 if (parseUInt64(BlockCount))
10044 Index->setBlockCount(BlockCount);
10052bool LLParser::parseGVEntry(
unsigned ID) {
10060 LocTy Loc = Lex.getLoc();
10063 switch (Lex.getKind()) {
10067 parseStringConstant(Name))
10073 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10077 return error(Lex.getLoc(),
"expected name or guid tag");
10100 switch (Lex.getKind()) {
10102 if (parseFunctionSummary(Name, GUID,
ID))
10106 if (parseVariableSummary(Name, GUID,
ID))
10110 if (parseAliasSummary(Name, GUID,
ID))
10114 return error(Lex.getLoc(),
"expected summary type");
10132 LocTy Loc = Lex.getLoc();
10136 StringRef ModulePath;
10137 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10140 false,
false,
false,
10142 unsigned InstCount;
10144 FunctionSummary::TypeIdInfo TypeIdInfo;
10145 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10147 std::vector<CallsiteInfo> Callsites;
10148 std::vector<AllocInfo> Allocs;
10150 FunctionSummary::FFlags FFlags = {};
10153 parseModuleReference(ModulePath) ||
10154 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10157 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10162 switch (Lex.getKind()) {
10164 if (parseOptionalFFlags(FFlags))
10168 if (parseOptionalCalls(Calls))
10172 if (parseOptionalTypeIdInfo(TypeIdInfo))
10176 if (parseOptionalRefs(Refs))
10180 if (parseOptionalParamAccesses(ParamAccesses))
10184 if (parseOptionalAllocs(Allocs))
10188 if (parseOptionalCallsites(Callsites))
10192 return error(Lex.getLoc(),
"expected optional function summary field");
10199 auto FS = std::make_unique<FunctionSummary>(
10200 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10206 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10208 FS->setModulePath(ModulePath);
10210 return addGlobalValueToIndex(Name, GUID,
10212 std::move(FS), Loc);
10220 LocTy Loc = Lex.getLoc();
10224 StringRef ModulePath;
10225 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10228 false,
false,
false,
10230 GlobalVarSummary::GVarFlags GVarFlags(
false,
10238 parseModuleReference(ModulePath) ||
10239 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10241 parseGVarFlags(GVarFlags))
10246 switch (Lex.getKind()) {
10248 if (parseOptionalVTableFuncs(VTableFuncs))
10252 if (parseOptionalRefs(Refs))
10256 return error(Lex.getLoc(),
"expected optional variable summary field");
10264 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10266 GS->setModulePath(ModulePath);
10267 GS->setVTableFuncs(std::move(VTableFuncs));
10269 return addGlobalValueToIndex(Name, GUID,
10271 std::move(GS), Loc);
10280 LocTy Loc = Lex.getLoc();
10283 StringRef ModulePath;
10284 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10287 false,
false,
false,
10291 parseModuleReference(ModulePath) ||
10292 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10298 ValueInfo AliaseeVI;
10300 auto AS = std::make_unique<AliasSummary>(GVFlags);
10301 AS->setModulePath(ModulePath);
10304 if (parseGVReference(AliaseeVI, GVId))
10309 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10311 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10312 assert(Summary &&
"Aliasee must be a definition");
10313 AS->setAliasee(AliaseeVI, Summary);
10320 return addGlobalValueToIndex(Name, GUID,
10322 std::move(AS), Loc);
10327bool LLParser::parseFlag(
unsigned &Val) {
10328 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10329 return tokError(
"expected integer");
10330 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10346bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10350 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10356 switch (Lex.getKind()) {
10359 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10365 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10371 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10377 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10383 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10389 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10395 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10401 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10407 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10413 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10418 return error(Lex.getLoc(),
"expected function flag type");
10422 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10433bool LLParser::parseOptionalCalls(
10434 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10438 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10442 IdToIndexMapType IdToIndexMap;
10451 LocTy Loc = Lex.getLoc();
10453 if (parseGVReference(VI, GVId))
10457 unsigned RelBF = 0;
10458 unsigned HasTailCall =
false;
10462 switch (Lex.getKind()) {
10465 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10471 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10476 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10480 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10487 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10497 for (
auto I : IdToIndexMap) {
10498 auto &Infos = ForwardRefValueInfos[
I.first];
10499 for (
auto P :
I.second) {
10501 "Forward referenced ValueInfo expected to be empty");
10502 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10515 switch (Lex.getKind()) {
10519 case lltok::kw_cold:
10525 case lltok::kw_hot:
10532 return error(Lex.getLoc(),
"invalid call edge hotness");
10541bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10545 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10549 IdToIndexMapType IdToIndexMap;
10553 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10558 LocTy Loc = Lex.getLoc();
10560 if (parseGVReference(VI, GVId))
10573 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10574 VTableFuncs.push_back({
VI,
Offset});
10576 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10582 for (
auto I : IdToIndexMap) {
10583 auto &Infos = ForwardRefValueInfos[
I.first];
10584 for (
auto P :
I.second) {
10586 "Forward referenced ValueInfo expected to be empty");
10587 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10591 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10598bool LLParser::parseParamNo(uint64_t &ParamNo) {
10600 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10606bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10609 auto ParseAPSInt = [&](
APSInt &Val) {
10611 return tokError(
"expected integer");
10612 Val = Lex.getAPSIntVal();
10614 Val.setIsSigned(
true);
10636bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10637 IdLocListType &IdLocList) {
10645 LocTy Loc = Lex.getLoc();
10646 if (parseGVReference(VI, GVId))
10650 IdLocList.emplace_back(GVId, Loc);
10653 parseParamNo(
Call.ParamNo) ||
10655 parseParamAccessOffset(
Call.Offsets))
10667bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10668 IdLocListType &IdLocList) {
10670 parseParamNo(
Param.ParamNo) ||
10672 parseParamAccessOffset(
Param.Use))
10681 FunctionSummary::ParamAccess::Call
Call;
10682 if (parseParamAccessCall(
Call, IdLocList))
10699bool LLParser::parseOptionalParamAccesses(
10700 std::vector<FunctionSummary::ParamAccess> &Params) {
10708 IdLocListType VContexts;
10709 size_t CallsNum = 0;
10711 FunctionSummary::ParamAccess ParamAccess;
10712 if (parseParamAccess(ParamAccess, VContexts))
10714 CallsNum += ParamAccess.
Calls.size();
10715 assert(VContexts.size() == CallsNum);
10717 Params.emplace_back(std::move(ParamAccess));
10725 IdLocListType::const_iterator ItContext = VContexts.begin();
10726 for (
auto &PA : Params) {
10727 for (
auto &
C : PA.Calls) {
10729 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10730 ItContext->second);
10734 assert(ItContext == VContexts.end());
10741bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10745 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10749 struct ValueContext {
10754 std::vector<ValueContext> VContexts;
10758 VC.Loc = Lex.getLoc();
10759 if (parseGVReference(
VC.VI,
VC.GVId))
10761 VContexts.push_back(VC);
10767 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10768 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10771 IdToIndexMapType IdToIndexMap;
10772 for (
auto &VC : VContexts) {
10777 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10783 for (
auto I : IdToIndexMap) {
10784 auto &Infos = ForwardRefValueInfos[
I.first];
10785 for (
auto P :
I.second) {
10787 "Forward referenced ValueInfo expected to be empty");
10788 Infos.emplace_back(&Refs[
P.first],
P.second);
10802bool LLParser::parseOptionalTypeIdInfo(
10803 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10812 switch (Lex.getKind()) {
10814 if (parseTypeTests(TypeIdInfo.
TypeTests))
10838 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
10842 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10851bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10859 IdToIndexMapType IdToIndexMap;
10863 unsigned ID = Lex.getUIntVal();
10864 LocTy Loc = Lex.getLoc();
10868 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10870 }
else if (parseUInt64(GUID))
10872 TypeTests.push_back(GUID);
10877 for (
auto I : IdToIndexMap) {
10878 auto &Ids = ForwardRefTypeIds[
I.first];
10879 for (
auto P :
I.second) {
10880 assert(TypeTests[
P.first] == 0 &&
10881 "Forward referenced type id GUID expected to be 0");
10882 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10886 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10894bool LLParser::parseVFuncIdList(
10895 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10896 assert(Lex.getKind() == Kind);
10903 IdToIndexMapType IdToIndexMap;
10905 FunctionSummary::VFuncId VFuncId;
10906 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10908 VFuncIdList.push_back(VFuncId);
10916 for (
auto I : IdToIndexMap) {
10917 auto &Ids = ForwardRefTypeIds[
I.first];
10918 for (
auto P :
I.second) {
10919 assert(VFuncIdList[
P.first].GUID == 0 &&
10920 "Forward referenced type id GUID expected to be 0");
10921 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10930bool LLParser::parseConstVCallList(
10932 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10933 assert(Lex.getKind() == Kind);
10940 IdToIndexMapType IdToIndexMap;
10942 FunctionSummary::ConstVCall ConstVCall;
10943 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10945 ConstVCallList.push_back(ConstVCall);
10953 for (
auto I : IdToIndexMap) {
10954 auto &Ids = ForwardRefTypeIds[
I.first];
10955 for (
auto P :
I.second) {
10956 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10957 "Forward referenced type id GUID expected to be 0");
10958 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10967bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10968 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10970 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
10974 if (parseArgs(ConstVCall.
Args))
10986bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10987 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10997 unsigned ID = Lex.getUIntVal();
10998 LocTy Loc = Lex.getLoc();
11002 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11004 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11006 parseUInt64(VFuncId.
GUID))
11012 parseUInt64(VFuncId.
Offset) ||
11024bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11034 switch (Lex.getKind()) {
11041 assert(HasLinkage &&
"Linkage not optional in summary entry");
11048 parseOptionalVisibility(Flag);
11053 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11059 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11065 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11071 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11080 if (parseOptionalImportType(Lex.getKind(), IK))
11082 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11087 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11092 return error(Lex.getLoc(),
"expected gv flag type");
11106bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11114 auto ParseRest = [
this](
unsigned int &Val) {
11118 return parseFlag(Val);
11123 switch (Lex.getKind()) {
11124 case lltok::kw_readonly:
11125 if (ParseRest(Flag))
11129 case lltok::kw_writeonly:
11130 if (ParseRest(Flag))
11135 if (ParseRest(Flag))
11140 if (ParseRest(Flag))
11145 return error(Lex.getLoc(),
"expected gvar flag type");
11153bool LLParser::parseModuleReference(StringRef &ModulePath) {
11160 unsigned ModuleID = Lex.getUIntVal();
11161 auto I = ModuleIdMap.find(ModuleID);
11163 assert(
I != ModuleIdMap.end());
11164 ModulePath =
I->second;
11170bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11173 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11177 GVId = Lex.getUIntVal();
11179 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11181 VI = NumberedValueInfos[GVId];
11198bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11202 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11214 SmallVector<uint8_t> Versions;
11217 if (parseAllocType(V))
11222 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11226 std::vector<MIBInfo> MIBs;
11227 if (parseMemProfs(MIBs))
11230 Allocs.push_back({Versions, MIBs});
11247bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11251 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11257 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11266 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11272 SmallVector<unsigned> StackIdIndices;
11276 uint64_t StackId = 0;
11277 if (parseUInt64(StackId))
11279 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11300bool LLParser::parseAllocType(uint8_t &
AllocType) {
11301 switch (Lex.getKind()) {
11308 case lltok::kw_cold:
11311 case lltok::kw_hot:
11315 return error(Lex.getLoc(),
"invalid alloc type");
11328bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11332 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11336 IdToIndexMapType IdToIndexMap;
11339 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11346 LocTy Loc = Lex.getLoc();
11348 if (parseGVReference(VI, GVId))
11352 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11358 SmallVector<unsigned> Clones;
11361 if (parseUInt32(V))
11367 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11373 SmallVector<unsigned> StackIdIndices;
11377 uint64_t StackId = 0;
11378 if (parseUInt64(StackId))
11380 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11391 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11392 Callsites.push_back({
VI, Clones, StackIdIndices});
11400 for (
auto I : IdToIndexMap) {
11401 auto &Infos = ForwardRefValueInfos[
I.first];
11402 for (
auto P :
I.second) {
11404 "Forward referenced ValueInfo expected to be empty");
11405 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11409 if (parseToken(
lltok::rparen,
"expected ')' in callsites"))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static uint64_t align(uint64_t Size)
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static SmallVector< MemoryEffects::Location, 2 > keywordToLoc(lltok::Kind Tok)
static std::optional< DenormalMode::DenormalModeKind > keywordToDenormalModeKind(lltok::Kind Tok)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
dot regions Print regions of function to dot file(with no function bodies)"
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
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.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
static SymbolRef::Type getType(const Symbol *Sym)
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static const fltSemantics & IEEEdouble()
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
opStatus
IEEE-754R 7: Default exception handling.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
APSInt extOrTrunc(uint32_t width) const
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
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)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind getKind() const
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
LLVMContext & getContext()
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
static MemoryEffectsBase readOnly()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static auto targetMemLocations()
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
A Module instance is used to store all the information related to an LLVM module.
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
constexpr const char * getPointer() const
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator find(StringRef Key)
StringMapIterBase< Comdat, false > iterator
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
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.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool 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.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
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.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool 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.
LLVM_ABI const fltSemantics & getFltSemantics() const
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
LLVM_ABI unsigned getTag(StringRef TagString)
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ 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).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ 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.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
@ X86_StdCall
stdcall is mostly used by the Win32 API.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_no_sanitize_hwaddress
@ kw_cheriot_librarycallcc
@ kw_cheriot_compartmentcalleecc
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_cheriot_compartmentcallcc
@ kw_amdgpu_gfx_whole_wave
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_dso_local_equivalent
@ kw_aarch64_sme_preservemost_from_x2
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
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.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto dyn_cast_or_null(const Y &Val)
@ 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.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
FunctionAddr VTableAddr Count
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
CaptureComponents
Components of the pointer that may be captured.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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.
IRMemLocation
The locations at which a function might access memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
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
@ NearestTiesToEven
roundTiesToEven.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
std::vector< uint64_t > Args
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
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....
unsigned NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
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::@273232264270353276247031231016211363171152164072 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.